qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list |
---|---|---|---|---|
43,533 |
<p>I'm trying to the the flv Flash player <a href="http://www.jeroenwijering.com/?item=JW_FLV_Player" rel="nofollow noreferrer">from here</a> in a windows forms application. I currently have it playing 1 .flv file with no problems but I really need to be able to play multiple files. Has anyone had experienace of using the playlists that this control offers or is there a better way to do this?</p>
|
[
{
"answer_id": 9561843,
"author": "Jas Laferriere",
"author_id": 1249024,
"author_profile": "https://Stackoverflow.com/users/1249024",
"pm_score": 0,
"selected": false,
"text": "//Load JWPlayer swf\naxShockwaveFlash1.FlashVars = \"autostart=true\";\naxShockwaveFlash1.ScaleMode = 0;\naxShockwaveFlash1.LoadMovie(0, Directory.GetCurrentDirectory() + @\"\\JWPlayer\\player.swf\");\naxShockwaveFlash1.Play();\n\n//Play new flv\naxShockwaveFlash1.CallFunction(\"<invoke name=\\\"sendEvent\\\" returntype=\\\"xml\\\">\" + \n \"<arguments><string>load</string><string>\" +\n @\"C:\\FLVFiles\\Example.flv\" +\n \"</string></arguments></invoke>\");\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4500/"
] |
43,536 |
<p>Using C# 2.0 what is the best way to implement dynamic form controls?</p>
<p>I need to provide a set of controls per data object, so should i just do it manually and lay them out while increment the top value or is there a better way?</p>
|
[
{
"answer_id": 43541,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 1,
"selected": false,
"text": "UserControl TextBox"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428/"
] |
43,569 |
<p>How to restrict the maximum number of characters that can be entered into an HTML <code><textarea></code>? I'm looking for a cross-browser solution.</p>
|
[
{
"answer_id": 43571,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 5,
"selected": true,
"text": "TEXTAREA MAXLENGTH INPUT TEXTAREA <textarea onKeyPress=\"return ( this.value.length < 50 );\"></textarea>\n onKeyPress false KeyPress TEXTAREA KeyPress onPaste <textarea onKeyPress=\"return ( this.value.length < 50 );\"\nonPaste=\"return (( this.value.length +\nwindow.clipboardData.getData('Text').length) < 50 );\"></textarea>\n onPaste clipboardData OnChange OnBlur"
},
{
"answer_id": 11957631,
"author": "indusBull",
"author_id": 854656,
"author_profile": "https://Stackoverflow.com/users/854656",
"pm_score": 3,
"selected": false,
"text": "maxlength <textarea>"
},
{
"answer_id": 23005615,
"author": "ngrashia",
"author_id": 3492139,
"author_profile": "https://Stackoverflow.com/users/3492139",
"pm_score": -1,
"selected": false,
"text": "$(function(){ \n $(\"#id\").keypress(function() { \n var maxlen = 100;\nif ($(this).val().length > maxlen) { \n return false;\n} \n})\n}); \n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3512/"
] |
43,580 |
<p>Let's say you want to save a bunch of files somewhere, for instance in BLOBs. Let's say you want to dish these files out via a web page and have the client automatically open the correct application/viewer.</p>
<p>Assumption: The browser figures out which application/viewer to use by the mime-type (content-type?) header in the HTTP response.</p>
<p>Based on that assumption, in addition to the bytes of the file, you also want to save the MIME type.</p>
<p>How would you find the MIME type of a file? I'm currently on a Mac, but this should also work on Windows. </p>
<p>Does the browser add this information when posting the file to the web page?</p>
<p>Is there a neat python library for finding this information? A WebService or (even better) a downloadable database?</p>
|
[
{
"answer_id": 43616,
"author": "akdom",
"author_id": 145,
"author_profile": "https://Stackoverflow.com/users/145",
"pm_score": 3,
"selected": false,
"text": "sys.popen('file -i ' + fileName, mode='r')"
},
{
"answer_id": 1662074,
"author": "apito",
"author_id": 180008,
"author_profile": "https://Stackoverflow.com/users/180008",
"pm_score": 3,
"selected": false,
"text": "import shlex\nimport subprocess\nmime = subprocess.Popen(\"/usr/bin/file --mime \" + shlex.quote(PATH), shell=True, \\\n stdout=subprocess.PIPE).communicate()[0]\n"
},
{
"answer_id": 2133843,
"author": "toivotuo",
"author_id": 223251,
"author_profile": "https://Stackoverflow.com/users/223251",
"pm_score": 6,
"selected": false,
"text": "import magic\nm = magic.open(magic.MAGIC_MIME)\nm.load()\nm.file(\"/tmp/document.pdf\")\n"
},
{
"answer_id": 2753385,
"author": "Simon Zimmermann",
"author_id": 230264,
"author_profile": "https://Stackoverflow.com/users/230264",
"pm_score": 9,
"selected": true,
"text": "# For MIME types\nimport magic\nmime = magic.Magic(mime=True)\nmime.from_file(\"testdata/test.pdf\") # 'application/pdf'\n"
},
{
"answer_id": 21755201,
"author": "Laxmikant Ratnaparkhi",
"author_id": 1182058,
"author_profile": "https://Stackoverflow.com/users/1182058",
"pm_score": 6,
"selected": false,
"text": ">>> from mimetypes import MimeTypes\n>>> import urllib \n>>> mime = MimeTypes()\n>>> url = urllib.pathname2url('Upload.xml')\n>>> mime_type = mime.guess_type(url)\n>>> print mime_type\n('application/xml', None)\n import mimetypes\nprint(mimetypes.guess_type(\"sample.html\"))\n"
},
{
"answer_id": 28306825,
"author": "ewr2san",
"author_id": 2883775,
"author_profile": "https://Stackoverflow.com/users/2883775",
"pm_score": 3,
"selected": false,
"text": "import magic\n\nfilename = \"./datasets/test\"\n\ndef file_mime_type(filename):\n m = magic.open(magic.MAGIC_MIME)\n m.load()\n return(m.file(filename))\n\nprint(file_mime_type(filename))\n"
},
{
"answer_id": 39356849,
"author": "Claude COULOMBE",
"author_id": 1209842,
"author_profile": "https://Stackoverflow.com/users/1209842",
"pm_score": 3,
"selected": false,
"text": "pip3 install python-magic\n brew install libmagic\n import urllib\nimport magic\nfrom urllib.request import urlopen\n\nurl = \"http://...url to the file ...\"\nrequest = urllib.request.Request(url)\nresponse = urlopen(request)\nmime_type = magic.from_buffer(response.readline())\nprint(mime_type)\n import urllib\nimport magic\nfrom urllib.request import urlopen\n\nurl = \"http://...url to the file ...\"\nrequest = urllib.request.Request(url)\nresponse = urlopen(request)\nmime_type = magic.from_buffer(response.read(128))\nprint(mime_type)\n"
},
{
"answer_id": 45770476,
"author": "Artem Bernatskyi",
"author_id": 5751147,
"author_profile": "https://Stackoverflow.com/users/5751147",
"pm_score": 0,
"selected": false,
"text": "mp3 from mutagen.mp3 import MP3, HeaderNotFoundError \n\ntry:\n audio = MP3(file)\nexcept HeaderNotFoundError:\n raise ValidationError('This file should be mp3')\n"
},
{
"answer_id": 46758932,
"author": "Gringo Suave",
"author_id": 450917,
"author_profile": "https://Stackoverflow.com/users/450917",
"pm_score": 4,
"selected": false,
"text": "pip3 install --user python-magic\n# or:\nsudo apt install python3-magic # Ubuntu distro package\n >>> import magic\n\n>>> magic.from_file('/tmp/img_3304.jpg', mime=True)\n'image/jpeg'\n"
},
{
"answer_id": 50985903,
"author": "bodo",
"author_id": 1534459,
"author_profile": "https://Stackoverflow.com/users/1534459",
"pm_score": 4,
"selected": false,
"text": "magic file libmagic file-magic man libmagic import magic\n\ndetected = magic.detect_from_filename('magic.py')\nprint 'Detected MIME type: {}'.format(detected.mime_type)\nprint 'Detected encoding: {}'.format(detected.encoding)\nprint 'Detected file type name: {}'.format(detected.name)\n Magic magic.open(flags) file-magic file python-magic file python-magic magic magic magic file-magic libmagic"
},
{
"answer_id": 56248128,
"author": "Jak Liao",
"author_id": 6016411,
"author_profile": "https://Stackoverflow.com/users/6016411",
"pm_score": 2,
"selected": false,
"text": "import mimetypes\ndef guess_type(filename, buffer=None):\nmimetype, encoding = mimetypes.guess_type(filename)\nif mimetype is None:\n try:\n import magic\n if buffer:\n mimetype = magic.from_buffer(buffer, mime=True)\n else:\n mimetype = magic.from_file(filename, mime=True)\n except ImportError:\n pass\nreturn mimetype\n"
},
{
"answer_id": 57941308,
"author": "oetzi",
"author_id": 9241362,
"author_profile": "https://Stackoverflow.com/users/9241362",
"pm_score": 3,
"selected": false,
"text": "import mimetypes\nprint(mimetypes.guess_type(\"sample.html\"))\n"
},
{
"answer_id": 62673207,
"author": "Eric McLachlan",
"author_id": 4093278,
"author_profile": "https://Stackoverflow.com/users/4093278",
"pm_score": 2,
"selected": false,
"text": "import inspect\n\ndef _test(text: str):\n from pygments.lexers import guess_lexer\n lexer = guess_lexer(text)\n mimetype = lexer.mimetypes[0] if lexer.mimetypes else None\n print(mimetype)\n\nif __name__ == \"__main__\":\n # Set the text to the actual defintion of _test(...) above\n text = inspect.getsource(_test)\n print('Text:')\n print(text)\n print()\n print('Result:')\n _test(text)\n Text:\ndef _test(text: str):\n from pygments.lexers import guess_lexer\n lexer = guess_lexer(text)\n mimetype = lexer.mimetypes[0] if lexer.mimetypes else None\n print(mimetype)\n\n\nResult:\ntext/x-python\n"
},
{
"answer_id": 66012377,
"author": "Pedro Lobito",
"author_id": 797495,
"author_profile": "https://Stackoverflow.com/users/797495",
"pm_score": 5,
"selected": false,
"text": "import mimetypes\n\nmt = mimetypes.guess_type(\"https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf\")\nif mt:\n print(\"Mime Type:\", mt[0])\nelse:\n print(\"Cannot determine Mime Type\")\n\n# Mime Type: application/pdf\n mimetypes.guess_type (type, encoding) None 'type/subtype' None True False"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43580",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
] |
43,584 |
<p>A very niche problem:</p>
<p>I sometimes (30% of the time) get an 'undefined handler' javascript error on line 3877 of the prototype.js library (version 1.6.0.2 from google: <a href="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js" rel="nofollow noreferrer">http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.2/prototype.js</a>).</p>
<p>Now on this page I have a Google Map and I use the Prototype Window library.</p>
<p>The problem occurs in IE7 and FF3.</p>
<p>This is the info FireBug gives:</p>
<pre><code>handler is undefined
? in prototype.js@3871()prototype.js (line 3877)
handler.call(element, event);
</code></pre>
<p>I switched to a local version of prototypejs and added some debugging in the offending method (createWraper) but the debugging never appears before the error...</p>
<p>I googled around and found 1 other mention of the error on the same line, but no answer so I'm posting it here where maybe, some day someone will have an answer :).</p>
|
[
{
"answer_id": 175102,
"author": "user25551",
"author_id": 25551,
"author_profile": "https://Stackoverflow.com/users/25551",
"pm_score": 4,
"selected": true,
"text": "Event.observe(document, 'myapp:application_ready', myapp.MyClass.initApp());\n Event.observe(document, 'myapp:application_ready', myapp.MyClass.initApp);\n"
},
{
"answer_id": 4789535,
"author": "Slav",
"author_id": 432573,
"author_profile": "https://Stackoverflow.com/users/432573",
"pm_score": 2,
"selected": false,
"text": "handler.call(element, event); if (handler) handler.call(element, event)"
},
{
"answer_id": 5219522,
"author": "TMN",
"author_id": 648107,
"author_profile": "https://Stackoverflow.com/users/648107",
"pm_score": 2,
"selected": false,
"text": "Event.observe(myElement, 'click', myFunction(myParameters));\n Event.observe(myElement, 'click', function() { myFunction(myParameters) });\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4512/"
] |
43,589 |
<p>I need to get the first and last day of a month in the format YYYY-MM-DD given only the month and year. Is there a good, easy way to do this?</p>
|
[
{
"answer_id": 43607,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 3,
"selected": false,
"text": "date(\"Y-M-d\", mktime(0, 0, 0, 8, 1, 2008)) $date = new DateTime(\"2008-09-01\");\n$date->modify(\"-1 day\");\necho $date->format(\"Y-m-d\");\n"
},
{
"answer_id": 43609,
"author": "Niyaz",
"author_id": 184,
"author_profile": "https://Stackoverflow.com/users/184",
"pm_score": 2,
"selected": false,
"text": "YYYY-MM-01\n <?php\n $num = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31\n echo \"There was $num days in August 2003\";\n?>\n"
},
{
"answer_id": 43610,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 7,
"selected": true,
"text": "$first = date('Y-m-d', mktime(0, 0, 0, $month, 1, $year));\n$last = date('Y-m-t', mktime(0, 0, 0, $month, 1, $year));\n"
},
{
"answer_id": 43618,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 2,
"selected": false,
"text": "date ('Y-m-d', mktime(0,0,0,MM,01,YYYY));\n date ('Y-m-d', mktime(0,0,0,MM + 1,-1,YYYY));\n date ('Y-m-d', mktime(0,0,0,$MM + 1,0,$YYYY)); // Day zero instead of -1\n"
},
{
"answer_id": 43634,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 0,
"selected": false,
"text": "date ('Y-m-d', mktime(0,0,0,$MM + 1,-1,$YYYY));\n date ('Y-m-d', mktime(0,0,0,$MM + 1,0,$YYYY)); // Day zero instead of -1\n"
},
{
"answer_id": 50065,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 0,
"selected": false,
"text": "$startDay = 1;\n\nif (date(\"m\") == 1) {\n $startMonth = 12;\n $startYear = date(\"Y\") - 1;\n\n $endMonth = 12;\n $endYear = date(\"Y\") - 1;\n}\nelse {\n $startMonth = date(\"m\") - 1;\n $startYear = date(\"Y\");\n\n $endMonth = date(\"m\") - 1;\n $endYear = date(\"Y\");\n}\n\n$endDay = date(\"d\") - 1;\n\n$startDate = date('Y-m-d', mktime(0, 0, 0, $startMonth , $startDay, $startYear));\n$endDate = date('Y-m-d', mktime(0, 0, 0, $endMonth, $endDay, $endYear));\n"
},
{
"answer_id": 9225401,
"author": "Eranda",
"author_id": 1181127,
"author_profile": "https://Stackoverflow.com/users/1181127",
"pm_score": 2,
"selected": false,
"text": "<?php\necho \"Month Start - \" . $monthStart = date(\"Y-m-1\") . \"<br/>\";\n$num = cal_days_in_month(CAL_GREGORIAN, date(\"m\"), date(\"Y\"));\necho \"Monthe End - \" . $monthEnd = date(\"Y-m-\".$num);\n?>\n"
},
{
"answer_id": 16603663,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "$dateBegin = strtotime(\"first day of last month\"); \n$dateEnd = strtotime(\"last day of last month\");\n\necho date(\"MYDATEFORMAT\", $dateBegin); \necho \"<br>\"; \necho date(\"MYDATEFORMAT\", $dateEnd);\n if (date('N', time()) == 7) {\n$dateBegin = strtotime(\"-2 weeks Monday\");\n$dateEnd = strtotime(\"last Sunday\");\n} else {\n$dateBegin = strtotime(\"Monday last week\"); \n$dateEnd = strtotime(\"Sunday last week\"); \n}\n $dateBegin = strtotime(\"1/1 last year\");\n$dateEnd = strtotime(\"12/31 this year\");\n"
},
{
"answer_id": 17627103,
"author": "Nate",
"author_id": 1205600,
"author_profile": "https://Stackoverflow.com/users/1205600",
"pm_score": 0,
"selected": false,
"text": "$numdays = date('t', mktime(0, 0, 0, $m, 1, $Y));\n"
},
{
"answer_id": 27856580,
"author": "csonuryilmaz",
"author_id": 1750142,
"author_profile": "https://Stackoverflow.com/users/1750142",
"pm_score": 0,
"selected": false,
"text": "$month = (int) date('F');\n$year = (int) date('Y');\n\ndate('Y-m-d', mktime(0, 0, 0, $month + 1, 1, $year)); //first\ndate('Y-m-d', mktime(0, 0, 0, $month + 2, 0, $year)); //last\n 2015-01-01\n2015-01-31\n"
},
{
"answer_id": 48094516,
"author": "arturwwl",
"author_id": 8367985,
"author_profile": "https://Stackoverflow.com/users/8367985",
"pm_score": 0,
"selected": false,
"text": "echo ((new DateTime(date('Y-m').'-01'))->modify('+1 month')->format('Y-m-t'));\n echo ((new DateTime(date('Y-m').'-01'))->modify('+1 month')->format('Y-m-01'));\n echo ((new DateTime())->modify('+1 month')->format('Y-m-t'));"
},
{
"answer_id": 70531006,
"author": "palmer",
"author_id": 1390834,
"author_profile": "https://Stackoverflow.com/users/1390834",
"pm_score": 0,
"selected": false,
"text": "//bad example - will be broken when generated at 30 of December (broken February)\n echo date(\"Y-m-d\", strtotime(\"now\")).\"\\n\";\n echo date(\"Y-m-d\", strtotime(\"now + 1 month\")).\"\\n\";\n echo date(\"Y-m-d\", strtotime(\"now + 2 month\")).\"\\n\";\n echo date(\"Y-m-d\", strtotime(\"now + 3 month\")).\"\\n\";\n \n//good example, you can change first day to last day or any day\n echo date(\"Y-m-d\", strtotime(\"first day of this month\")).\"\\n\";\n echo date(\"Y-m-d\", strtotime(\"first day of next month\")).\"\\n\";\n echo date(\"Y-m-d\", strtotime(\"first day of +2 month\")).\"\\n\";\n echo date(\"Y-m-d\", strtotime(\"first day of +3 month\")).\"\\n\";\n 2021-12-30\n2022-01-30\n2022-03-02\n2022-03-30\n\n2021-12-01\n2022-01-01\n2022-02-01\n2022-03-01\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43589",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
43,632 |
<p>I've seen lots of examples of making an entire regular expression case-insensitive. What I'm wondering about is having just part of the expression be case-insensitive.</p>
<p>For example, let's say I have a string like this:</p>
<pre><code>fooFOOfOoFoOBARBARbarbarbAr
</code></pre>
<p>What if I want to match all occurrences of "foo" regardless of case but I only want to match the upper-case "BAR"s?</p>
<p>The ideal solution would be something that works across regex flavors but I'm interested in hearing language-specific ones as well (Thanks <a href="https://stackoverflow.com/questions/43632/can-you-make-just-part-of-a-regex-case-insensitive#43636">Espo</a>)</p>
<p><strong><em>Edit</em></strong></p>
<p>The link Espo provided was very helpful. There's a good example in there about turning modifiers on and off within the expression.</p>
<p>For my contrived example, I can do something like this:</p>
<pre><code>(?i)foo*(?-i)|BAR
</code></pre>
<p>which makes the match case-insensitive for just the foo portion of the match.</p>
<p>That seemed to work in most regex implementations except Javascript, Python, and a few others (as Espo mentioned). </p>
<p>The big ones that I was wondering about (Perl, PHP, .NET) all support inline mode changes.</p>
|
[
{
"answer_id": 43641,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 2,
"selected": false,
"text": "(?:F|f)(?:O|o)(?:O|o)\n"
},
{
"answer_id": 58818125,
"author": "Wiktor Stribiżew",
"author_id": 3832970,
"author_profile": "https://Stackoverflow.com/users/3832970",
"pm_score": 4,
"selected": false,
"text": "(?i)te(?-i)st TEst teST TEST (?i:...) (?i: ) (?i:foo)|BAR\n - ? (?-i:...) preg_replace(\"~(?i:foo)|BAR~\", '<$0>', \"fooFOOfOoFoOBARBARbarbarbAr\") re.sub(r'(?i:foo)|BAR', r'<\\g<0>>', 'fooFOOfOoFoOBARBARbarbarbAr') re Regex.Replace(\"fooFOOfOoFoOBARBARbarbarbAr\", \"(?i:foo)|BAR\", \"<$&>\") \"fooFOOfOoFoOBARBARbarbarbAr\".replaceAll(\"(?i:foo)|BAR\", \"<$0>\") $s =~ s/(?i:foo)|BAR/<$&>/g \"fooFOOfOoFoOBARBARbarbarbAr\".gsub(/(?i:foo)|BAR/, '<\\0>') gsub(\"((?i:foo)|BAR)\", \"<\\\\1>\", \"fooFOOfOoFoOBARBARbarbarbAr\", perl=TRUE) \"fooFOOfOoFoOBARBARbarbarbAr\".replacingOccurrences(of: \"(?i:foo)|BAR\", with: \"<$0>\", options: [.regularExpression]) regexp.MustCompile(`(?i:foo)|BAR`).ReplaceAllString( \"fooFOOfOoFoOBARBARbarbarbAr\", `<${0}>`) std::regex sed -E 's/[Ff][Oo][Oo]|BAR/<&>/g' file > outfile grep -Eo '[Ff][Oo][Oo]|BAR' file grep -Po '(?i:foo)|BAR' file"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] |
43,643 |
<p>Given the code bellow, how do I style the radio buttons to be next to the labels and style the label of the selected radio button differently than the other labels?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css" rel="stylesheet">
<link href="http://yui.yahooapis.com/2.5.2/build/base/base-min.css" rel="stylesheet">
<div class="input radio">
<fieldset>
<legend>What color is the sky?</legend>
<input type="hidden" name="color" value="" id="SubmitQuestion" />
<input type="radio" name="color" id="SubmitQuestion1" value="1" />
<label for="SubmitQuestion1">A strange radient green.</label>
<input type="radio" name="color" id="SubmitQuestion2" value="2" />
<label for="SubmitQuestion2">A dark gloomy orange</label>
<input type="radio" name="color" id="SubmitQuestion3" value="3" />
<label for="SubmitQuestion3">A perfect glittering blue</label>
</fieldset>
</div></code></pre>
</div>
</div>
</p>
<p>Also let me state that I use the yui css styles as base. If you are not familir with them, they can be found here:</p>
<ul>
<li><a href="http://yui.yahooapis.com/2.5.2/build/reset-fonts-grids/reset-fonts-grids.css" rel="nofollow noreferrer">reset-fonts-grids.css</a></li>
<li><a href="http://yui.yahooapis.com/2.5.2/build/base/base-min.css" rel="nofollow noreferrer">base-min.css</a></li>
</ul>
<p>Documentation for them both here : <a href="http://developer.yahoo.com/yui/reset/" rel="nofollow noreferrer">Yahoo! UI Library</a></p>
<p>@pkaeding: Thanks. I tried some floating both thing that just looked messed up. The styling active radio button seemed to be doable with some input[type=radio]:active nomination on a google search, but I didnt get it to work properly. So the question I guess is more: Is this possible on all of todays modern browsers, and if not, what is the minimal JS needed?</p>
|
[
{
"answer_id": 43703,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 3,
"selected": false,
"text": "<style type=\"text/css\">\n.input input {\n float: left;\n}\n.input label {\n margin: 5px;\n}\n</style>\n<div class=\"input radio\">\n <fieldset>\n <legend>What color is the sky?</legend>\n <input type=\"hidden\" name=\"data[Submit][question]\" value=\"\" id=\"SubmitQuestion\" />\n\n <input type=\"radio\" name=\"data[Submit][question]\" id=\"SubmitQuestion1\" value=\"1\" />\n <label for=\"SubmitQuestion1\">A strange radient green.</label>\n\n <input type=\"radio\" name=\"data[Submit][question]\" id=\"SubmitQuestion2\" value=\"2\" />\n <label for=\"SubmitQuestion2\">A dark gloomy orange</label>\n <input type=\"radio\" name=\"data[Submit][question]\" id=\"SubmitQuestion3\" value=\"3\" />\n <label for=\"SubmitQuestion3\">A perfect glittering blue</label>\n </fieldset>\n</div>\n"
},
{
"answer_id": 44043,
"author": "Chris Zwiryk",
"author_id": 734,
"author_profile": "https://Stackoverflow.com/users/734",
"pm_score": 6,
"selected": true,
"text": "float: <br />s <style type='text/css'>\n .input input\n {\n width: 20px;\n }\n</style>\n<div class=\"input radio\">\n <fieldset>\n <legend>What color is the sky?</legend>\n <input type=\"hidden\" name=\"data[Submit][question]\" value=\"\" id=\"SubmitQuestion\" />\n\n <input type=\"radio\" name=\"data[Submit][question]\" id=\"SubmitQuestion1\" value=\"1\" />\n <label for=\"SubmitQuestion1\">A strange radient green.</label>\n <br />\n <input type=\"radio\" name=\"data[Submit][question]\" id=\"SubmitQuestion2\" value=\"2\" />\n <label for=\"SubmitQuestion2\">A dark gloomy orange</label>\n <br />\n <input type=\"radio\" name=\"data[Submit][question]\" id=\"SubmitQuestion3\" value=\"3\" />\n <label for=\"SubmitQuestion3\">A perfect glittering blue</label>\n </fieldset>\n</div>\n <label> <style type='text/css'>\n .input label.focused\n {\n background-color: #EEEEEE;\n font-style: italic;\n }\n</style>\n<script type='text/javascript' src='jquery.js'></script>\n<script type='text/javascript'>\n $(document).ready(function() {\n $('.input :radio').focus(updateSelectedStyle);\n $('.input :radio').blur(updateSelectedStyle);\n $('.input :radio').change(updateSelectedStyle);\n })\n\n function updateSelectedStyle() {\n $('.input :radio').removeClass('focused').next().removeClass('focused');\n $('.input :radio:checked').addClass('focused').next().addClass('focused');\n }\n</script>\n focus blur"
},
{
"answer_id": 44072,
"author": "Henrik Gustafsson",
"author_id": 2010,
"author_profile": "https://Stackoverflow.com/users/2010",
"pm_score": 5,
"selected": false,
"text": "input:checked + label {\n color: white;\n} \n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4013/"
] |
43,644 |
<p>I need to select data when a page is viewed and update the 'views' column is there a way to do this in one query, or do I have to use to distinct queries?</p>
|
[
{
"answer_id": 43651,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 2,
"selected": false,
"text": "Begin Tran\n\nUpdate Pages Set Views = Views + 1 Where ID = @ID\nSelect Columns From Pages Where ID = @ID\n\nCommit Tran\n"
},
{
"answer_id": 43677,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 0,
"selected": false,
"text": "UPDATE mytable\n SET views = 5\n WHERE id = 16\n RETURNING id, views, othercolumn;\n"
},
{
"answer_id": 44104,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 1,
"selected": false,
"text": "USE AdventureWorks;\nGO\nDECLARE @MyTestVar table (\n OldScrapReasonID int NOT NULL, \n NewScrapReasonID int NOT NULL, \n WorkOrderID int NOT NULL,\n ProductID int NOT NULL,\n ProductName nvarchar(50)NOT NULL);\n\nUPDATE Production.WorkOrder\nSET ScrapReasonID = 4\nOUTPUT DELETED.ScrapReasonID,\n INSERTED.ScrapReasonID, \n INSERTED.WorkOrderID,\n INSERTED.ProductID,\n p.Name\n INTO @MyTestVar\nFROM Production.WorkOrder AS wo\n INNER JOIN Production.Product AS p \n ON wo.ProductID = p.ProductID \n AND wo.ScrapReasonID= 16\n AND p.ProductID = 733;\nSELECT OldScrapReasonID, NewScrapReasonID, WorkOrderID, \n ProductID, ProductName \nFROM @MyTestVar;\nGO\n"
},
{
"answer_id": 719992,
"author": "Nathan Feger",
"author_id": 8563,
"author_profile": "https://Stackoverflow.com/users/8563",
"pm_score": 0,
"selected": false,
"text": "update tablex set y=z where a=b \\r\\n select a,b,y,z from tablex\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
43,711 |
<p>I've got some (C#) code that relies on today's date to correctly calculate things in the future. If I use today's date in the testing, I have to repeat the calculation in the test, which doesn't feel right. What's the best way to set the date to a known value within the test so that I can test that the result is a known value?</p>
|
[
{
"answer_id": 43718,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": -1,
"selected": false,
"text": "DateTime date;\n#if DEBUG\n date = new DateTime(2008, 09, 04);\n#else\n date = DateTime.Now;\n#endif\n"
},
{
"answer_id": 43720,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 8,
"selected": true,
"text": "interface IClock\n{\n DateTime Now { get; } \n}\n class SystemClock: IClock\n{\n DateTime Now { get { return DateTime.Now; } }\n}\n class StaticClock: IClock\n{\n DateTime Now { get { return new DateTime(2008, 09, 3, 9, 6, 13); } }\n}\n DateTime.Now"
},
{
"answer_id": 43721,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 2,
"selected": false,
"text": "DateTime.Now DateTime.Now IClock"
},
{
"answer_id": 43731,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 6,
"selected": false,
"text": "public static class SystemTime\n{\n public static Func<DateTime> Now = () => DateTime.Now;\n}\n"
},
{
"answer_id": 2183744,
"author": "Pawel Lesnikowski",
"author_id": 80894,
"author_profile": "https://Stackoverflow.com/users/80894",
"pm_score": 3,
"selected": false,
"text": "[Test] \npublic void CreateName_AddsCurrentTimeAtEnd() \n{\n using (Clock.NowIs(new DateTime(2010, 12, 31, 23, 59, 00)))\n {\n string name = new ReportNameService().CreateName(...);\n Assert.AreEqual(\"name 2010-12-31 23:59:00\", name);\n } \n}\n"
},
{
"answer_id": 2183833,
"author": "João Angelo",
"author_id": 204699,
"author_profile": "https://Stackoverflow.com/users/204699",
"pm_score": 4,
"selected": false,
"text": "MDateTime.NowGet = () => new DateTime(2000, 1, 1);\n"
},
{
"answer_id": 20906399,
"author": "mmilleruva",
"author_id": 1301147,
"author_profile": "https://Stackoverflow.com/users/1301147",
"pm_score": 5,
"selected": false,
"text": "public class MyClass\n{\n public string WhatsTheTime()\n {\n return DateTime.Now.ToString();\n }\n\n}\n using System;\nusing ConsoleApplication11;\nusing Microsoft.QualityTools.Testing.Fakes;\nusing Microsoft.VisualStudio.TestTools.UnitTesting;\n\nnamespace DateTimeTest\n{\n[TestClass]\npublic class UnitTest1\n{\n [TestMethod]\n public void TestWhatsTheTime()\n {\n\n using(ShimsContext.Create()){\n\n //Arrange\n System.Fakes.ShimDateTime.NowGet =\n () =>\n { return new DateTime(2010, 1, 1); };\n\n var myClass = new MyClass();\n\n //Act\n var timeString = myClass.WhatsTheTime();\n\n //Assert\n Assert.AreEqual(\"1/1/2010 12:00:00 AM\",timeString);\n\n }\n }\n}\n}\n"
},
{
"answer_id": 51064402,
"author": "Pawel Wujczyk",
"author_id": 9107834,
"author_profile": "https://Stackoverflow.com/users/9107834",
"pm_score": 1,
"selected": false,
"text": "public interface IDateTimeTools\n{\n DateTime Now { get; }\n}\n public class DateTimeTools : IDateTimeTools\n{\n public DateTime Now => DateTime.Now;\n}\n Install-Package -Id DateTimePT -ProjectName Project\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1404/"
] |
43,738 |
<p>I have a line color property in my custom grid control. I want it to default to <code>Drawing.SystemColors.InactiveBorder</code>. I tried:</p>
<pre><code>[DefaultValue(typeof(System.Drawing.SystemColors), "InactiveBorder")]
public Color LineColor { get; set; }
</code></pre>
<p>But it doesn't seem to work. How do I do that with the default value attribute?</p>
|
[
{
"answer_id": 43751,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 4,
"selected": false,
"text": "SystemColors Color SystemColors Color [DefaultValue(typeof(Color),\"InactiveBorder\")]\n"
},
{
"answer_id": 44073,
"author": "roomaroo",
"author_id": 3464,
"author_profile": "https://Stackoverflow.com/users/3464",
"pm_score": 2,
"selected": false,
"text": "class MyClass\n{\n Color lineColor = SystemColors.InactiveBorder;\n\n [DefaultValue(true)]\n public Color LineColor {\n get {\n return lineColor;\n }\n\n set {\n lineColor = value;\n }\n }\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43738",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/976/"
] |
43,765 |
<p>For my day job, I live in Emacs. Utterly. I also have become pretty dependent on CScope to help me find things in the code.</p>
<p>Normally, I have 2 windows in a split (C-x 3):
<a href="http://bitthicket.com/files/emacs-2split.JPG">alt text http://bitthicket.com/files/emacs-2split.JPG</a></p>
<p>And I use the right window for code buffers and the left window for the CScope search buffer. When you do a CScope search and select a result, it automatically updates the right-side window to show the buffer referred to by the result. This is all well and good, except that it causes me to lose my place in some other buffer that I was studying. Sometimes this is no biggie, because [C-s u] gets me back to where I was.</p>
<p>What would be better, though, is to have 3 split windows like this ([C-x 2] in the left window):
<a href="http://bitthicket.com/files/emacs-3split.jpg">alt text http://bitthicket.com/files/emacs-3split.jpg</a></p>
<p>And have the bottom left window contain the CScope search buffer, and the top left window be the only buffer that CScope ever updates. That way, I can see my CScope searches and navigate around the code without losing the buffer I'm focused on.</p>
<p>Anyone know how I can do that?</p>
|
[
{
"answer_id": 44562,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 0,
"selected": false,
"text": "*browse-buffer* [C-c C-s g] *browse-buffer* *browse-buffer*"
},
{
"answer_id": 65992,
"author": "Frank Klotz",
"author_id": 9668,
"author_profile": "https://Stackoverflow.com/users/9668",
"pm_score": 6,
"selected": true,
"text": ";; Toggle window dedication\n\n(defun toggle-window-dedicated ()\n\n\"Toggle whether the current active window is dedicated or not\"\n\n(interactive)\n\n(message \n\n (if (let (window (get-buffer-window (current-buffer)))\n\n (set-window-dedicated-p window \n\n (not (window-dedicated-p window))))\n\n \"Window '%s' is dedicated\"\n\n \"Window '%s' is normal\")\n\n (current-buffer)))\n (global-set-key [pause] 'toggle-window-dedicated)\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3279/"
] |
43,775 |
<p>Can you please tell me how much is <code>(-2) % 5</code>?
According to my Python interpreter is 3, but do you have a wise explanation for this?</p>
<p>I've read that in some languages the result can be machine-dependent, but I'm not sure though.</p>
|
[
{
"answer_id": 43794,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": true,
"text": "-2"
},
{
"answer_id": 43863,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 2,
"selected": false,
"text": "x == (x/y)*y + (x%y)\n"
},
{
"answer_id": 43916,
"author": "Jared Updike",
"author_id": 2543,
"author_profile": "https://Stackoverflow.com/users/2543",
"pm_score": 0,
"selected": false,
"text": "float x2 = x % n;\n"
},
{
"answer_id": 3224825,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 3,
"selected": false,
"text": "x == (x/y)*y + (x%y) divmod(x, y) == (x/y, x%y) >>> divmod(-2, 5)\n(-1, 3).\n divmod >>> for number in xrange(-10, 10):\n... print divmod(number, 5)\n...\n(-2, 0)\n(-2, 1)\n(-2, 2)\n(-2, 3)\n(-2, 4)\n(-1, 0)\n(-1, 1)\n(-1, 2)\n(-1, 3)\n(-1, 4)\n(0, 0)\n(0, 1)\n(0, 2)\n(0, 3)\n(0, 4)\n(1, 0)\n(1, 1)\n(1, 2)\n(1, 3)\n(1, 4)\n"
},
{
"answer_id": 5203460,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "a / b == c rem d (c * b) + d == a 0 <= r < divisor % mod rem"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1876/"
] |
43,778 |
<p><strong>Update:</strong> Check out this follow-up question: <a href="https://stackoverflow.com/questions/134581/gem-update-on-windows-is-it-broken"><strong>Gem Update on Windows - is it broken?</strong></a></p>
<hr>
<p>On Windows, when I do this:</p>
<pre><code>gem install sqlite3-ruby
</code></pre>
<p>I get the following error:</p>
<pre><code>Building native extensions. This could take a while...
ERROR: Error installing sqlite3-ruby:
ERROR: Failed to build gem native extension.
c:/ruby/bin/ruby.exe extconf.rb install sqlite3-ruby --platform Win32
checking for fdatasync() in rt.lib... no
checking for sqlite3.h... no
nmake
'nmake' is not recognized as an internal or external command,
operable program or batch file.
Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4 for inspection.
Results logged to c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4/ext/sqlite3_api/gem_make.out
</code></pre>
<p><strong>Same thing happens with the hpricot gem</strong>. I seem to remember these gems installed just fine on < 1.0 gems, but now I'm on 1.2.0, things have gone screwy.</p>
<p>I have also tried this:</p>
<pre><code>gem install sqlite3-ruby --platform Win32
</code></pre>
<p>Needless to say, this doesn't work either (same error)</p>
<p>Does anyone know what is going on here and how to fix this?</p>
<hr>
<p><strong>Update:</strong> Check out this follow-up question: <a href="https://stackoverflow.com/questions/134581/gem-update-on-windows-is-it-broken"><strong>Gem Update on Windows - is it broken?</strong></a></p>
|
[
{
"answer_id": 43840,
"author": "Charles Roper",
"author_id": 1944,
"author_profile": "https://Stackoverflow.com/users/1944",
"pm_score": 6,
"selected": true,
"text": "$ gem list --remote --all sqlite\n\n*** REMOTE GEMS ***\n\nsqlite (2.0.1, 2.0.0, 1.3.1, 1.3.0, 1.2.9.1, 1.2.0, 1.1.3, 1.1.2, 1.1.1, 1.1)\nsqlite-ruby (2.2.3, 2.2.2, 2.2.1, 2.2.0, 2.1.0, 2.0.3, 2.0.2)\nsqlite3-ruby (1.2.4, 1.2.3, 1.2.2, 1.2.1, 1.2.0, 1.1.0, 1.0.1, 1.0.0, 0.9.0, 0.6.0, 0.5.0)\n gem install sqlite3-ruby -v 1.2.3\n gem install hpricot -v 0.6\n gem update"
},
{
"answer_id": 17907570,
"author": "jiahut",
"author_id": 1517100,
"author_profile": "https://Stackoverflow.com/users/1517100",
"pm_score": 2,
"selected": false,
"text": "sqlite-dll-win32-x86-3071700.zip sqlite-autoconf-3071700.tar.gz -include\n --sqlite3.h\n --sqlite3ext.h\n-lib\n --shell.c\n --sqlite3.c\n --sqlite3.def\n --sqlite3.dll\n gem install sqlite3 --platform=ruby -- --with-sqlite3-include=path\\to\\include \n --with-sqlite3-lib=path\\to\\lib --no-ri --no-rdoc\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1944/"
] |
43,802 |
<p>I have a <code>String</code> representation of a date that I need to create a <code>Date</code> or <code>Calendar</code> object from. I've looked through <code>Date</code> and <code>Calendar</code> APIs but haven't found anything that can do this other than creating my own ugly parse method. I know there must be a way, does anyone know of a solution?</p>
|
[
{
"answer_id": 43806,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 0,
"selected": false,
"text": "DateFormat.parse(String)\n"
},
{
"answer_id": 43807,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 8,
"selected": true,
"text": "DateFormat formatter = new SimpleDateFormat(\"MM/dd/yy\");\ntry {\n Date date = formatter.parse(\"01/29/02\");\n} catch (ParseException e) {\n e.printStackTrace();\n}\n SimpleDateFormat Calendar Calendar calendar = Calendar.getInstance();\ncalendar.setTime(date);\n"
},
{
"answer_id": 43812,
"author": "Alexander Stolz",
"author_id": 2450,
"author_profile": "https://Stackoverflow.com/users/2450",
"pm_score": 0,
"selected": false,
"text": "DateFormat parse"
},
{
"answer_id": 44012,
"author": "serg10",
"author_id": 1853,
"author_profile": "https://Stackoverflow.com/users/1853",
"pm_score": 3,
"selected": false,
"text": "java.util.Date java.util.Calendar DateFormatter DateTime"
},
{
"answer_id": 33405474,
"author": "Basil Bourque",
"author_id": 642706,
"author_profile": "https://Stackoverflow.com/users/642706",
"pm_score": 4,
"selected": false,
"text": "LocalDate.parse( \"2015-01-02\" )\n LocalDate LocalDate yyyy-MM-dd LocalDate localDate = LocalDate.parse( \"2015-01-02\" );\n Locale DateTimeFormatter java.text.SimpleDateFormat parse String input = \"January 2, 2015\";\nDateTimeFormatter formatter = DateTimeFormatter.ofPattern ( \"MMMM d, yyyy\" , Locale.US );\nLocalDate localDate = LocalDate.parse ( input , formatter );\n System.out.println ( \"localDate: \" + localDate );\n DateTimeFormatter.ofLocalizedDate Locale String input = \"January 2, 2015\";\nDateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG );\nformatter = formatter.withLocale ( Locale.US );\nLocalDate localDate = LocalDate.parse ( input , formatter );\n System.out.println ( \"input: \" + input + \" | localDate: \" + localDate );\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2628/"
] |
43,803 |
<p>This is what I've got. It works. But, is there a simpler or better way?</p>
<p>ASPX Page…</p>
<pre><code><asp:Repeater ID="RepeaterBooks" runat="server">
<HeaderTemplate>
<table class="report">
<tr>
<th>Published</th>
<th>Title</th>
<th>Author</th>
<th>Price</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:Literal ID="LiteralPublished" runat="server" /></td>
<td><asp:Literal ID="LiteralTitle" runat="server" /></td>
<td><asp:Literal ID="LiteralAuthor" runat="server" /></td>
<td><asp:Literal ID="LiteralPrice" runat="server" /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</code></pre>
<p>ASPX.VB Code Behind…</p>
<pre><code>Protected Sub Page_Load( ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim db As New BookstoreDataContext
RepeaterBooks.DataSource = From b In db.Books _
Order By b.Published _
Select b
RepeaterBooks.DataBind()
End Sub
Sub RepeaterBooks_ItemDataBound( ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles RepeaterBooks.ItemDataBound
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Dim b As Book = DirectCast(e.Item.DataItem, Book)
DirectCast(e.Item.FindControl("LiteralPublished"), Literal).Text = "<nobr>" + b.Published.ToShortDateString + "</nobr>"
DirectCast(e.Item.FindControl("LiteralTitle"), Literal).Text = "<nobr>" + TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Title)) + "</nobr>"
DirectCast(e.Item.FindControl("LiteralAuthor"), Literal).Text = "<nobr>" + TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Author)) + "</nobr>"
DirectCast(e.Item.FindControl("LiteralPrice"), Literal).Text = "<nobr>" + Format(b.Price, "c") + "</nobr>"
End If
End Sub
Function TryNbsp(ByVal s As String) As String
If s = "" Then
Return "&nbsp;"
Else
Return s
End If
End Function
</code></pre>
|
[
{
"answer_id": 43818,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 2,
"selected": false,
"text": "<ItemTemplate>\n <tr>\n <td><%# Eval(\"published\") %></td>\n ...\n"
},
{
"answer_id": 43820,
"author": "mattruma",
"author_id": 1768,
"author_profile": "https://Stackoverflow.com/users/1768",
"pm_score": 1,
"selected": false,
"text": "Literals DueDate"
},
{
"answer_id": 43894,
"author": "Adam Lassek",
"author_id": 1249,
"author_profile": "https://Stackoverflow.com/users/1249",
"pm_score": 3,
"selected": true,
"text": "<table class=\"report\" id=\"bookTable\" runat=\"server\">\n <tr>\n <th>Published</th>\n <th>Title</th>\n <th>Author</th>\n <th>Price</th>\n </tr>\n </table>\n Protected Sub Page_Load( ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n If Not Page.IsPostback Then\n BuildTable()\n End If\nEnd Sub\n\nPrivate Sub BuildTable()\n Dim db As New BookstoreDataContext\n Dim bookCollection = from b in db.Books _\n Order By b.Published _\n Select b\n Dim row As HtmlTableRow\n Dim cell As HtmlTableCell\n\n For Each book As Books In bookCollection\n row = New HtmlTableRow()\n cell = New HtmlTableCell With { .InnerText = b.Published.ToShortDateString }\n row.Controls.Add(cell)\n cell = New HtmlTableCell With { .InnerText = TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Title)) }\n row.Controls.Add(cell)\n cell = New HtmlTableCell With { .InnerText = TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Author))\n row.Controls.Add(cell)\n cell = New HtmlTableCell With { .InnerText = Format(b.Price, \"c\") }\n row.Controls.Add(cell)\n bookTable.Controls.Add(row)\n Next\n"
},
{
"answer_id": 43932,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 2,
"selected": false,
"text": "<asp:ListView runat=\"server\" ID=\"ListView1\"\n DataSourceID=\"SqlDataSource1\">\n <LayoutTemplate>\n <table runat=\"server\" id=\"table1\" runat=\"server\" >\n <tr runat=\"server\" id=\"itemPlaceholder\" ></tr>\n </table>\n </LayoutTemplate>\n <ItemTemplate>\n <tr runat=\"server\">\n <td runat=\"server\">\n <asp:Label ID=\"NameLabel\" runat=\"server\"\n Text='<%#Eval(\"Name\") %>' />\n </td>\n </tr>\n </ItemTemplate>\n</asp:ListView>\n"
},
{
"answer_id": 44051,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 1,
"selected": false,
"text": "<asp:GridView runat=\"server\" DataSourceID=\"SqlDataSource1\">\n <Columns>\n <asp:BoundField HeaderText=\"Published\" DataField=\"Published\" />\n <asp:BoundField HeaderText=\"Author\" DataField=\"Author\" />\n </Columns>\n</asp:GridView>\n"
},
{
"answer_id": 44081,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 1,
"selected": false,
"text": "<asp:GridView ID=\"gvBooks\" runat=\"server\" AutoGenerateColumns=\"False\">\n <Columns>\n <asp:BoundField HeaderText=\"Published\" DataField=\"Published\" />\n <asp:BoundField HeaderText=\"Title\" DataField=\"Title\" /> \n <asp:BoundField HeaderText=\"Author\" DataField=\"Author\" />\n <asp:BoundField HeaderText=\"Price\" DataField=\"Price\" />\n </Columns>\n</asp:GridView>\n Private Sub gvBooksRowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvBooks.RowDataBound\n Select Case e.Row.RowType\n Case DataControlRowType.DataRow\n\n ''' Your code here '''\n\n End Select\nEnd Sub\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
43,808 |
<p>I have a distributed Java application running on 5 application servers. The servers all use the same Oracle 9i database running on a 6th machine.</p>
<p>The application need to prefetch a batch of 100 IDs from a sequence. It's relatively easy to do in a single-threaded, non-distributed environment, you can just issue these queries:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT seq.nextval FROM dual;
ALTER SEQUENCE seq INCREMENT BY 100;
SELECT seq.nextval FROM dual;
</code></pre>
<p>The first select fetches the first sequence ID that the application can use, the second select returns the last one that can be used.</p>
<p>Things get way more interesting in a multithreaded environment. You can't be sure that before the second select another thread doesn't increase the sequence by 100 again. This issue can be solved by synchronizing the access on the Java side - you only let one thread begin fetching the IDs at one time.</p>
<p>The situation becomes really hard when you can't synchronize because parts of the application doesn't run on the same JVM, not even on the same physical machine. I found some references on forums that others have problems with solving this problem too, but none of the answers are really working not to mention being reasonable.</p>
<p>Can the community provide a solution for this problem?</p>
<p>Some more information:</p>
<ul>
<li>I can't really play with the transaction isolation levels. I use JPA and the change would affect the entire application, not only the prefetching queries and that's not acceptable for me.</li>
<li><p>On PostgreSQL I could do the following:
<code>SELECT setval('seq', NEXTVAL('seq') + n - 1)</code></p></li>
<li><p>The solution by Matthew works when you can use a fixed increment value (which is perfectly acceptable in my case). However is there a solution when you don't want to fix the size of the increment, but want to adjust it dynamically?</p></li>
</ul>
|
[
{
"answer_id": 43830,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 5,
"selected": true,
"text": "SQL> create sequence so_test start with 100 increment by 100 nocache;\n\nSequence created.\n\nSQL> select so_test.nextval - 99 as first_seq, so_test.currval as last_seq from dual;\n\n FIRST_SEQ LAST_SEQ\n---------- ----------\n 1 100\n\nSQL> /\n\n FIRST_SEQ LAST_SEQ\n---------- ----------\n 101 200\n\nSQL> /\n\n FIRST_SEQ LAST_SEQ\n---------- ----------\n 201 300\n\nSQL> \n SQL> select * from xx;\n\nno rows selected\n\nSQL> insert into xx values ('x');\n\n1 row created.\n\nSQL> alter sequence so_test increment by 100;\n\nSequence altered.\n\nSQL> rollback;\n\nRollback complete.\n\nSQL> select * from xx;\n\nY\n-----\nx\n\nSQL> \n"
},
{
"answer_id": 44457,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "insert into t (my_pk, my_data) values (mysequence.nextval, :the_data)\nreturning my_pk into :the_pk;\n"
},
{
"answer_id": 45011,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 1,
"selected": false,
"text": "drop table t_so_test;\n\ncreate table t_so_test (curr_num number(10));\n\ninsert into t_so_test values (1);\ncreate or replace procedure p_get_next_seq (inc IN NUMBER, v_next_seq OUT NUMBER) As\nBEGIN\n update t_so_test set curr_num = curr_num + inc RETURNING curr_num into v_next_seq;\nEND;\n/\n\n\nSQL> var p number;\nSQL> execute p_get_next_seq(100,:p);\n\nPL/SQL procedure successfully completed.\n\nSQL> print p;\n\n P\n----------\n 101\n\nSQL> execute p_get_next_seq(10,:p); \n\nPL/SQL procedure successfully completed.\n\nSQL> print p;\n\n P\n----------\n 111\n\nSQL> execute p_get_next_seq(1000,:p);\n\nPL/SQL procedure successfully completed.\n\nSQL> print p;\n\n P\n----------\n 1111\n\nSQL> \n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686/"
] |
43,811 |
<p>This is probably a really simple jQuery question, but I couldn't answer it after 10 minutes in the documentation so...</p>
<p>I have a list of checkboxes, and I can get them with the selector <code>'input[type=checkbox]'</code>. I want the user to be able to shift-click and select a range of checkboxes. To accomplish this, I need to get the index of a checkbox in the list, so I can pass that index to <code>.slice(start, end)</code>. How do I get the index when the user clicks a box?</p>
|
[
{
"answer_id": 43824,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 4,
"selected": true,
"text": "input:checkbox :gt(index) :lt(index) input:checkbox:gt(4):lt(2) $(\"input:checkbox\").index($(this))"
},
{
"answer_id": 43854,
"author": "Ryan Duffield",
"author_id": 2696,
"author_profile": "https://Stackoverflow.com/users/2696",
"pm_score": 1,
"selected": false,
"text": "<input id=\"checkbox-0\" type=\"checkbox\" />\n<input id=\"checkbox-1\" type=\"checkbox\" />\n<input id=\"checkbox-2\" type=\"checkbox\" />\n<input id=\"checkbox-3\" type=\"checkbox\" />\n<input id=\"checkbox-4\" type=\"checkbox\" />\n $(document).ready(function() {\n $(\"input:checkbox\").click(function() {\n index = /checkbox-(\\d+)/.exec(this.id)[1];\n alert(index);\n });\n});\n"
},
{
"answer_id": 43898,
"author": "Christian Oudard",
"author_id": 3757,
"author_profile": "https://Stackoverflow.com/users/3757",
"pm_score": 0,
"selected": false,
"text": "$(':checkbox') .slice() :gt :lt .slice()"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3757/"
] |
43,819 |
<p>We are now using NHibernate to connect to different database base on where our software is installed. So I am porting many SQL Procedures to Oracle.</p>
<p>SQL Server has a nice function called DateDiff which takes a date part, startdate and enddate.</p>
<p>Date parts examples are day, week, month, year, etc. . . </p>
<p>What is the Oracle equivalent?</p>
<p>I have not found one do I have to create my own version of it?</p>
<p><strong>(update by Mark Harrison)</strong> there are several nice answers that explain Oracle date arithmetic. If you need an Oracle datediff() see Einstein's answer. (I need this to keep spme SQL scripts compatible between Sybase and Oracle.) Note that this question applies equally to Sybase.</p>
|
[
{
"answer_id": 44597,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "DECLARE\nts_a timestamp;\nts_b timestamp;\ndiff interval day to second;\nBEGIN\n ts_a := systimestamp;\n ts_b := systimestamp-1/24;\n diff := ts_a - ts_b;\n dbms_output.put_line(diff);\nEND;\n+00 01:00:00.462000\n DECLARE\nts_b timestamp;\nts_a timestamp;\ndate_part interval day to second;\n\nBEGIN\n ts_a := systimestamp;\n date_part := to_dsinterval('0 01:23:45.678');\n ts_b := ts_a + date_part;\n dbms_output.put_line(ts_b);\nEND;\n\n04-SEP-08 05.00.38.108000 PM\n"
},
{
"answer_id": 312993,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "CREATE OR REPLACE FUNCTION GetDate \nRETURN date IS today date;\nBEGIN\nRETURN(sysdate);\nEND;\n/\n\nCREATE OR REPLACE FUNCTION mm RETURN VARCHAR2 IS BEGIN RETURN('mm'); END;\n/\nCREATE OR REPLACE FUNCTION yy RETURN VARCHAR2 IS BEGIN RETURN('yyyy'); END;\n/\nCREATE OR REPLACE FUNCTION dd RETURN VARCHAR2 IS BEGIN RETURN('dd'); END;\n/\nCREATE OR REPLACE FUNCTION dy RETURN VARCHAR2 IS BEGIN RETURN('dd'); END;\n/\nCREATE OR REPLACE FUNCTION hh RETURN VARCHAR2 IS BEGIN RETURN('hh'); END;\n/\nCREATE OR REPLACE FUNCTION mi RETURN VARCHAR2 IS BEGIN RETURN('mi'); END;\n/\nCREATE OR REPLACE FUNCTION ss RETURN VARCHAR2 IS BEGIN RETURN('ss'); END;\n/\n\nCREATE OR REPLACE Function DateAdd(date_type IN varchar2, offset IN integer, date_in IN date )\nRETURN date IS date_returned date;\nBEGIN\ndate_returned := CASE date_type\n WHEN 'mm' THEN add_months(date_in,TRUNC(offset))\n WHEN 'yyyy' THEN add_months(date_in,TRUNC(offset) * 12)\n WHEN 'dd' THEN date_in + TRUNC(offset)\n WHEN 'hh' THEN date_in + (TRUNC(offset) / 24)\n WHEN 'mi' THEN date_in + (TRUNC(offset) /24/60)\n WHEN 'ss' THEN date_in + (TRUNC(offset) /24/60/60)\n END;\nRETURN(date_returned);\nEND;\n/\n\nCREATE OR REPLACE Function DateDiff( return_type IN varchar2, date_1 IN date, date_2 IN date)\nRETURN integer IS number_return integer;\nBEGIN\nnumber_return := CASE return_type\n WHEN 'mm' THEN ROUND(MONTHS_BETWEEN(TRUNC(date_2,'MM'),TRUNC(date_1, 'MM')))\n WHEN 'yyyy' THEN ROUND(MONTHS_BETWEEN(TRUNC(date_2,'YYYY'), TRUNC(date_1, 'YYYY')))/12\n WHEN 'dd' THEN ROUND((TRUNC(date_2,'DD') - TRUNC(date_1, 'DD')))\n WHEN 'hh' THEN (TRUNC(date_2,'HH') - TRUNC(date_1,'HH')) * 24\n WHEN 'mi' THEN (TRUNC(date_2,'MI') - TRUNC(date_1,'MI')) * 24 * 60\n WHEN 'ss' THEN (date_2 - date_1) * 24 * 60 * 60\n END;\nRETURN(number_return);\nEND;\n/\n"
},
{
"answer_id": 26465764,
"author": "Kamyar Gilak",
"author_id": 1780453,
"author_profile": "https://Stackoverflow.com/users/1780453",
"pm_score": 0,
"selected": false,
"text": "function datediff( p_what in varchar2, p_d1 in date, p_d2 in date) return number as l_result number; \nBEGIN\n select (p_d2-p_d1) * \n decode( upper(p_what), 'SS', 24*60*60, 'MI', 24*60, 'HH', 24, NULL ) \n into l_result from dual; \n\n return l_result; \nEND;\n DATEDIFF('YYYY-MM-DD', SYSTIMESTAMP, SYSTIMESTAMP)\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
] |
43,832 |
<p>I think I might be missing something here. Here is the relevant part of the trigger:</p>
<pre><code> CURSOR columnNames (inTableName IN VARCHAR2) IS
SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = inTableName;
/* Removed for brevity */
OPEN columnNames('TEMP');
</code></pre>
<p>And here is the error message that I'm getting back,</p>
<pre>
27/20 PLS-00306: wrong number or types of arguments in call to 'COLUMNNAMES'
27/2 PL/SQL: Statement ignored
</pre>
<p>If I am understanding the documentation correctly, that should work, but since it is not I must be doing something wrong. Any ideas?</p>
<hr />
<p>@<a href="https://stackoverflow.com/questions/43832/pls-00306-error-on-call-to-cursor#43859">Matthew</a> - I appreciate the help, but the reason that I am confused is because this bit of code isn't working for me and is raising the errors referenced. We have other triggers in the database with code almost exactly the as that so I'm not sure if it is something that I did wrong, or something with how I am trying to store the trigger, etc.</p>
<hr />
<p>@<a href="https://stackoverflow.com/questions/43832/pls-00306-error-on-call-to-cursor#43859">Matthew</a> - Well, now I get to feel embarrassed. I did a copy/paste of the code that you provided into a new trigger and it worked fine. So I went back into the original trigger and tried it and received the error message again, except this time I started to delete stuff out of the trigger and after getting rid of this line,</p>
<pre><code>FOR columnName IN columnNames LOOP
</code></pre>
<p>Things saved fine. So it turns out that where I thought the error was, wasn't actually were the error was.</p>
|
[
{
"answer_id": 43859,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 1,
"selected": false,
"text": "create or replace procedure so_test_procedure as \n CURSOR columnNames (inTableName IN VARCHAR2) IS \n SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = inTableName; \nBEGIN \n OPEN columnNames('TEMP');\n CLOSE columnNames;\nEND;\n\nprocedure so_test_procedure Compiled.\nexecute so_test_procedure();\n\nanonymous block completed\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1185/"
] |
43,842 |
<p>I have a string that contains the representation of a date. It looks like: </p>
<p><strong>Thu Nov 30 19:00:00 EST 2006</strong></p>
<p>I'm trying to create a Date object using SimpleDateFormat and have 2 problems. </p>
<p>1.) I can't figure out the pattern to hard-code the solution into the SimpleDateFormat constructor</p>
<p>2.) I can't find a way I could parse the string using API to determine the pattern so I could reuse this for different patterns of date output </p>
<p>If anyone knows a solution using API or a custom solution I would greatly appreciate it.</p>
|
[
{
"answer_id": 43850,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 0,
"selected": false,
"text": "\"EEE MMM d HH:mm:ss z yyyy\"\n"
},
{
"answer_id": 43852,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 4,
"selected": true,
"text": "new SimpleDateFormat(\"EEE MMM dd HH:mm:ss zzz yyyy\")\n"
},
{
"answer_id": 43867,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 1,
"selected": false,
"text": "new SimpleDateFormat(\"EEE MMM dd HH:mm:ss zzz yyyy\"\n"
},
{
"answer_id": 43869,
"author": "Nick Pierpoint",
"author_id": 4003,
"author_profile": "https://Stackoverflow.com/users/4003",
"pm_score": 0,
"selected": false,
"text": "EEE MMM dd HH:mm:ss zzz yyyy"
},
{
"answer_id": 45167,
"author": "Joe Liversedge",
"author_id": 4552,
"author_profile": "https://Stackoverflow.com/users/4552",
"pm_score": 2,
"selected": false,
"text": "parseDate String Date"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2628/"
] |
43,866 |
<p>Why do I need two of them? When I have to use one or another?</p>
|
[
{
"answer_id": 43901,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 8,
"selected": true,
"text": "SALES.acme.com SALES.acme.com SALES.acme.com"
},
{
"answer_id": 30327260,
"author": "seorphates",
"author_id": 4916341,
"author_profile": "https://Stackoverflow.com/users/4916341",
"pm_score": 5,
"selected": false,
"text": "mySID, mySID.whereever.com =\n(DESCRIPTION =\n (ADDRESS_LIST =\n (ADDRESS = (PROTOCOL = TCP)(HOST = myHostname)(PORT = 1521))\n )\n (CONNECT_DATA =\n (SERVICE_NAME = mySID.whereever.com)\n (SID = mySID)\n (SERVER = DEDICATED)\n )\n)\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4052/"
] |
43,870 |
<p>I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table:</p>
<pre><code>ID COMPANY_ID EMPLOYEE
1 1 Anna
2 1 Bill
3 2 Carol
4 2 Dave
</code></pre>
<p>and I wanted to group by company_id to get something like:</p>
<pre><code>COMPANY_ID EMPLOYEE
1 Anna, Bill
2 Carol, Dave
</code></pre>
<p>There is a built-in function in mySQL to do this <a href="http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat" rel="noreferrer">group_concat</a></p>
|
[
{
"answer_id": 43889,
"author": "Guy C",
"author_id": 4045,
"author_profile": "https://Stackoverflow.com/users/4045",
"pm_score": 4,
"selected": false,
"text": "CREATE AGGREGATE textcat_all(\n basetype = text,\n sfunc = textcat,\n stype = text,\n initcond = ''\n);\n\nSELECT company_id, textcat_all(employee || ', ')\nFROM mytable\nGROUP BY company_id;\n"
},
{
"answer_id": 43944,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 10,
"selected": true,
"text": "string_agg(expression, delimiter) SELECT company_id, string_agg(employee, ', ')\nFROM mytable\nGROUP BY company_id;\n ORDER BY SELECT company_id, string_agg(employee, ', ' ORDER BY employee)\nFROM mytable\nGROUP BY company_id;\n array_agg(expression) array_to_string() SELECT company_id, array_to_string(array_agg(employee), ', ')\nFROM mytable\nGROUP BY company_id;\n textcat || CREATE AGGREGATE textcat_all(\n basetype = text,\n sfunc = textcat,\n stype = text,\n initcond = ''\n);\n CREATE AGGREGATE CREATE FUNCTION commacat(acc text, instr text) RETURNS text AS $$\n BEGIN\n IF acc IS NULL OR acc = '' THEN\n RETURN instr;\n ELSE\n RETURN acc || ', ' || instr;\n END IF;\n END;\n$$ LANGUAGE plpgsql;\n a, b, c, , e, , g\n a, b, c, e, g\n ELSIF CREATE FUNCTION commacat_ignore_nulls(acc text, instr text) RETURNS text AS $$\n BEGIN\n IF acc IS NULL OR acc = '' THEN\n RETURN instr;\n ELSIF instr IS NULL OR instr = '' THEN\n RETURN acc;\n ELSE\n RETURN acc || ', ' || instr;\n END IF;\n END;\n$$ LANGUAGE plpgsql;\n"
},
{
"answer_id": 354009,
"author": "bortzmeyer",
"author_id": 15625,
"author_profile": "https://Stackoverflow.com/users/15625",
"pm_score": 3,
"selected": false,
"text": "CREATE OR REPLACE FUNCTION concat2(text, text) RETURNS text AS '\n SELECT CASE WHEN $1 IS NULL OR $1 = \\'\\' THEN $2\n WHEN $2 IS NULL OR $2 = \\'\\' THEN $1\n ELSE $1 || \\' / \\' || $2\n END; \n'\n LANGUAGE SQL;\n\nCREATE AGGREGATE concatenate (\n sfunc = concat2,\n basetype = text,\n stype = text,\n initcond = ''\n SELECT company_id, concatenate(employee) AS employees FROM ...\n"
},
{
"answer_id": 563907,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "select itemid, \n CASE \n itemdescription WHEN '' THEN itemname \n ELSE itemname || ' (' || itemdescription || ')' \n END \nfrom items;\n"
},
{
"answer_id": 882375,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "array_to_string CREATE AGGREGATE array_accum (anyelement)\n(\n sfunc = array_append,\n stype = anyarray,\n initcond = '{}'\n);\n\nselect array_to_string(array_accum(name),'|') from table group by id;\n"
},
{
"answer_id": 1374479,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "SELECT custom_aggregate(MY.special_strings)\nFROM (SELECT special_strings, grouping_column \n FROM a_table \n ORDER BY ordering_column) MY\nGROUP BY MY.grouping_column\n"
},
{
"answer_id": 2292862,
"author": "Markus Döring",
"author_id": 276551,
"author_profile": "https://Stackoverflow.com/users/276551",
"pm_score": 7,
"selected": false,
"text": "SELECT company_id, array_to_string(array_agg(employee), ',')\nFROM mytable\nGROUP BY company_id;\n"
},
{
"answer_id": 6139500,
"author": "dirbacke",
"author_id": 435140,
"author_profile": "https://Stackoverflow.com/users/435140",
"pm_score": 5,
"selected": false,
"text": "SELECT company_id, string_agg(employee, ', ')\nFROM mytable\nGROUP BY company_id;"
},
{
"answer_id": 45433428,
"author": "Gobinath",
"author_id": 7368539,
"author_profile": "https://Stackoverflow.com/users/7368539",
"pm_score": 0,
"selected": false,
"text": "SELECT company_id, string_agg(employee, ', ')\n FROM mytable GROUP BY company_id;\n"
},
{
"answer_id": 52096061,
"author": "Sandip Debnath",
"author_id": 1459714,
"author_profile": "https://Stackoverflow.com/users/1459714",
"pm_score": 0,
"selected": false,
"text": "create or replace function concat_return_row_count(tbl_name text, column_name text, value int)\nreturns integer as $row_count$\ndeclare\ntotal integer;\nbegin\n EXECUTE format('select count(*) from %s WHERE %s = %s', tbl_name, column_name, value) INTO total;\n return total;\nend;\n$row_count$ language plpgsql;\n\n\npostgres=# select concat_return_row_count('tbl_name','column_name',2); --2 is the value\n"
},
{
"answer_id": 53605287,
"author": "Damien Sawyer",
"author_id": 494635,
"author_profile": "https://Stackoverflow.com/users/494635",
"pm_score": 0,
"selected": false,
"text": "select string_agg('drop table if exists \"' || tablename || '\" cascade', ';') \nfrom pg_tables where schemaname != $$pg_catalog$$ and tableName like $$rm_%$$\n"
},
{
"answer_id": 55178427,
"author": "Gapp",
"author_id": 11207468,
"author_profile": "https://Stackoverflow.com/users/11207468",
"pm_score": 1,
"selected": false,
"text": "SELECT company_id, listagg(EMPLOYEE, ', ') as employees\nFROM EMPLOYEE_table\nGROUP BY company_id;\n"
},
{
"answer_id": 55659734,
"author": "Valentin Podkamennyi",
"author_id": 5438323,
"author_profile": "https://Stackoverflow.com/users/5438323",
"pm_score": 3,
"selected": false,
"text": "STRING_AGG SELECT company_id, STRING_AGG(employee, ', ')\nFROM employees\nGROUP BY company_id;\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4045/"
] |
43,874 |
<p>I have a multiple selection SELECT field which I don't want the end user to be able to change the value of. </p>
<p>For UI reasons, I would like to be able to do this without using the disabled="true" attribute. I've tried using onmousedown, onfocus, onclick and setting each to blur or return false but with no success.</p>
<p>Can this be done or am I trying to do the impossible?</p>
|
[
{
"answer_id": 43880,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 2,
"selected": false,
"text": "onchange <select onfocus=\"this.oldIndex=this.selectedIndex\" onchange=\"this.selectedIndex=this.oldIndex\">\n"
},
{
"answer_id": 43931,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 4,
"selected": true,
"text": "disabled <select multiple=\"multiple\">\n <option value=\"volvo\" selected=\"true\" disabled=\"disabled\">Volvo</option>\n <option value=\"saab\" disabled=\"disabled\">Saab</option>\n <option value=\"opel\" disabled=\"disabled\">Opel</option>\n <option value=\"audi\" disabled=\"disabled\">Audi</option>\n</select>\n select class"
},
{
"answer_id": 14748471,
"author": "user1842841",
"author_id": 1842841,
"author_profile": "https://Stackoverflow.com/users/1842841",
"pm_score": 0,
"selected": false,
"text": "<select multiple onchange=\"this.selectedIndex=this.selectedIndex\">\n<option>1</option>\n<option>2</option>\n</select>\n"
},
{
"answer_id": 49288620,
"author": "Eliseo D'Annunzio",
"author_id": 1739744,
"author_profile": "https://Stackoverflow.com/users/1739744",
"pm_score": 0,
"selected": false,
"text": "pointer-events SELECT"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1980/"
] |
43,890 |
<p><strong>Original Question</strong></p>
<p>I want to be able to generate a new (fully valid) MP3 file from an existing MP3 file to be used as a preview -- try-before-you-buy style. The new file should only contain the first <em>n</em> seconds of the track.</p>
<p>Now, I know I could just "chop the stream" at <em>n</em> seconds (calculating from the bitrate and header size) when delivering the file, but this is a bit dirty and a real PITA on a VBR track. I'd like to be able to generate a proper MP3 file.</p>
<p>Anyone any ideas?</p>
<p><strong>Answers</strong></p>
<p>Both <code>mp3split</code> and <code>ffmpeg</code> are both good solutions. I chose ffmpeg as it is commonly installed on linux servers and is also <a href="http://sourceforge.net/project/showfiles.php?group_id=205275&package_id=248632" rel="noreferrer">easily available for windows</a>. Here's some more good command line parameters for generating previews with ffmpeg</p>
<ul>
<li><strong><code>-t <seconds></code></strong> chop after specified number of seconds</li>
<li><strong><code>-y</code></strong> force file overwrite</li>
<li><strong><code>-ab <bitrate></code></strong> set bitrate e.g. <em>-ab 96k</em></li>
<li><strong><code>-ar <rate Hz></code></strong> set sampling rate e.g. <em>-ar 22050</em> for 22.05kHz</li>
<li><strong><code>-map_meta_data <outfile>:<infile></code></strong> copy track metadata from infile to outfile</li>
</ul>
<p>instead of setting -ab and -ar, you can copy the original track settings, as Tim Farley suggests, with:</p>
<ul>
<li><strong><code>-acodec copy</code></strong></li>
</ul>
|
[
{
"answer_id": 43912,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 4,
"selected": false,
"text": "ffmpeg -t 30 -i inputfile.mp3 outputfile.mp3\n"
},
{
"answer_id": 44032,
"author": "Tim Farley",
"author_id": 4425,
"author_profile": "https://Stackoverflow.com/users/4425",
"pm_score": 8,
"selected": true,
"text": "ffmpeg -t 30 -i inputfile.mp3 -acodec copy outputfile.mp3\n"
},
{
"answer_id": 2925734,
"author": "the.jxc",
"author_id": 84949,
"author_profile": "https://Stackoverflow.com/users/84949",
"pm_score": 6,
"selected": false,
"text": "ffmpeg -ss 30 -i inputfile.mp3 -acodec copy outputfile.mp3\n"
},
{
"answer_id": 7465346,
"author": "Michał Šrajer",
"author_id": 705676,
"author_profile": "https://Stackoverflow.com/users/705676",
"pm_score": 4,
"selected": false,
"text": "cutmp3 -i foo.mp3 -O 30s.mp3 -a 0:00.0 -b 0:30.0\n sudo apt-get install cutmp3"
},
{
"answer_id": 40923857,
"author": "Mithun Cheriyath",
"author_id": 7239222,
"author_profile": "https://Stackoverflow.com/users/7239222",
"pm_score": 1,
"selected": false,
"text": "Invalid audio stream. Exactly one MP3 audio stream is required.\nCould not write header for output file #0 (incorrect codec parameters ?): Invalid argumentStream mapping:\n ffmpeg -ss 00:02:43.00 -t 00:00:10 -i input.mp3 -codec:a libmp3lame out.mp3\n"
},
{
"answer_id": 44536650,
"author": "Rahul Chauhan",
"author_id": 7333306,
"author_profile": "https://Stackoverflow.com/users/7333306",
"pm_score": 4,
"selected": false,
"text": "ffmpeg -i test.mp3 -ss 00:00:20 -to 00:00:40 -c copy -y temp.mp3\n"
},
{
"answer_id": 57763520,
"author": "srbcheema1",
"author_id": 6799074,
"author_profile": "https://Stackoverflow.com/users/6799074",
"pm_score": 0,
"selected": false,
"text": "ffmpeg medipack trim input.mp3 -s 00:00 -e 00:30 -o output.mp3\nmedipack trim input.mp3 -s 00:00 -t 00:30 -o output.mp3\n srb@srb-pc:$ medipack trim -h\nusage: medipack trim [-h] [-s START] [-e END | -t TIME] [-o OUTPUT] [inp]\n\npositional arguments:\n inp input video file ex: input.mp4\n\noptional arguments:\n -h, --help show this help message and exit\n -s START, --start START\n start time for cuting in format hh:mm:ss or mm:ss\n -e END, --end END end time for cuting in format hh:mm:ss or mm:ss\n -t TIME, --time TIME clip duration in format hh:mm:ss or mm:ss\n -o OUTPUT, --output OUTPUT\n medipack -h srb@srb-pc:$ medipack --help\nusage: medipack.py [-h] [-v] {trim,crop,resize,extract} ...\n\npositional arguments:\n {trim,crop,resize,extract}\n\noptional arguments:\n -h, --help show this help message and exit\n -v, --version Display version number\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820/"
] |
43,903 |
<p>In a stored procedure, when is #Temptable created in SQL Server 2005? When creating the query execution plan or when executing the stored procedure?</p>
<pre><code>if (@x = 1)
begin
select 1 as Text into #Temptable
end
else
begin
select 2 as Text into #Temptable
end
</code></pre>
|
[
{
"answer_id": 77262,
"author": "Chris Wuestefeld",
"author_id": 10082,
"author_profile": "https://Stackoverflow.com/users/10082",
"pm_score": 2,
"selected": false,
"text": "DECLARE @MyTable TABLE (MyPK INT IDENTITY, MyName VARCHAR(100))\nINSERT INTO @MyTable ( MyName ) VALUES ( 'Icarus' )\nINSERT INTO @MyTable ( MyName ) VALUES ( 'Daedalus' )\nSELECT * FROM @MyTable\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2184/"
] |
43,926 |
<p>A <code>.container</code> can contain many <code>.components</code>, and <code>.components</code> themselves can contain <code>.containers</code> (which in turn can contain .components etc. etc.)</p>
<p>Given code like this:</p>
<pre><code>$(".container .component").each(function(){
$(".container", this).css('border', '1px solid #f00');
});
</code></pre>
<p>What do I need to add to the line within the braces to select only the nested <code>.containers</code> that have their <code>width</code> in CSS set to <code>auto</code>? I'm sure it's something simple, but I haven't really used jQuery all that much.</p>
|
[
{
"answer_id": 43933,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 2,
"selected": false,
"text": "$(\".container .component\").each(function() {\n if ($(\".container\", this).css('width') === \"auto\")\n $(\".container\", this).css('border', '1px solid #f00');\n});\n"
},
{
"answer_id": 43937,
"author": "David McLaughlin",
"author_id": 3404,
"author_profile": "https://Stackoverflow.com/users/3404",
"pm_score": 5,
"selected": true,
"text": "$(\".container .component\").each(function()\n{\n $(\".container\", this).each(function() {\n if($(this).css('width') == 'auto')\n {\n $(this).css('border', '1px solid #f00');\n }\n });\n});\n"
},
{
"answer_id": 8934795,
"author": "anon",
"author_id": 731352,
"author_profile": "https://Stackoverflow.com/users/731352",
"pm_score": 4,
"selected": false,
"text": ".filter() $('.container .component .container')\n.filter(function() {return $(this).css('width') == 'auto';})\n.css({border: '1px solid #f00'});\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2268/"
] |
43,947 |
<p>Caveat: I'm relatively new to coding as well as <a href="http://macromates.com/" rel="nofollow noreferrer">TextMate</a>, so apologies if there is an obvious answer I'm missing here.</p>
<p>I do a lot of HTML/CSS markup, there are certain patterns that I use a lot, for example, forms, navigation menus etc. What I would like is a way to store those patterns and insert them quickly when I need them. </p>
<p>Is there a way to do this using TextMate?</p>
|
[
{
"answer_id": 43968,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 4,
"selected": true,
"text": "Tab Tab"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2977/"
] |
43,955 |
<p>Is it possible to modify the title of the message box the confirm() function opens in JavaScript? </p>
<p>I could create a modal popup box, but I would like to do this as minimalistic as possible.
I would like to do something like this:</p>
<pre><code>confirm("This is the content of the message box", "Modified title");
</code></pre>
<p>The default title in Internet Explorer is "Windows Internet Explorer" and in Firefox it's "[JavaScript-program]." Not very informative. Though I can understand from a browser security stand point that you shouldn't be able to do this.</p>
|
[
{
"answer_id": 24963561,
"author": "Ramon",
"author_id": 1211777,
"author_profile": "https://Stackoverflow.com/users/1211777",
"pm_score": 4,
"selected": false,
"text": "var iframe = document.createElement(\"IFRAME\");\niframe.setAttribute(\"src\", 'data:text/plain,');\ndocument.documentElement.appendChild(iframe);\nif(window.frames[0].window.confirm(\"Are you sure?\")){\n // what to do if answer \"YES\"\n}else{\n // what to do if answer \"NO\"\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2241/"
] |
43,970 |
<p>I'm setting up a server which is on a network behind a firewall and I want programs on this computer to be able to use sendmail to send emails to any email address. We have an SMTP server running on this network (let's call it mailrelay.example.com) which is how we're supposed to get outgoing emails through the firewall.</p>
<p>So how do I configure sendmail to send all mail through mailrelay.example.com? Googling hasn't given me the answer yet, and has only revealed that sendmail configuration is extremely complex and annoying.</p>
|
[
{
"answer_id": 44014,
"author": "Eli Courtwright",
"author_id": 1694,
"author_profile": "https://Stackoverflow.com/users/1694",
"pm_score": 2,
"selected": false,
"text": "DS\n DSmailrelay.example.com\n"
},
{
"answer_id": 107795,
"author": "tardate",
"author_id": 6329,
"author_profile": "https://Stackoverflow.com/users/6329",
"pm_score": 5,
"selected": true,
"text": " define(`SMART_HOST',`mailrelay.example.com')dnl \n # m4 /etc/mail/sendmail.mc > /etc/sendmail.cf\n # /etc/init.d/sendmail restart\n host map: lookup (mydomain.com): deferred)\n define(`confSERVICE_SWITCH_FILE',`/etc/mail/service.switch')dnl\n # cat /etc/mail/service.switch\n hosts files\n DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA')\n DAEMON_OPTIONS(`Port=125,Addr=127.0.0.1, Name=MTA')\n DAEMON=no\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
] |
43,971 |
<p>Let's say I have a web site for hosting community generated content that targets a very specific set of users. Now, let's say in the interest of fostering a better community I have an off-topic area where community members can post or talk about anything they want, regardless of the site's main theme.</p>
<p>Now, I <em>want</em> most of the content to get indexed by Google. The notable exception is the off-topic content. Each thread has it's own page, but all the threads are listed in the same folder so I can't just exclude search engines from a folder somewhere. It has to be per-page. A traditional robots.txt file would get huge, so how else could I accomplish this?</p>
|
[
{
"answer_id": 43983,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 6,
"selected": true,
"text": "<head> <meta name=\"robots\" content=\"noindex, nofollow\" />\n"
},
{
"answer_id": 19090271,
"author": "Ajay Prasad",
"author_id": 2768704,
"author_profile": "https://Stackoverflow.com/users/2768704",
"pm_score": 1,
"selected": false,
"text": "RewriteRule ^robots\\.txt$ /robots.php [NC,L]\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
43,992 |
<p>I want to allow my users to embed their own Flash animations in their posts. Usually the actual file is hosted on some free image hosting site. I wouldn't actually load the flash unless the user clicked a button to play (so that nothing auto-plays on page load). I know people can make some really annoying crap in flash, but I can't find any information about potential <em>serious</em> damage a flash app could cause to the viewer.</p>
<p>Is it unsafe to embed just any flash file from the internets? If so, how can I let users embed innocent animations but still keep out the harmful apps?</p>
<p>edit:</p>
<p>From what I can gather, the most obvious threat is for actionscript to redirect you to a malicious site.</p>
<p>Adobe <a href="http://www.adobe.com/devnet/flashplayer/articles/secure_swf_apps_04.html" rel="nofollow noreferrer">says</a> you can set <strong>allowScriptAccess=never</strong> and <strong>allowNetworking=none</strong> and the swf should have no access to anything outside of itself. <strong>Will this solve all my problems?</strong></p>
|
[
{
"answer_id": 52037,
"author": "RickDT",
"author_id": 5421,
"author_profile": "https://Stackoverflow.com/users/5421",
"pm_score": 2,
"selected": false,
"text": "var maskSpr : Sprite = new Sprite();\nmaskSpr.graphics.beginFill();\nmaskSpr.graphics.drawRect(0,0,safeWidth,safeHeight);\nmaskSpr.graphics.endFill();\nmyLdr.mask = maskSpr;\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43992",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/744/"
] |
43,995 |
<p>Handling multiple merges onto branches in Subversion or CVS is just one of those things that has to be experienced. It is inordinately easier to keep track of branches and merges in Mercurial (and probably any other distributed system) but I don't know why. Does anyone else know?</p>
<p>My question stems from the fact that with Mercurial you can adopt a working practice similar to that of Subversions/CVSs central repository and everything will work just fine. You can do multiple merges on the same branch and you won't need endless scraps of paper with commit numbers and tag names.</p>
<p>I know the latest version of Subversion has the ability to track merges to branches so you don't get quite the same degree of hassle but it was a huge and major development on their side and it still doesn't do everything the development team would like it to do.</p>
<p>There must be a fundamental difference in the way it all works.</p>
|
[
{
"answer_id": 44708,
"author": "Damien Diederen",
"author_id": 3844,
"author_profile": "https://Stackoverflow.com/users/3844",
"pm_score": 8,
"selected": true,
"text": "gitk hg\nview o---A---o---B---o---C (branch #1)\n \\ \\\n o---o---M---X---? (branch #2)\n $ git merge branch-1\n o---A---o---B---o---C (branch #1)\n \\ \n o---o---M---X---? (branch #2)\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/43995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4003/"
] |
44,007 |
<p>Is there any chance to get this work? I want my tests to be run by nunit2 task in NAnt. In addition I want to run NCover without running tests again. </p>
|
[
{
"answer_id": 190097,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": " <mkdir dir=\"${build}/coverage\" failonerror=\"false\"/>\n\n <!-- run the unit tests and generate code coverage -->\n <property name=\"tools.dir.tmp\" value=\"${tools.dir}\"/>\n <if test=\"${not path::is-path-rooted(tools.dir)}\">\n <property name=\"tools.dir.tmp\" value=\"../../${tools.dir}\"/>\n </if>\n\n <property name=\"nunitpath\" value=\"${lib.dir}/${lib.nunit.basedir}/bin/nunit-console.exe\"/>\n <property name=\"nunitargs\" value=\"\"/>\n <if test=\"${property::exists('teamcity.dotnet.nunitlauncher')}\">\n <property name=\"nunitpath\" value=\"${teamcity.dotnet.nunitlauncher}\"/>\n <property name=\"nunitargs\" value=\"v2.0 x86 NUnit-2.4.8\"/>\n </if>\n\n <ncover program=\"${tools.dir.tmp}/${tools.ncover.basedir}/ncover.console.exe\"\n commandLineExe=\"${nunitpath}\"\n commandLineArgs=\"${nunitargs} ${proj.name.unix}.dll\"\n workingDirectory=\"${build}\"\n assemblyList=\"${proj.srcproj.name.unix}\"\n logFile=\"${build}/coverage/coverage.log\"\n excludeAttributes=\"System.CodeDom.Compiler.GeneratedCodeAttribute\"\n typeExclusionPatterns=\".*?\\{.*?\\}.*?\"\n methodExclusionPatterns=\"get_.*?; set_.*?\"\n coverageFile=\"${build}/coverage/coverage.xml\"\n coverageHtmlDirectory=\"${build}/coverage/html/\"\n />\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3182/"
] |
44,019 |
<p>I need to diff two log files but ignore the time stamp part of each line (the first 12 characters to be exact). Is there a good tool, or a clever awk command, that could help me out?</p>
|
[
{
"answer_id": 44028,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 5,
"selected": false,
"text": "cut -b13- file1 > trimmed_file1\ncut -b13- file2 > trimmed_file2\ndiff trimmed_file1 trimmed_file2\n"
},
{
"answer_id": 44033,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 7,
"selected": true,
"text": "diff <(cut -b13- file1) <(cut -b13- file2)\n"
},
{
"answer_id": 20129125,
"author": "oHo",
"author_id": 938111,
"author_profile": "https://Stackoverflow.com/users/938111",
"pm_score": 4,
"selected": false,
"text": "cut diff diff -I '^#' <(sed -r 's/^((.){12})/#\\1\\n/' 1.log) <(sed -r 's/^((.){12})/#\\1\\n/' 2.log)\n sed # \\n diff -I '^#' # $> for ((i=1;i<11;i++)) do echo \"09:0${i::1}:00.000 data $i\"; done > 1.log\n$> for ((i=1;i<11;i++)) do echo \"11:00:0${i::1}.000 data $i\"; done > 2.log\n diff $> diff 1.log 2.log\n1,10c1,10\n< 09:01:00.000 data 1\n< 09:02:00.000 data 2\n< 09:03:00.000 data 3\n< 09:04:00.000 data 4\n< 09:05:00.000 data 5\n< 09:06:00.000 data 6\n< 09:07:00.000 data 7\n< 09:08:00.000 data 8\n< 09:09:00.000 data 9\n< 09:01:00.000 data 10\n---\n> 11:00:01.000 data 1\n> 11:00:02.000 data 2\n> 11:00:03.000 data 3\n> 11:00:04.000 data 4\n> 11:00:05.000 data 5\n> 11:00:06.000 data 6\n> 11:00:07.000 data 7\n> 11:00:08.000 data 8\n> 11:00:09.000 data 9\n> 11:00:01.000 data 10\n diff -I '^#' $> diff -I '^#' <(sed -r 's/^((.){12})/#\\1\\n/' 1.log) <(sed -r 's/^((.){12})/#\\1\\n/' 2.log)\n$>\n 2.log data foo $> sed '6s/data/foo/' -i 2.log\n$> diff -I '^#' <(sed -r 's/^((.){12})/#\\1\\n/' 1.log) <(sed -r 's/^((.){12})/#\\1\\n/' 2.log)\n11,13c11,13\n11,13c11,13\n< #09:06:00.000\n< data 6\n< #09:07:00.000\n---\n> #11:00:06.000\n> foo 6\n> #11:00:07.000\n diff -y --side-by-side $> diff -y -I '^#' <(sed -r 's/^((.){12})/#\\1\\n/' 1.log) <(sed -r 's/^((.){12})/#\\1\\n/' 2.log)\n#09:01:00.000 #11:00:01.000\n data 1 data 1\n#09:02:00.000 #11:00:02.000\n data 2 data 2\n#09:03:00.000 #11:00:03.000\n data 3 data 3\n#09:04:00.000 #11:00:04.000\n data 4 data 4\n#09:05:00.000 #11:00:05.000\n data 5 data 5\n#09:06:00.000 | #11:00:06.000\n data 6 | foo 6\n#09:07:00.000 | #11:00:07.000\n data 7 data 7\n#09:08:00.000 #11:00:08.000\n data 8 data 8\n#09:09:00.000 #11:00:09.000\n data 9 data 9\n#09:01:00.000 #11:00:01.000\n data 10 data 10\n sed sed -r <(sed 's/^\\(............\\)/#\\1\\n/' 1.log)"
},
{
"answer_id": 33210487,
"author": "Pedro Reis",
"author_id": 1665301,
"author_profile": "https://Stackoverflow.com/users/1665301",
"pm_score": 2,
"selected": false,
"text": "sed \"s/[ 012][0-9]:[0-5][0-9]:[0-5][0-9]//\""
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4061/"
] |
44,034 |
<p>Unable to find a SQL diff tool that meets my needs, I am writing my own. Between the INFORMATION_SCHEMA and sys tables, I have a mostly-complete working version. But one thing I can't find in the metadata is the <em>definition</em> of a trigger, you know, the actual SQL code. Am I overlooking something?</p>
<p>Thanks.</p>
<hr>
<p>Thanks, Pete, I didn't know about that!</p>
<p>Scott, I'm working with very basic hosting packages that don't allow remote connections to the DB. I don't know from the specs on RedGate (which I can't afford anyway) whether they provide a workaround for that, and although there are also API's out there (such as the one from Apex), I didn't see the point in investing in a solution that was still going to require more programming on my part. :)</p>
<p>My solution is to drop an ASPX page on the site that acts as a kind of "schema service", returning the collected metadata as XML. I set up a little AJAX app that compares any number of catalog instances to a master and shows the diffs. It's not perfect, but a major step forward for me.</p>
<p>Thanks again!</p>
|
[
{
"answer_id": 28305390,
"author": "Sathish",
"author_id": 3789892,
"author_profile": "https://Stackoverflow.com/users/3789892",
"pm_score": 4,
"selected": false,
"text": "SELECT \n DB_NAME() AS DataBaseName, \n dbo.SysObjects.Name AS TriggerName,\n dbo.sysComments.Text AS SqlContent\nFROM \n dbo.SysObjects INNER JOIN \n dbo.sysComments ON \n dbo.SysObjects.ID = dbo.sysComments.ID\nWHERE \n (dbo.SysObjects.xType = 'TR') \n AND \n dbo.SysObjects.Name = '<YourTriggerName>'\n"
},
{
"answer_id": 42998834,
"author": "Loftx",
"author_id": 89941,
"author_profile": "https://Stackoverflow.com/users/89941",
"pm_score": 3,
"selected": false,
"text": "SELECT \n sysobjects.name AS trigger_name, \n OBJECT_NAME(parent_obj) AS table_name,\n OBJECT_DEFINITION(id) AS trigger_definition\nFROM sysobjects \nWHERE sysobjects.type = 'TR' \n"
},
{
"answer_id": 48515193,
"author": "mehdi",
"author_id": 1831567,
"author_profile": "https://Stackoverflow.com/users/1831567",
"pm_score": 0,
"selected": false,
"text": "Select \n [tgr].[name] as [trigger name], \n [tbl].[name] as [table name] , \n OBJECT_DEFINITION(tgr.id) body\n\n from sysobjects tgr \n\n join sysobjects tbl\n on tgr.parent_obj = tbl.id\n\nWHERE tgr.xtype = 'TR'\n"
},
{
"answer_id": 59265974,
"author": "Reza Jenabi",
"author_id": 9549856,
"author_profile": "https://Stackoverflow.com/users/9549856",
"pm_score": 2,
"selected": false,
"text": "SELECT definition\nFROM sys.sql_modules\nWHERE object_id = OBJECT_ID('trigger_name');\n SELECT OBJECT_NAME(parent_obj) [table name], \n NAME [triger name], \n OBJECT_DEFINITION(id) body\nFROM sysobjects\nWHERE xtype = 'TR'\n AND name = 'trigger_name';\n SELECT OBJECT_DEFINITION(OBJECT_ID('trigger_name')) AS trigger_definition;\n EXEC sp_helptext \n 'trigger_name';\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4525/"
] |
44,046 |
<p>I'm trying to determine the best way to truncate or drop extra decimal places in SQL without rounding. For example:</p>
<pre><code>declare @value decimal(18,2)
set @value = 123.456
</code></pre>
<p>This will automatically round <code>@value</code> to be <code>123.46</code>, which is good in most cases. However, for this project, I don't need that. Is there a simple way to truncate the decimals I don't need? I know I can use the <code>left()</code> function and convert back to a decimal. Are there any other ways?</p>
|
[
{
"answer_id": 44049,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": -1,
"selected": false,
"text": "select convert(int,@value)\n"
},
{
"answer_id": 44052,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 9,
"selected": true,
"text": "select round(123.456, 2, 1)\n"
},
{
"answer_id": 44063,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 3,
"selected": false,
"text": "select ceiling(@value),floor(@value)\n select round(@value,2)\n"
},
{
"answer_id": 44093,
"author": "Jeff Cuscutis",
"author_id": 2277,
"author_profile": "https://Stackoverflow.com/users/2277",
"pm_score": 8,
"selected": false,
"text": "ROUND ( 123.456 , 2 , 1 )\n ROUND ( numeric_expression , length [ ,function ] )\n numeric_expression length function"
},
{
"answer_id": 543876,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "select 100.0019-(100.0019%.001)\n select 123.456-(123.456%.001)\n select cast((123.456-(123.456%.001)) as decimal (18,2))\n"
},
{
"answer_id": 543922,
"author": "James",
"author_id": 56753,
"author_profile": "https://Stackoverflow.com/users/56753",
"pm_score": 3,
"selected": false,
"text": " Convert 71.950005666 to a single decimal place number (71.9)\n 1) 71.950005666 * 10.0 = 719.50005666\n 2) Floor(719.50005666) = 719.0\n 3) 719.0 / 10.0 = 71.9\n\n select Floor(71.950005666 * 10.0) / 10.0\n"
},
{
"answer_id": 826659,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "SELECT Cast(Round(123.456,2,1) as decimal(18,2))\n"
},
{
"answer_id": 1067677,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "declare @val decimal (8, 2)\nselect @val = 123.456\nselect @val = @val\n\nselect @val\n"
},
{
"answer_id": 1603920,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "Mod(x,1)"
},
{
"answer_id": 1725878,
"author": "Quentin",
"author_id": 210016,
"author_profile": "https://Stackoverflow.com/users/210016",
"pm_score": 3,
"selected": false,
"text": "Select round(123.456, 2, 1) will = 123.45\nSelect round(123.456, 2, 0) will = 123.46\n"
},
{
"answer_id": 1769828,
"author": "Mohamed",
"author_id": 215369,
"author_profile": "https://Stackoverflow.com/users/215369",
"pm_score": 0,
"selected": false,
"text": "declare @val decimal (8, 3)\nSET @val = 123.456\n\nSELECT @val - ROUND(@val,0,1)\n"
},
{
"answer_id": 1887371,
"author": "Probal",
"author_id": 229569,
"author_profile": "https://Stackoverflow.com/users/229569",
"pm_score": 2,
"selected": false,
"text": "SELECT ROUND(@val,0,1)\n"
},
{
"answer_id": 20858286,
"author": "Jai",
"author_id": 3070147,
"author_profile": "https://Stackoverflow.com/users/3070147",
"pm_score": 4,
"selected": false,
"text": "CAST(ROUND(10.0055,2,0) AS NUMERIC(10,2))\n"
},
{
"answer_id": 36606943,
"author": "Lukasz Szozda",
"author_id": 5070879,
"author_profile": "https://Stackoverflow.com/users/5070879",
"pm_score": 2,
"selected": false,
"text": "ODBC TRUNCATE DECLARE @value DECIMAL(18,3) =123.456;\n\nSELECT @value AS val, {fn TRUNCATE(@value, 2)} AS result\n LiveDemo ╔═════════╦═════════╗\n║ val ║ result ║\n╠═════════╬═════════╣\n║ 123,456 ║ 123,450 ║\n╚═════════╩═════════╝\n ROUND"
},
{
"answer_id": 41881349,
"author": "KeithL",
"author_id": 3325290,
"author_profile": "https://Stackoverflow.com/users/3325290",
"pm_score": 1,
"selected": false,
"text": "declare @num decimal(9,5) = 123.456\n\nselect round(@num-.005,2)\n"
},
{
"answer_id": 49507245,
"author": "tukan",
"author_id": 6059896,
"author_profile": "https://Stackoverflow.com/users/6059896",
"pm_score": 0,
"selected": false,
"text": "SUBSTRING('123.456', 1, CHARINDEX('.', '123.456') + 2)\n"
},
{
"answer_id": 57759691,
"author": "Ishwor Bhusal",
"author_id": 10480983,
"author_profile": "https://Stackoverflow.com/users/10480983",
"pm_score": 0,
"selected": false,
"text": "SELECT TRUNCATE(MAX(LAT_N),4)\nFROM STATION\nWHERE LAT_N < 137.23453;\n"
},
{
"answer_id": 57942938,
"author": "Dawood Zaidi",
"author_id": 7938407,
"author_profile": "https://Stackoverflow.com/users/7938407",
"pm_score": 2,
"selected": false,
"text": "SELECT CAST(Value as Decimal(10,2)) FROM TABLE_NAME;\n"
},
{
"answer_id": 64183589,
"author": "Adrita Sharma",
"author_id": 7603109,
"author_profile": "https://Stackoverflow.com/users/7603109",
"pm_score": 1,
"selected": false,
"text": "SELECT cast(round(123.456,2,1) as decimal(18,2)) \n"
},
{
"answer_id": 65255378,
"author": "Harshit Mahajan",
"author_id": 10566155,
"author_profile": "https://Stackoverflow.com/users/10566155",
"pm_score": 3,
"selected": false,
"text": "ROUND(number, decimals, operation)\n SELECT ROUND(235.415, 2, 1)\n 235.410 SELECT ROUND(235.415, 0, 1)\n 235.000 0 cast SELECT CAST(ROUND(235.415, 0, 1) AS INT)\n 235"
},
{
"answer_id": 70211618,
"author": "Andrey Vasilyev",
"author_id": 11099129,
"author_profile": "https://Stackoverflow.com/users/11099129",
"pm_score": 1,
"selected": false,
"text": "89.0904987 89.09 select cast(yourColumnName as decimal(18,2))\n decimal(18,2) select cast(89.0904987 as decimal(18,2))\n 89.09"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105/"
] |
44,048 |
<p>I've got an Apache server that has one access log file that is topping 600MB. This makes it really hard to search the file or parse it.<br>
What software or modules for Apache are available that will make a daily copy of my access file to make it more manageable?</p>
|
[
{
"answer_id": 44067,
"author": "Eric Hogue",
"author_id": 4137,
"author_profile": "https://Stackoverflow.com/users/4137",
"pm_score": 3,
"selected": false,
"text": "logrotate /etc/logrotate.conf weekly daily compress rotate 4"
},
{
"answer_id": 44096,
"author": "Brian",
"author_id": 683,
"author_profile": "https://Stackoverflow.com/users/683",
"pm_score": 5,
"selected": false,
"text": "ErrorLog \"|/usr/bin/cronolog /path/to/logs/%Y-%m-%d/error.log\"\nCustomLog \"|/usr/bin/cronolog /path/to/logs/%Y-%m-%d/access.log\" combined\n"
},
{
"answer_id": 355725,
"author": "alimack",
"author_id": 39447,
"author_profile": "https://Stackoverflow.com/users/39447",
"pm_score": 4,
"selected": false,
"text": "CustomLog '|\" \"*Apache-Path/bin/rotatelogs.exe\" \n \"**Apache-Path*/logs/backup/internet_access_%d-%m-%y.log\" 86400' combined\n"
},
{
"answer_id": 6419036,
"author": "Bipin",
"author_id": 807570,
"author_profile": "https://Stackoverflow.com/users/807570",
"pm_score": 2,
"selected": false,
"text": "ErrorLog \"|bin/rotatelogs /var/logs/errorlog.%Y-%m-%d-%H_%M_%S 5M\" \n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2863/"
] |
44,066 |
<p>Is it possible to pass a reference to a function to another function in F#? Specifically, I'd like to pass lambda functions like</p>
<p>foo(fun x -> x ** 3)</p>
<p>More specifically, I need to know how I would refer to the passed function in a function that I wrote myself.</p>
|
[
{
"answer_id": 44079,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": true,
"text": "> List.map (fun x -> x % 2 = 0) [1 .. 5];;\n\nval it : bool list\n= [false; true; false; true; false]\n"
},
{
"answer_id": 44082,
"author": "nickd",
"author_id": 2373,
"author_profile": "https://Stackoverflow.com/users/2373",
"pm_score": 2,
"selected": false,
"text": "let myFunction f =\n f 1 2 3\n"
},
{
"answer_id": 60508,
"author": "Michiel Borkent",
"author_id": 6264,
"author_profile": "https://Stackoverflow.com/users/6264",
"pm_score": 2,
"selected": false,
"text": "let functionThatTakesaFunctionAndAList f l = List.map f l\n functionThatTakesaFunctionAndAList (fun x -> x ** 3.0) [1.0;2.0;3.0]\n functionThatTakesaFunctionAndAList f f float list = [1.0; 8.0; 27.0]\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2270/"
] |
44,078 |
<p>I am trying to write a regular expression to strip all HTML with the exception of links (the <code><a href</code> and <code></a></code> tags respectively. It does not have to be 100% secure (I am not worried about injection attacks or anything as I am parsing content that has already been approved and published into a <a href="http://en.wikipedia.org/wiki/SWF" rel="noreferrer">SWF</a> movie).</p>
<p>The original "strip tags" regular expression I'm using was <code><(.|\n)+?></code>, and I tried to modify it to <code><([^a]|\n)+?></code>, but that of course will allow any tag that has an <strong>a</strong> in it rather than one that has it in the beginning, with a space.</p>
<p>Not that it should really matter, but in case anyone cares to know I am writing this in <a href="http://en.wikipedia.org/wiki/ActionScript#ActionScript_3.0" rel="noreferrer">ActionScript 3.0</a> for a <a href="http://en.wikipedia.org/wiki/Adobe_Flash" rel="noreferrer">Flash</a> movie.</p>
|
[
{
"answer_id": 44088,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": -1,
"selected": false,
"text": "<[^a](.|\\n)+?>\n"
},
{
"answer_id": 44124,
"author": "Xetius",
"author_id": 274,
"author_profile": "https://Stackoverflow.com/users/274",
"pm_score": 6,
"selected": true,
"text": "<(?!\\/?a(?=>|\\s.*>))\\/?.*?>\n s/<(?!\\/?a(?=>|\\s.*>))\\/?.*?>//g;\n"
},
{
"answer_id": 1968498,
"author": "Qamar ",
"author_id": 237660,
"author_profile": "https://Stackoverflow.com/users/237660",
"pm_score": 0,
"selected": false,
"text": "{<(?!i|b|h[1-6]|/i|/b|/h[1-6][\\s|>|/])[^>]*>}\n"
},
{
"answer_id": 23640549,
"author": "Geremia",
"author_id": 1429450,
"author_profile": "https://Stackoverflow.com/users/1429450",
"pm_score": -1,
"selected": false,
"text": "strip_tags() <a><p><font><b><i><sup> cat input.htm | tr -d '\\n' | php -r '$input=fgets(STDIN); echo strip_tags($input,\"<a><p><font><b><i><sup>\");' | tidy -i -wrap 0 -o output.htm\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1306/"
] |
44,084 |
<p>That's it. If you want to document a function or a class, you put a string just after the definition. For instance:</p>
<pre><code>def foo():
"""This function does nothing."""
pass
</code></pre>
<p>But what about a module? How can I document what a <em>file.py</em> does?</p>
|
[
{
"answer_id": 44095,
"author": "Grégoire Cachet",
"author_id": 1044,
"author_profile": "https://Stackoverflow.com/users/1044",
"pm_score": 7,
"selected": true,
"text": "__init__.py"
},
{
"answer_id": 23450896,
"author": "Brad Koch",
"author_id": 425313,
"author_profile": "https://Stackoverflow.com/users/425313",
"pm_score": 7,
"selected": false,
"text": "\"\"\"\nYour module's verbose yet thorough docstring.\n\"\"\"\n\nimport foo\n\n# ...\n __init__.py"
},
{
"answer_id": 41913969,
"author": "Vlad Bezden",
"author_id": 30038,
"author_profile": "https://Stackoverflow.com/users/30038",
"pm_score": 5,
"selected": false,
"text": "\"\"\"Example Google style docstrings.\n\nThis module demonstrates documentation as specified by the `Google\nPython Style Guide`_. Docstrings may extend over multiple lines.\nSections are created with a section header and a colon followed by a\nblock of indented text.\n\nExample:\n Examples can be given using either the ``Example`` or ``Examples``\n sections. Sections support any reStructuredText formatting, including\n literal blocks::\n\n $ python example_google.py\n\nSection breaks are created by resuming unindented text. Section breaks\nare also implicitly created anytime a new section starts.\n\nAttributes:\n module_level_variable1 (int): Module level variables may be documented in\n either the ``Attributes`` section of the module docstring, or in an\n inline docstring immediately following the variable.\n\n Either form is acceptable, but the two should not be mixed. Choose\n one convention to document module level variables and be consistent\n with it.\n\nTodo:\n * For module TODOs\n * You have to also use ``sphinx.ext.todo`` extension\n\n.. _Google Python Style Guide: \nhttp://google.github.io/styleguide/pyguide.html\n\n\"\"\"\n\nmodule_level_variable1 = 12345\n\ndef my_function(): \n pass \n... \n...\n"
},
{
"answer_id": 57529785,
"author": "Kermit",
"author_id": 5739514,
"author_profile": "https://Stackoverflow.com/users/5739514",
"pm_score": 2,
"selected": false,
"text": "\"\"\"\nPlease refer to the documentation provided in the README.md,\nwhich can be found at gorpyter's PyPI URL: https://pypi.org/project/gorpyter/\n\"\"\"\n\n# <IMPORT_DEPENDENCIES>\n\ndef setup():\n \"\"\"Verify your Python and R dependencies.\"\"\"\n help(<YOUR_PACKAGE>) DESCRIPTION\n Please refer to the documentation provided in the README.md,\n which can be found at gorpyter's PyPI URL: https://pypi.org/project/gorpyter/\n\n\nFUNCTIONS\n setup()\n Verify your Python and R dependencies.\n DESCRIPTION"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1679/"
] |
44,089 |
<p>I have connected to a server via SFTP using FileZilla and accepted adding the server's SSH key to the key cache in FileZilla. </p>
<p>How can I extract this cached key to a keyfile so that may use it through other SFTP applications that require a keyfile be made available? </p>
<p>I have not been able to find anything in the FileZilla documentation related to this.</p>
|
[
{
"answer_id": 44712,
"author": "Doug Porter",
"author_id": 4311,
"author_profile": "https://Stackoverflow.com/users/4311",
"pm_score": 3,
"selected": false,
"text": "ssh-keyscan -t rsa <my_ftp_ip_address> > c:\\known_hosts\nssh-keyscan -t dsa <my_ftp_ip_address> > c:\\known_hosts\n"
},
{
"answer_id": 12189504,
"author": "Nasri Najib",
"author_id": 1631784,
"author_profile": "https://Stackoverflow.com/users/1631784",
"pm_score": 3,
"selected": false,
"text": "C:\\Program Files\\OpenSSH\\bin>mkgroup -l >> ..\\etc\\group\nC:\\Program Files\\OpenSSH\\bin>mkpasswd -l >> ..\\etc\\passwd\nC:\\Program Files\\OpenSSH\\bin>net start opensshd\nThe OpenSSH Server service is starting.\nThe OpenSSH Server service was started successfully.\nC:\\Program Files\\OpenSSH\\bin>ssh-keyscan -t rsa vivo.sg.m.com > c:\\known_hosts\nvivo.sg.m.com SSH-2.0-Sun_SSH_1.1\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4311/"
] |
44,100 |
<p>This is a fairly trivial matter, but I'm curious to hear people's opinions on it.</p>
<p>If I have a Dictionary which I'm access through properties, which of these formats would you prefer for the property?</p>
<pre><code>/// <summary>
/// This class's FirstProperty property
/// </summary>
[DefaultValue("myValue")]
public string FirstProperty {
get {
return Dictionary["myKey"];
}
set {
Dictionary["myKey"] = value;
}
</code></pre>
<p>This is probably the typical way of doing it. It's fairly efficient, easy to understand, etc. The only disadvantage is with a longer or more complex key it would be possible to misspell it or change only one instance or something, leading me to this:</p>
<pre><code>/// <summary>
/// This class's SecondProperty property
/// </summary>
[DefaultValue("myValue")]
private const string DICT_MYKEY = "myKey"
public string SecondProperty {
get {
return Dictionary[DICT_MYKEY];
}
set {
Dictionary[DICT_MYKEY] = value;
}
</code></pre>
<p>Which is marginally more complicated, but seems to offer additional safety, and is closer to what I would think of as the "Code Complete" solution. The downside is that when you also have a /// block and a [DefaultValue()] block above the property already, it starts getting a bit crowded up there.</p>
<p>So which do you like better, and why? Does anybody have any better ideas?</p>
|
[
{
"answer_id": 44134,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "public string FirstProperty {\nget {\n return Dictionary[PropertyName()];\n}\nset {\n Dictionary[PropertyName()] = value;\n}\n\nprivate string PropertyName()\n{\n return new StackFrame(1).GetMethod().Name.Substring(4);\n}\n"
},
{
"answer_id": 44140,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 0,
"selected": false,
"text": "const"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
] |
44,101 |
<p>How do you insert invisible watermarks in images for copyright purposes? I'm looking for a python library.</p>
<p>What algorithm do you use? What about performance and efficiency?</p>
|
[
{
"answer_id": 45232,
"author": "tghw",
"author_id": 2363,
"author_profile": "https://Stackoverflow.com/users/2363",
"pm_score": 2,
"selected": false,
"text": "def reduceOpacity(im, opacity):\n \"\"\"Returns an image with reduced opacity.\"\"\"\n assert opacity >= 0 and opacity <= 1\n if im.mode != 'RGBA':\n im = im.convert('RGBA')\n else:\n im = im.copy()\n alpha = im.split()[3]\n alpha = ImageEnhance.Brightness(alpha).enhance(opacity)\n im.putalpha(alpha)\n return im\n\ndef watermark(im, mark, position, opacity=1):\n \"\"\"Adds a watermark to an image.\"\"\"\n if opacity < 1:\n mark = reduceOpacity(mark, opacity)\n if im.mode != 'RGBA':\n im = im.convert('RGBA')\n # create a transparent layer the size of the image and draw the\n # watermark in that layer.\n layer = Image.new('RGBA', im.size, (0,0,0,0))\n if position == 'tile':\n for y in range(0, im.size[1], mark.size[1]):\n for x in range(0, im.size[0], mark.size[0]):\n layer.paste(mark, (x, y))\n elif position == 'scale':\n # scale, but preserve the aspect ratio\n ratio = min(float(im.size[0]) / mark.size[0], float(im.size[1]) / mark.size[1])\n w = int(mark.size[0] * ratio)\n h = int(mark.size[1] * ratio)\n mark = mark.resize((w, h))\n layer.paste(mark, ((im.size[0] - w) / 2, (im.size[1] - h) / 2))\n else:\n layer.paste(mark, position)\n # composite the watermark with the layer\n return Image.composite(layer, im, layer)\n\nimg = Image.open('/path/to/image/to/be/watermarked.jpg')\n\nmark1 = Image.open('/path/to/watermark1.png')\nmark2 = Image.open('/path/to/watermark2.png')\n\nimg = watermark(img, mark1, (img.size[0]-mark1.size[0]-5, img.size[1]-mark1.size[1]-5), 0.5)\nimg = watermark(img, mark2, 'scale', 0.01)\n"
},
{
"answer_id": 4063844,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 2,
"selected": false,
"text": "from __future__ import division\n\nimport math, os, array, random\nimport itertools as it\nimport Image as I\nimport sys\n\ndef encode(txtfn, imgfn):\n with open(txtfn, \"rb\") as ifp:\n txtdata= ifp.read()\n txtdata= txtdata.encode('zip')\n\n img= I.open(imgfn).convert(\"RGB\")\n pixelcount= img.size[0]*img.size[1]\n## sys.stderr.write(\"image %dx%d\\n\" % img.size)\n\n factor= len(txtdata) / pixelcount\n width= int(math.ceil(img.size[0]*factor**.5))\n height= int(math.ceil(img.size[1]*factor**.5))\n\n pixelcount= width * height\n if pixelcount < len(txtdata): # just a sanity check\n sys.stderr.write(\"phase 2, %d bytes in %d pixels?\\n\" % (len(txtdata), pixelcount))\n sys.exit(1)\n## sys.stderr.write(\"%d bytes in %d pixels (%dx%d)\\n\" % (len(txtdata), pixelcount, width, height))\n img= img.resize( (width, height), I.ANTIALIAS)\n\n txtarr= array.array('B')\n txtarr.fromstring(txtdata)\n txtarr.extend(random.randrange(256) for x in xrange(len(txtdata) - pixelcount))\n\n newimg= img.copy()\n newimg.putdata([\n (\n r & 0xf8 |(c & 0xe0)>>5,\n g & 0xfc |(c & 0x18)>>3,\n b & 0xf8 |(c & 0x07),\n )\n for (r, g, b), c in it.izip(img.getdata(), txtarr)])\n newimg.save(os.path.splitext(imgfn)[0]+'.png', optimize=1, compression=9)\n\ndef decode(imgfn, txtfn):\n img= I.open(imgfn)\n with open(txtfn, 'wb') as ofp:\n arrdata= array.array('B',\n ((r & 0x7) << 5 | (g & 0x3) << 3 | (b & 0x7)\n for r, g, b in img.getdata())).tostring()\n findata= arrdata.decode('zip')\n ofp.write(findata)\n\nif __name__ == \"__main__\":\n if sys.argv[1] == 'e':\n encode(sys.argv[2], sys.argv[3])\n elif sys.argv[1] == 'd':\n decode(sys.argv[2], sys.argv[3])\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1044/"
] |
44,109 |
<p>What's the best way to extend the User model (bundled with Django's authentication app) with custom fields? I would also possibly like to use the email as the username (for authentication purposes).</p>
<p>I've already seen a <a href="http://scottbarnham.com/blog/2008/08/21/extending-the-django-user-model-with-inheritance/" rel="noreferrer">few</a> <a href="http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/" rel="noreferrer">ways</a> to do it, but can't decide on which one is the best.</p>
|
[
{
"answer_id": 44178,
"author": "Ryan Duffield",
"author_id": 2696,
"author_profile": "https://Stackoverflow.com/users/2696",
"pm_score": 9,
"selected": true,
"text": "OneToOneField(User) User django.contrib.auth.models.User User"
},
{
"answer_id": 965883,
"author": "Raisins",
"author_id": 75803,
"author_profile": "https://Stackoverflow.com/users/75803",
"pm_score": 8,
"selected": false,
"text": "#in models.py\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\n\nclass UserProfile(models.Model): \n user = models.OneToOneField(User) \n #other fields here\n\n def __str__(self): \n return \"%s's profile\" % self.user \n\ndef create_user_profile(sender, instance, created, **kwargs): \n if created: \n profile, created = UserProfile.objects.get_or_create(user=instance) \n\npost_save.connect(create_user_profile, sender=User) \n\n#in settings.py\nAUTH_PROFILE_MODULE = 'YOURAPP.UserProfile'\n user.get_profile().whatever\n AUTH_PROFILE_MODULE"
},
{
"answer_id": 12648124,
"author": "Ondrej Slinták",
"author_id": 206720,
"author_profile": "https://Stackoverflow.com/users/206720",
"pm_score": 8,
"selected": false,
"text": "AUTH_USER_MODEL AbstractBaseUser AbstractUser from django.db import models\nfrom django.contrib.auth.models import (\n BaseUserManager, AbstractBaseUser\n)\n\n\nclass MyUserManager(BaseUserManager):\n def create_user(self, email, date_of_birth, password=None):\n \"\"\"\n Creates and saves a User with the given email, date of\n birth and password.\n \"\"\"\n if not email:\n raise ValueError('Users must have an email address')\n\n user = self.model(\n email=MyUserManager.normalize_email(email),\n date_of_birth=date_of_birth,\n )\n\n user.set_password(password)\n user.save(using=self._db)\n return user\n\n def create_superuser(self, username, date_of_birth, password):\n \"\"\"\n Creates and saves a superuser with the given email, date of\n birth and password.\n \"\"\"\n u = self.create_user(username,\n password=password,\n date_of_birth=date_of_birth\n )\n u.is_admin = True\n u.save(using=self._db)\n return u\n\n\nclass MyUser(AbstractBaseUser):\n email = models.EmailField(\n verbose_name='email address',\n max_length=255,\n unique=True,\n )\n date_of_birth = models.DateField()\n is_active = models.BooleanField(default=True)\n is_admin = models.BooleanField(default=False)\n\n objects = MyUserManager()\n\n USERNAME_FIELD = 'email'\n REQUIRED_FIELDS = ['date_of_birth']\n\n def get_full_name(self):\n # The user is identified by their email address\n return self.email\n\n def get_short_name(self):\n # The user is identified by their email address\n return self.email\n\n def __unicode__(self):\n return self.email\n\n def has_perm(self, perm, obj=None):\n \"Does the user have a specific permission?\"\n # Simplest possible answer: Yes, always\n return True\n\n def has_module_perms(self, app_label):\n \"Does the user have permissions to view the app `app_label`?\"\n # Simplest possible answer: Yes, always\n return True\n\n @property\n def is_staff(self):\n \"Is the user a member of staff?\"\n # Simplest possible answer: All admins are staff\n return self.is_admin\n"
},
{
"answer_id": 16125609,
"author": "Riccardo Galli",
"author_id": 210090,
"author_profile": "https://Stackoverflow.com/users/210090",
"pm_score": 6,
"selected": false,
"text": "from django.contrib.auth.models import AbstractUser\nfrom django.db import models\nfrom django.utils.translation import ugettext_lazy as _\n\nclass UserProfile(AbstractUser):\n age = models.PositiveIntegerField(_(\"age\"))\n # supposing you put it in apps/profiles/models.py\nAUTH_USER_MODEL = \"profiles.UserProfile\"\n from django.contrib.auth import get_user_model\n\nUser = get_user_model()\n"
},
{
"answer_id": 36592330,
"author": "Massimo Variolo",
"author_id": 752102,
"author_profile": "https://Stackoverflow.com/users/752102",
"pm_score": 4,
"selected": false,
"text": "from django.contrib.auth.models import User\n\nclass Employee(models.Model):\n user = models.OneToOneField(User)\n department = models.CharField(max_length=100)\n\n>>> u = User.objects.get(username='fsmith')\n>>> freds_department = u.employee.department\n"
},
{
"answer_id": 38024560,
"author": "Atul Yadav",
"author_id": 6507549,
"author_profile": "https://Stackoverflow.com/users/6507549",
"pm_score": 4,
"selected": false,
"text": "from django.db.models.signals import *\nfrom __future__ import unicode_literals\n\nclass UserProfile(models.Model):\n\n user_name = models.OneToOneField(User, related_name='profile')\n city = models.CharField(max_length=100, null=True)\n\n def __unicode__(self): # __str__\n return unicode(self.user_name)\n\ndef create_user_profile(sender, instance, created, **kwargs):\n if created:\n userProfile.objects.create(user_name=instance)\n\npost_save.connect(create_user_profile, sender=User)\n from django.db.models.signals import *\nfrom __future__ import unicode_literals\n\nclass UserProfile(models.Model):\n\n user_name = models.OneToOneField(User)\n city = models.CharField(max_length=100)\n\n def __unicode__(self): # __str__\n return unicode(self.user_name)\n from django import forms\nfrom django.forms import ModelForm\nfrom betterforms.multiform import MultiModelForm\nfrom django.contrib.auth.forms import UserCreationForm\nfrom .models import *\n\nclass ProfileForm(ModelForm):\n\n class Meta:\n model = Employee\n exclude = ('user_name',)\n\n\nclass addUserMultiForm(MultiModelForm):\n form_classes = {\n 'user':UserCreationForm,\n 'profile':ProfileForm,\n }\n from django.shortcuts import redirect\nfrom .models import *\nfrom .forms import *\nfrom django.views.generic import CreateView\n\nclass AddUser(CreateView):\n form_class = AddUserMultiForm\n template_name = \"add-user.html\"\n success_url = '/your-url-after-user-created'\n\n def form_valid(self, form):\n user = form['user'].save()\n profile = form['profile'].save(commit=False)\n profile.user_name = User.objects.get(username= user.username)\n profile.save()\n return redirect(self.success_url)\n <!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"UTF-8\">\n <title>Title</title>\n </head>\n <body>\n <form action=\".\" method=\"post\">\n {% csrf_token %}\n {{ form }} \n <button type=\"submit\">Add</button>\n </form>\n </body>\n</html>\n from django.conf.urls import url, include\nfrom appName.views import *\nurlpatterns = [\n url(r'^add-user/$', AddUser.as_view(), name='add-user'),\n]\n"
},
{
"answer_id": 51511108,
"author": "Milad Khodabandehloo",
"author_id": 9083861,
"author_profile": "https://Stackoverflow.com/users/9083861",
"pm_score": 2,
"selected": false,
"text": "from django.db import models\nfrom django.contrib.auth.models import PermissionsMixin, AbstractBaseUser, BaseUserManager\n\nclass User_manager(BaseUserManager):\n def create_user(self, username, email, gender, nickname, password):\n email = self.normalize_email(email)\n user = self.model(username=username, email=email, gender=gender, nickname=nickname)\n user.set_password(password)\n user.save(using=self.db)\n return user\n\n def create_superuser(self, username, email, gender, password, nickname=None):\n user = self.create_user(username=username, email=email, gender=gender, nickname=nickname, password=password)\n user.is_superuser = True\n user.is_staff = True\n user.save()\n return user\n\n\n\n class User(PermissionsMixin, AbstractBaseUser):\n username = models.CharField(max_length=32, unique=True, )\n email = models.EmailField(max_length=32)\n gender_choices = [(\"M\", \"Male\"), (\"F\", \"Female\"), (\"O\", \"Others\")]\n gender = models.CharField(choices=gender_choices, default=\"M\", max_length=1)\n nickname = models.CharField(max_length=32, blank=True, null=True)\n\n is_active = models.BooleanField(default=True)\n is_staff = models.BooleanField(default=False)\n REQUIRED_FIELDS = [\"email\", \"gender\"]\n USERNAME_FIELD = \"username\"\n objects = User_manager()\n\n def __str__(self):\n return self.username\n settings.py AUTH_USER_MODEL = 'YourApp.User'\n"
},
{
"answer_id": 60355460,
"author": "NeerajSahani",
"author_id": 12270394,
"author_profile": "https://Stackoverflow.com/users/12270394",
"pm_score": 1,
"selected": false,
"text": "from django.contrib.auth.models import User\nclass CustomUser(User):\n profile_pic = models.ImageField(upload_to='...')\n other_field = models.CharField()\n"
},
{
"answer_id": 64312498,
"author": "Shahriar.M",
"author_id": 3777814,
"author_profile": "https://Stackoverflow.com/users/3777814",
"pm_score": 2,
"selected": false,
"text": "models.py from django.db import models\nfrom django.contrib.auth.models import User\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n extra_Field_1 = models.CharField(max_length=25, blank=True)\n extra_Field_2 = models.CharField(max_length=25, blank=True)\n\n\n@receiver(post_save, sender=User)\ndef create_user_profile(sender, instance, created, **kwargs):\n if created:\n Profile.objects.create(user=instance)\n\n@receiver(post_save, sender=User)\ndef save_user_profile(sender, instance, **kwargs):\n instance.profile.save()\n <h2>{{ user.get_full_name }}</h2>\n<ul>\n <li>Username: {{ user.username }}</li>\n <li>Location: {{ user.profile.extra_Field_1 }}</li>\n <li>Birth Date: {{ user.profile.extra_Field_2 }}</li>\n</ul>\n views.py def update_profile(request, user_id):\n user = User.objects.get(pk=user_id)\n user.profile.extra_Field_1 = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit...'\n user.save()\n"
},
{
"answer_id": 65976535,
"author": "Ajay Lingayat",
"author_id": 12132509,
"author_profile": "https://Stackoverflow.com/users/12132509",
"pm_score": 0,
"selected": false,
"text": "Profile OneToOneField related_name from django.db import models\nfrom django.contrib.auth.models import *\nfrom django.dispatch import receiver\nfrom django.db.models.signals import post_save\n\nclass Profile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user_profile')\n\n def __str__(self):\n return self.user.username\n\n@receiver(post_save, sender=User)\ndef create_profile(sender, instance, created, **kwargs):\n try:\n if created:\n Profile.objects.create(user=instance).save()\n except Exception as err:\n print('Error creating user profile!')\n User related_name from django.http import HttpResponse\n\ndef home(request):\n profile = f'profile of {request.user.user_profile}'\n return HttpResponse(profile)\n"
},
{
"answer_id": 67204210,
"author": "Alphonse Prakash",
"author_id": 13344453,
"author_profile": "https://Stackoverflow.com/users/13344453",
"pm_score": 3,
"selected": false,
"text": "from django.db import models\nfrom django.contrib.auth.models import AbstractUser\n\nclass CustomUser(AbstractUser):\n extra_field=models.CharField(max_length=40)\n AUTH_USER_MODEL ='users.CustomUser'\n"
},
{
"answer_id": 72434745,
"author": "Mahammadhusain kadiwala",
"author_id": 19205926,
"author_profile": "https://Stackoverflow.com/users/19205926",
"pm_score": 2,
"selected": false,
"text": "from django.db import models\nfrom django.contrib.auth.models import AbstractUser\n# Create your models here.\n\n\nclass CustomUser(AbstractUser):\n mobile_no = models.IntegerField(blank=True,null=True)\n date_of_birth = models.DateField(blank=True,null=True)\n #settings.py\n\nAUTH_USER_MODEL = 'myapp.CustomUser'\n @admin.register(CustomUser)\nclass CustomUserAdmin(admin.ModelAdmin):\n list_display = (\"username\",\"first_name\",\"last_name\",\"email\",\"date_of_birth\", \"mobile_no\")\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2841/"
] |
44,131 |
<p>I need to display a variable-length message and allow the text to be selectable. I have made the TextBox ReadOnly which does not allow the text to be edited, but the input caret is still shown. </p>
<p>The blinking input caret is confusing. How do I hide it?</p>
|
[
{
"answer_id": 44146,
"author": "Simon Gillbee",
"author_id": 756,
"author_profile": "https://Stackoverflow.com/users/756",
"pm_score": 1,
"selected": false,
"text": "Enable=false System.Drawing.SystemColors SystemColors.ControlLight"
},
{
"answer_id": 44174,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 5,
"selected": true,
"text": "[DllImport(\"user32.dll\")]\nstatic extern bool HideCaret(IntPtr hWnd);\npublic void HideCaret()\n{\n HideCaret(someTextBox.Handle);\n}\n"
},
{
"answer_id": 16515169,
"author": "Uwe Keim",
"author_id": 107625,
"author_profile": "https://Stackoverflow.com/users/107625",
"pm_score": 2,
"selected": false,
"text": "TextEdit ShowCaret HideCaret public class MyTextEdit : TextEdit\n{\n private bool _wantHideCaret;\n\n public void DoHideCaret()\n {\n HideCaret();\n\n _wantHideCaret = true;\n }\n\n public void DoShowCaret()\n {\n ShowCaret();\n\n _wantHideCaret = false;\n }\n\n protected override void OnGotFocus(EventArgs e)\n {\n base.OnGotFocus(e);\n\n if (_wantHideCaret)\n {\n HideCaret();\n }\n }\n}\n TextEdit DoHideCaret()"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1042/"
] |
44,145 |
<p>What's the best way to deal with a sharded database in Rails? Should the sharding be handled at the application layer, the active record layer, the database driver layer, a proxy layer, or something else altogether? What are the pros and cons of each?</p>
|
[
{
"answer_id": 68921027,
"author": "Oshan Wisumperuma",
"author_id": 3011280,
"author_profile": "https://Stackoverflow.com/users/3011280",
"pm_score": 2,
"selected": false,
"text": "production:\n primary:\n database: my_primary_database\n adapter: mysql2\n primary_replica:\n database: my_primary_database\n adapter: mysql2\n replica: true\n primary_shard_one:\n database: my_primary_shard_one\n adapter: mysql2\n primary_shard_one_replica:\n database: my_primary_shard_one\n adapter: mysql2\n replica: true\n class ApplicationRecord < ActiveRecord::Base\n self.abstract_class = true\n\n connects_to shards: {\n default: { writing: :primary, reading: :primary_replica },\n shard_one: { writing: :primary_shard_one, reading: :primary_shard_one_replica }\n }\nend\n ActiveRecord::Base.connected_to(role: :writing, shard: :shard_one) do\n @id = Person.create! # Creates a record in shard one\nend\n\nActiveRecord::Base.connected_to(role: :writing, shard: :shard_one) do\n Person.find(@id) # Can't find record, doesn't exist because it was created\n # in the default shard\nend\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4061/"
] |
44,153 |
<p>Like the title says: Can reflection give you the name of the currently executing method.</p>
<p>I'm inclined to guess not, because of the Heisenberg problem. How do you call a method that will tell you the current method without changing what the current method is? But I'm hoping someone can prove me wrong there.</p>
<p><strong>Update:</strong> </p>
<ul>
<li>Part 2: Could this be used to look inside code for a property as well? </li>
<li>Part 3: What would the performance be like?</li>
</ul>
<p><strong>Final Result</strong><br>
I learned about MethodBase.GetCurrentMethod(). I also learned that not only can I create a stack trace, I can create only the exact frame I need if I want. </p>
<p>To use this inside a property, just take a .Substring(4) to remove the 'set_' or 'get_'.</p>
|
[
{
"answer_id": 44165,
"author": "Lex",
"author_id": 4109,
"author_profile": "https://Stackoverflow.com/users/4109",
"pm_score": 4,
"selected": false,
"text": "public static T CreateWrapper<T>(Exception innerException, params object[] parameterValues) where T : Exception, new()\n{\n if (parameterValues == null)\n {\n parameterValues = new object[0];\n }\n\n Exception exception = null;\n StringBuilder builder = new StringBuilder();\n MethodBase method = new StackFrame(2).GetMethod();\n ParameterInfo[] parameters = method.GetParameters();\n builder.AppendFormat(CultureInfo.InvariantCulture, ExceptionFormat, new object[] { method.DeclaringType.Name, method.Name });\n if ((parameters.Length > 0) || (parameterValues.Length > 0))\n {\n builder.Append(GetParameterList(parameters, parameterValues));\n }\n\n exception = (Exception)Activator.CreateInstance(typeof(T), new object[] { builder.ToString(), innerException });\n return (T)exception;\n}\n MethodBase method = new StackFrame(2).GetMethod();\n MethodBase.GetCurrentMethod()\n public void Foo ([CallerMemberName] string methodName = null)\n"
},
{
"answer_id": 44166,
"author": "Ed Guiness",
"author_id": 4200,
"author_profile": "https://Stackoverflow.com/users/4200",
"pm_score": 8,
"selected": false,
"text": "async System.Reflection.MethodBase.GetCurrentMethod().Name;\n async"
},
{
"answer_id": 44170,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 4,
"selected": false,
"text": "MethodBase method = MethodBase.GetCurrentMethod();\nConsole.WriteLine(method.Name);\n Main"
},
{
"answer_id": 44171,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 3,
"selected": false,
"text": "StackTrace st = new StackTrace(true);\n // The first frame will be the method you want (However, see caution below)\nst.GetFrames();\n [MethodImpl(MethodImplOptions.NoInlining)]\n"
},
{
"answer_id": 44215,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 6,
"selected": false,
"text": "string MethodName = new StackFrame(0).GetMethod().Name;\n private string GetPropertyName()\n{ //.SubString(4) strips the property prefix (get|set) from the name\n return new StackFrame(1).GetMethod().Name.Substring(4);\n}\n"
},
{
"answer_id": 172562,
"author": "jesal",
"author_id": 20092,
"author_profile": "https://Stackoverflow.com/users/20092",
"pm_score": 2,
"selected": false,
"text": "StackFrame frame = new StackFrame(1);\nframe.GetMethod().Name; //Gets the current method name\n\nMethodBase method = frame.GetMethod();\nmethod.DeclaringType.Name //Gets the current class name\n"
},
{
"answer_id": 15310053,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 8,
"selected": true,
"text": "protected void SetProperty<T>(T value, [CallerMemberName] string property = null)\n{\n this.propertyValues[property] = value;\n OnPropertyChanged(property);\n}\n\npublic string SomeProperty\n{\n set { SetProperty(value); }\n}\n"
},
{
"answer_id": 21295459,
"author": "drzaus",
"author_id": 1037948,
"author_profile": "https://Stackoverflow.com/users/1037948",
"pm_score": 4,
"selected": false,
"text": "void Main()\n{\n // from http://blogs.msdn.com/b/webdevelopertips/archive/2009/06/23/tip-83-did-you-know-you-can-get-the-name-of-the-calling-method-from-the-stack-using-reflection.aspx\n // and https://stackoverflow.com/questions/2652460/c-sharp-how-to-get-the-name-of-the-current-method-from-code\n\n var fn = new methods();\n\n fn.reflection().Dump(\"reflection\");\n fn.stacktrace().Dump(\"stacktrace\");\n fn.inlineconstant().Dump(\"inlineconstant\");\n fn.constant().Dump(\"constant\");\n fn.expr().Dump(\"expr\");\n fn.exprmember().Dump(\"exprmember\");\n fn.callermember().Dump(\"callermember\");\n\n new Perf {\n { \"reflection\", n => fn.reflection() },\n { \"stacktrace\", n => fn.stacktrace() },\n { \"inlineconstant\", n => fn.inlineconstant() },\n { \"constant\", n => fn.constant() },\n { \"expr\", n => fn.expr() },\n { \"exprmember\", n => fn.exprmember() },\n { \"callermember\", n => fn.callermember() },\n }.Vs(\"Method name retrieval\");\n}\n\n// Define other methods and classes here\nclass methods {\n public string reflection() {\n return System.Reflection.MethodBase.GetCurrentMethod().Name;\n }\n public string stacktrace() {\n return new StackTrace().GetFrame(0).GetMethod().Name;\n }\n public string inlineconstant() {\n return \"inlineconstant\";\n }\n const string CONSTANT_NAME = \"constant\";\n public string constant() {\n return CONSTANT_NAME;\n }\n public string expr() {\n Expression<Func<methods, string>> ex = e => e.expr();\n return ex.ToString();\n }\n public string exprmember() {\n return expressionName<methods,string>(e => e.exprmember);\n }\n protected string expressionName<T,P>(Expression<Func<T,Func<P>>> action) {\n // https://stackoverflow.com/a/9015598/1037948\n return ((((action.Body as UnaryExpression).Operand as MethodCallExpression).Object as ConstantExpression).Value as MethodInfo).Name;\n }\n public string callermember([CallerMemberName]string name = null) {\n return name;\n }\n}\n Method name retrieval: (reflection) vs (stacktrace) vs (inlineconstant) vs (constant) vs (expr) vs (exprmember) vs (callermember) \n\n 154673 ticks elapsed ( 15.4673 ms) - reflection\n2588601 ticks elapsed (258.8601 ms) - stacktrace\n 1985 ticks elapsed ( 0.1985 ms) - inlineconstant\n 1385 ticks elapsed ( 0.1385 ms) - constant\n1366706 ticks elapsed (136.6706 ms) - expr\n 775160 ticks elapsed ( 77.516 ms) - exprmember\n 2073 ticks elapsed ( 0.2073 ms) - callermember\n\n\n>> winner: constant\n expr callermember"
},
{
"answer_id": 33020480,
"author": "SharK",
"author_id": 2841325,
"author_profile": "https://Stackoverflow.com/users/2841325",
"pm_score": 3,
"selected": false,
"text": "System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + \".\" + System.Reflection.MethodBase.GetCurrentMethod().Name;\n MethodBase.GetCurrentMethod().DeclaringType.FullName + \".\" + MethodBase.GetCurrentMethod().Name;\n"
},
{
"answer_id": 34505798,
"author": "Adriano Silva Ribeiro",
"author_id": 5034536,
"author_profile": "https://Stackoverflow.com/users/5034536",
"pm_score": 0,
"selected": false,
"text": " /// <summary>\n /// Return the full name of method\n /// </summary>\n /// <param name=\"obj\">Class that calls this method (use Report(this))</param>\n /// <returns></returns>\n public string Report(object obj)\n {\n var reflectedType = new StackTrace().GetFrame(1).GetMethod().ReflectedType;\n if (reflectedType == null) return null;\n\n var i = reflectedType.FullName;\n var ii = new StackTrace().GetFrame(1).GetMethod().Name;\n\n return string.Concat(i, \".\", ii);\n }\n"
},
{
"answer_id": 45594089,
"author": "michael kosak",
"author_id": 8440225,
"author_profile": "https://Stackoverflow.com/users/8440225",
"pm_score": 2,
"selected": false,
"text": "using System.Runtime.CompilerServices;\n.\n.\n.\npublic static class MyMethodName\n{\n public static string Show([CallerMemberName] string name = \"\")\n {\n return name;\n }\n}\n private void button1_Click(object sender, EventArgs e)\n{\n textBox1.Text = MyMethodName.Show();\n}\n\nprivate void button2_Click(object sender, EventArgs e)\n{\n textBox1.Text = MyMethodName.Show();\n}\n"
},
{
"answer_id": 57527607,
"author": "Baglay Vyacheslav",
"author_id": 1361923,
"author_profile": "https://Stackoverflow.com/users/1361923",
"pm_score": -1,
"selected": false,
"text": "new StackTrace().ToString().Split(\"\\r\\n\",StringSplitOptions.RemoveEmptyEntries)[0].Replace(\"at \",\"\").Trim()\n"
},
{
"answer_id": 62810747,
"author": "mr R",
"author_id": 1831734,
"author_profile": "https://Stackoverflow.com/users/1831734",
"pm_score": 2,
"selected": false,
"text": "using System;\n \npublic class Program\n{\n public static void Main()\n {\n \n Console.WriteLine(\"1: {0} {1}\", System.Reflection.MethodBase.GetCurrentMethod().Name, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType);\n OtherMethod();\n }\n \n public static void OtherMethod()\n {\n Console.WriteLine(\"2: {0} {1}\", System.Reflection.MethodBase.GetCurrentMethod().Name, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType);\n }\n}\n 1: Main Program\n2: OtherMethod Program\n"
},
{
"answer_id": 63949974,
"author": "Romerik Rousseau",
"author_id": 2335803,
"author_profile": "https://Stackoverflow.com/users/2335803",
"pm_score": 1,
"selected": false,
"text": "public static string GetCurrentMethodName([System.Runtime.CompilerServices.CallerMemberName] string name = \"\")\n{\n return name;\n}\n"
},
{
"answer_id": 66869691,
"author": "Chef Gladiator",
"author_id": 10870835,
"author_profile": "https://Stackoverflow.com/users/10870835",
"pm_score": 2,
"selected": false,
"text": "namespace my {\n public struct notmacros\n {\n\n[MethodImpl(MethodImplOptions.AggressiveInlining)]\npublic static string \n whoami( [CallerMemberName] string caller_name = null)\n {\n if (string.IsNullOrEmpty(caller_name)) \n return \"unknown\";\n if (string.IsNullOrWhiteSpace(caller_name)) \n return \"unknown\";\n return caller_name;\n }\n }\n} // my namespace\n using static my.notmacros\n // somewhere appropriate\n var my_name = whoami() ;\n"
},
{
"answer_id": 67372375,
"author": "Useme Alehosaini",
"author_id": 13121879,
"author_profile": "https://Stackoverflow.com/users/13121879",
"pm_score": 3,
"selected": false,
"text": "Async //using System.Reflection;\n\nvar myMethodName = MethodBase\n .GetCurrentMethod()\n .DeclaringType\n .Name\n .Substring(1)\n .Split('>')[0];\n"
},
{
"answer_id": 68122310,
"author": "Paul Williams",
"author_id": 420400,
"author_profile": "https://Stackoverflow.com/users/420400",
"pm_score": 2,
"selected": false,
"text": "[MethodImpl(MethodImplOptions.NoInlining)]\npublic static string GetCurrentMethodName()\n{\n var st = new StackTrace();\n var sf = st.GetFrame(1);\n string name = sf.GetMethod().Name;\n\n if (name.Equals(\"MoveNext\"))\n {\n // We're inside an async method\n name = sf.GetMethod().ReflectedType.Name\n .Split(new char[] { '<', '>' }, StringSplitOptions.RemoveEmptyEntries)[0];\n }\n\n return name;\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] |
44,176 |
<p>Is there a way to perform a full text search of a subversion repository, including all the history?</p>
<p>For example, I've written a feature that I used somewhere, but then it wasn't needed, so I svn rm'd the files, but now I need to find it again to use it for something else. The svn log probably says something like "removed unused stuff", and there's loads of checkins like that.</p>
<p><strong>Edit 2016-04-15:</strong> Please note that what is asked here by the term "full text search", is to <strong>search the actual diffs of the commit history, and not filenames and/or commit messages</strong>. I'm pointing this out because the author's phrasing above does not reflect that very well - since in his example he might as well be only looking for a filename and/or commit message. Hence a lot of the <code>svn log</code> answers and comments.</p>
|
[
{
"answer_id": 44226,
"author": "Jack M.",
"author_id": 3421,
"author_profile": "https://Stackoverflow.com/users/3421",
"pm_score": 4,
"selected": false,
"text": "/ svn diff -r0:HEAD | less\n grep svn log 0"
},
{
"answer_id": 2019277,
"author": "Bas Grolleman",
"author_id": 245387,
"author_profile": "https://Stackoverflow.com/users/245387",
"pm_score": 4,
"selected": false,
"text": "#!/bin/bash\nfor REV in `svn log $1 | grep ^r[0-9] | awk '{print $1}'`; do \n svn cat $1 -r $REV | grep -q $2\n if [ $? -eq 0 ]; then \n echo \"$REV\"\n fi \ndone\n svnadmin dump"
},
{
"answer_id": 3110880,
"author": "pfyon",
"author_id": 136746,
"author_profile": "https://Stackoverflow.com/users/136746",
"pm_score": 3,
"selected": false,
"text": "svnadmin dump <repo location> |grep -i <search term>\n"
},
{
"answer_id": 3820708,
"author": "luis gutierrez",
"author_id": 461606,
"author_profile": "https://Stackoverflow.com/users/461606",
"pm_score": 7,
"selected": true,
"text": "git svn clone <svn url>\n git log -G<some regex>\n"
},
{
"answer_id": 8766101,
"author": "James McGuigan",
"author_id": 748503,
"author_profile": "https://Stackoverflow.com/users/748503",
"pm_score": 1,
"selected": false,
"text": "#!/bin/bash\n# Usage: svngrep $regex @grep_args\n\nregex=\"$@\"\npattern=`echo $regex | perl -p -e 's/--?\\S+//g; s/^\\\\s+//;'` # strip --args\nif [[ ! $regex ]]; then\n echo \"Usage: svngrep \\$regex @grep_args\"\nelse \n for file in `grep -irl --no-messages --exclude=\\*.tmp --exclude=\\.svn $regex ./`; do \n revs=\"`svnrevisions $file`\";\n for rev in $revs; do\n diff=`svn diff $file -r$[rev-1]:$rev \\\n --diff-cmd /usr/bin/diff -x \"-Ew -U5 --strip-trailing-cr\" 2> /dev/null`\n context=`echo \"$diff\" \\\n | grep -i --color=none -U5 \"^\\(+\\|-\\).*$pattern\" \\\n | grep -i --color=always -U5 $pattern \\\n | grep -v '^+++\\|^---\\|^===\\|^Index: ' \\\n `\n if [[ $context ]]; then\n info=`echo \"$diff\" | grep '^+++\\|^---'`\n log=`svn log $file -r$rev`\n #author=`svn info -r$rev | awk '/Last Changed Author:/ { print $4 }'`; \n\n echo \"========================================================================\"\n echo \"========================================================================\"\n echo \"$log\"\n echo \"$info\"\n echo \"$context\"\n echo\n fi;\n done;\n done;\nfi\n #!/bin/sh\n# Usage: svnrevisions $file\n# Output: list of fully numeric svn revisions (without the r), one per line\n\nfile=\"$@\"\n svn log \"$file\" 2> /dev/null | awk '/^r[[:digit:]]+ \\|/ { sub(/^r/,\"\",$1); print $1 }'\n"
},
{
"answer_id": 17473516,
"author": "bahrep",
"author_id": 761095,
"author_profile": "https://Stackoverflow.com/users/761095",
"pm_score": 5,
"selected": false,
"text": "svn log --search svn log --search svn log"
},
{
"answer_id": 33120139,
"author": "JREN",
"author_id": 2504013,
"author_profile": "https://Stackoverflow.com/users/2504013",
"pm_score": 3,
"selected": false,
"text": "svn log -v [repository] > somefile.log\n --diff svn log -v --diff [repository] > somefile.log\n"
},
{
"answer_id": 37855087,
"author": "zednight",
"author_id": 1893975,
"author_profile": "https://Stackoverflow.com/users/1893975",
"pm_score": 2,
"selected": false,
"text": "svn log -l<commit limit> | grep -C<5 or more lines> <search message>"
},
{
"answer_id": 38661105,
"author": "DustWolf",
"author_id": 2897386,
"author_profile": "https://Stackoverflow.com/users/2897386",
"pm_score": -1,
"selected": false,
"text": "svn blame\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3408/"
] |
44,177 |
<p>A friend of mine told me there was a way to connect two private IPs without using a proxy server. The idea was that both computers connected to a public server and some how the server joined the private connections and won't use any more bandwidth.</p>
<p>Is this true? How's this technique named?</p>
|
[
{
"answer_id": 44231,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 0,
"selected": false,
"text": "ssh -R localhost:13306:localhost:3306 username@serverA\n ssh -L 3306:localhost:13306 username@serverA\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4269/"
] |
44,181 |
<p>I have a database with two tables (<code>Table1</code> and <code>Table2</code>). They both have a common column <code>[ColumnA]</code> which is an <code>nvarchar</code>. </p>
<p>How can I select this column from both tables and return it as a single column in my result set?</p>
<p>So I'm looking for something like:</p>
<pre><code>ColumnA in Table1:
a
b
c
ColumnA in Table2:
d
e
f
Result set should be:
a
b
c
d
e
f
</code></pre>
|
[
{
"answer_id": 44183,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 5,
"selected": true,
"text": "SELECT ColumnA FROM Table1 UNION Select ColumnB FROM Table2 ORDER BY 1\n"
},
{
"answer_id": 44186,
"author": "Joseph Sturtevant",
"author_id": 317,
"author_profile": "https://Stackoverflow.com/users/317",
"pm_score": 1,
"selected": false,
"text": "SELECT ColumnA FROM Table1\nUNION\nSELECT ColumnA FROM Table2\n"
},
{
"answer_id": 44189,
"author": "Haydar",
"author_id": 288,
"author_profile": "https://Stackoverflow.com/users/288",
"pm_score": 0,
"selected": false,
"text": "Select columnA from table1 union select columnA from table2 \n"
},
{
"answer_id": 44191,
"author": "JesDaw",
"author_id": 4440,
"author_profile": "https://Stackoverflow.com/users/4440",
"pm_score": 0,
"selected": false,
"text": "SELECT Table1.*, Table2.d, Table2.e, Table2.f \nFROM Table1 JOIN Table2 ON Table1.a = Table2.a\n"
},
{
"answer_id": 44192,
"author": "Nathan Fritz",
"author_id": 4142,
"author_profile": "https://Stackoverflow.com/users/4142",
"pm_score": 0,
"selected": false,
"text": "SELECT columna FROM table1 UNION SELECT columnb FROM table2;\n"
},
{
"answer_id": 44201,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 1,
"selected": false,
"text": "SELECT distinct ColumnA FROM Table1\nUNION\nSELECT distinct ColumnA FROM Table2\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1980/"
] |
44,190 |
<p>I am looking for a simple JavaScript example that updates DOM.<br>
Any suggestions?</p>
|
[
{
"answer_id": 44216,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 4,
"selected": true,
"text": "var newnode = document.createTextNode('Here is some text.');\ndocument.getElementById('maincontent').appendChild(newnode);\n"
},
{
"answer_id": 44250,
"author": "Ravi Chhabra",
"author_id": 370899,
"author_profile": "https://Stackoverflow.com/users/370899",
"pm_score": 0,
"selected": false,
"text": "<html>\n <head>\n <title>Font Detect please</title>\n\n <script src=\"prototype.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\">\n $('Myanmar3').update('False'); \n $('Myanmar3').innerHTML; \n </script>\n </head>\n <body> \n\n <table border=\"1\">\n <tr><td>Font</td><td>Installed</td></tr>\n <tr><td>Myanmar3</td><td id=Myanmar3>True</td></tr>\n </table> \n\n </body>\n</html>\n"
},
{
"answer_id": 44273,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 1,
"selected": false,
"text": "<html>\n <head>\n <title>Font Detect please</title>\n\n <script src=\"prototype.js\" type=\"text/javascript\"></script>\n <script type=\"text/javascript\">\n function changeTD()\n {\n $('Myanmar3').innerHTML = 'False'; \n }\n </script>\n </head>\n <body> \n\n <table border=\"1\">\n <tr><td>Font</td><td>Installed</td></tr>\n <tr><td>Myanmar3</td><td id=\"Myanmar3\">True</td></tr>\n </table> \n\n <a href=\"javascript:void(0);\" onclick=\"changeTD();\">Click Me</a>\n\n </body>\n</html>\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/370899/"
] |
44,194 |
<p>This is what I've got. It works. But, is there a simpler or better way?</p>
<p>One an ASPX page, I've got the download link...</p>
<pre><code><asp:HyperLink ID="HyperLinkDownload" runat="server" NavigateUrl="~/Download.aspx">Download as CSV file</asp:HyperLink>
</code></pre>
<p>And then I've got the Download.aspx.vb Code Behind...</p>
<pre><code>Public Partial Class Download
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'set header
Response.Clear()
Response.ContentType = "text/csv"
Dim FileName As String = "books.csv"
Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName)
'generate file content
Dim db As New bookDevelopmentDataContext
Dim Allbooks = From b In db.books _
Order By b.Added _
Select b
Dim CsvFile As New StringBuilder
CsvFile.AppendLine(CsvHeader())
For Each b As Book In Allbooks
CsvFile.AppendLine(bookString(b))
Next
'write the file
Response.Write(CsvFile.ToString)
Response.End()
End Sub
Function CsvHeader() As String
Dim CsvLine As New StringBuilder
CsvLine.Append("Published,")
CsvLine.Append("Title,")
CsvLine.Append("Author,")
CsvLine.Append("Price")
Return CsvLine.ToString
End Function
Function bookString(ByVal b As Book) As String
Dim CsvLine As New StringBuilder
CsvLine.Append(b.Published.ToShortDateString + ",")
CsvLine.Append(b.Title.Replace(",", "") + ",")
CsvLine.Append(b.Author.Replace(",", "") + ",")
CsvLine.Append(Format(b.Price, "c").Replace(",", ""))
Return CsvLine.ToString
End Function
End Class
</code></pre>
|
[
{
"answer_id": 44219,
"author": "Simon Gillbee",
"author_id": 756,
"author_profile": "https://Stackoverflow.com/users/756",
"pm_score": 6,
"selected": true,
"text": "CsvLine.Append(Format(b.Price, \"c\").Replace(\",\", \"\"))\n CsvLine.Append(String.Format(\"\\\"{0:c}\\\"\", b.Price))\n \" \"\" b.Title.Replace(\"\\\"\", \"\\\"\\\"\")\n"
},
{
"answer_id": 44237,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "Function PrepForCSV(ByVal value As String) As String\n return String.Format(\"\"\"{0}\"\"\", Value.Replace(\"\"\"\", \"\"\"\"\"\"))\nEnd Function\n"
},
{
"answer_id": 98123,
"author": "Ricky Supit",
"author_id": 4191,
"author_profile": "https://Stackoverflow.com/users/4191",
"pm_score": 2,
"selected": false,
"text": "protected void Page_Load(object sender, EventArgs e)\n{\n using (var db = new bookDevelopmentDataContext())\n {\n string fileName = \"book.csv\";\n var q = from b in db.books\n select string.Format(\"{0:d},\\\"{1}\\\",\\\"{2}\\\",{3:F2}\", b.Published, b.Title.Replace(\"\\\"\", \"\\\"\\\"\"), b.Author.Replace(\"\\\"\", \"\\\"\\\"\"), t.price);\n\n string outstring = string.Join(\",\", q.ToArray());\n\n Response.Clear();\n Response.ClearHeaders();\n Response.ContentType = \"text/csv\";\n Response.AppendHeader(\"Content-Disposition\", string.Format(\"attachment;filename={0}\", fileName));\n Response.Write(\"Published,Title,Author,Price,\" + outstring);\n Response.End();\n }\n}\n"
},
{
"answer_id": 4046459,
"author": "Paul Mendoza",
"author_id": 29277,
"author_profile": "https://Stackoverflow.com/users/29277",
"pm_score": 1,
"selected": false,
"text": "public override void ExecuteResult(ControllerContext context)\n {\n StringBuilder csv = new StringBuilder(10 * Table.Rows.Count * Table.Columns.Count);\n\n for (int c = 0; c < Table.Columns.Count; c++)\n {\n if (c > 0)\n csv.Append(\",\");\n DataColumn dc = Table.Columns[c];\n string columnTitleCleaned = CleanCSVString(dc.ColumnName);\n csv.Append(columnTitleCleaned);\n }\n csv.Append(Environment.NewLine);\n foreach (DataRow dr in Table.Rows)\n {\n StringBuilder csvRow = new StringBuilder();\n for(int c = 0; c < Table.Columns.Count; c++)\n {\n if(c != 0)\n csvRow.Append(\",\");\n\n object columnValue = dr[c];\n if (columnValue == null)\n csvRow.Append(\"\");\n else\n {\n string columnStringValue = columnValue.ToString();\n\n\n string cleanedColumnValue = CleanCSVString(columnStringValue);\n\n if (columnValue.GetType() == typeof(string) && !columnStringValue.Contains(\",\"))\n {\n cleanedColumnValue = \"=\" + cleanedColumnValue; // Prevents a number stored in a string from being shown as 8888E+24 in Excel. Example use is the AccountNum field in CI that looks like a number but is really a string.\n }\n csvRow.Append(cleanedColumnValue);\n }\n }\n csv.AppendLine(csvRow.ToString());\n }\n\n HttpResponseBase response = context.HttpContext.Response;\n response.ContentType = \"text/csv\";\n response.AppendHeader(\"Content-Disposition\", \"attachment;filename=\" + this.FileName);\n response.Write(csv.ToString());\n }\n\n protected string CleanCSVString(string input)\n {\n string output = \"\\\"\" + input.Replace(\"\\\"\", \"\\\"\\\"\").Replace(\"\\r\\n\", \" \").Replace(\"\\r\", \" \").Replace(\"\\n\", \"\") + \"\\\"\";\n return output;\n }\n"
},
{
"answer_id": 18404453,
"author": "blalond",
"author_id": 536625,
"author_profile": "https://Stackoverflow.com/users/536625",
"pm_score": 1,
"selected": false,
"text": "Private Function formatForCSV(stringToProcess As String) As String\n If stringToProcess.Contains(\"\"\"\") Or stringToProcess.Contains(\",\") Then\n stringToProcess = String.Format(\"\"\"{0}\"\"\", stringToProcess.Replace(\"\"\"\", \"\"\"\"\"\"))\n End If\n Return stringToProcess\nEnd Function\n\n'So, lines like this:\nCsvLine.Append(b.Title.Replace(\",\", \"\") + \",\")\n'would be lines like this instead:\nCsvLine.Append(formatForCSV(b.Title)) + \",\")\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
44,207 |
<p>XML, granted, is very useful, but can be quite verbose. What alternatives are there and are they specialised for any particular purpose? Library support to interrogate the contents easily is a big plus point.</p>
|
[
{
"answer_id": 20363397,
"author": "Qwertie",
"author_id": 22820,
"author_profile": "https://Stackoverflow.com/users/22820",
"pm_score": 0,
"selected": false,
"text": "// LES code has no built-in meaning. This just shows what it looks like.\n[DelayedWrite] // an \"attribute\"\nOutput(\n if version > 4.0 {\n $ProjectDir/Src/Foo;\n } else {\n $ProjectDir/Foo;\n }\n);\n body {\n '''Click here to use the World's '''\n a href=\"http://google.com\" {\n strong \"most popular\"; \" search engine!\"\n };\n};\n\npoint = (2, -3);\ntasteMap = { \"lemon\" -> sour; \"sugar\" -> sweet; \"grape\" -> yummy };\n"
},
{
"answer_id": 22239825,
"author": "B Robster",
"author_id": 652693,
"author_profile": "https://Stackoverflow.com/users/652693",
"pm_score": 2,
"selected": false,
"text": "# This is a TOML document. Boom.\n\ntitle = \"TOML Example\"\n\n[owner]\nname = \"Tom Preston-Werner\"\norganization = \"GitHub\"\nbio = \"GitHub Cofounder & CEO\\nLikes tater tots and beer.\"\ndob = 1979-05-27T07:32:00Z # First class dates? Why not?\n\n[database]\nserver = \"192.168.1.1\"\nports = [ 8001, 8001, 8002 ]\nconnection_max = 5000\nenabled = true\n\n[servers]\n\n # You can indent as you please. Tabs or spaces. TOML don't care.\n [servers.alpha]\n ip = \"10.0.0.1\"\n dc = \"eqdc10\"\n\n [servers.beta]\n ip = \"10.0.0.2\"\n dc = \"eqdc10\"\n\n[clients]\ndata = [ [\"gamma\", \"delta\"], [1, 2] ]\n\n# Line breaks are OK when inside arrays\nhosts = [\n \"alpha\",\n \"omega\"\n]\n"
},
{
"answer_id": 27487206,
"author": "igagis",
"author_id": 1221106,
"author_profile": "https://Stackoverflow.com/users/1221106",
"pm_score": 0,
"selected": false,
"text": "\"String object\"\nAnotherStringObject\n\"String with children\"{\n \"child 1\"\n Child2\n \"child three\"{\n SubChild1\n \"Subchild two\"\n\n Property1 {Value1}\n \"Property two\" {\"Value 2\"}\n //comment\n\n /* multi-line\n comment */\n\n \"multi-line\n string\"\n\n \"Escape sequences \\\" \\n \\r \\t \\\\\"\n }\n}\n"
},
{
"answer_id": 29946862,
"author": "intellimath",
"author_id": 4743644,
"author_profile": "https://Stackoverflow.com/users/4743644",
"pm_score": 2,
"selected": false,
"text": "<person>\n <name>Alex</name>\n <age>34</age>\n <email>[email protected]</email>\n</person>\n person {\n name {\"Alex\"}\n age {34}\n email {\"[email protected]\"}}\n <memo date=\"2008-02-14\">\n<from>\n<name>The Whole World</name><email>[email protected]</email>\n</from>\n<to>\n<name>Dawg</name><email>[email protected]</email>\n</to>\n<message>\nDear sir, you won the internet. http://is.gd/fh0\n</message>\n</memo>\n memo {\n date:2008-02-14\n from {\n name{\"The Whole World\"} email{\"[email protected]\"}}\n to {\n name{\"Dawg\"} email{\"[email protected]\"}}\n message {\"Dear sir, you won the internet. http://is.gd/fh0\"}\n}\n <club>\n <players>\n <player id=\"kramnik\"\n name=\"Vladimir Kramnik\"\n rating=\"2700\"\n status=\"GM\" />\n <player id=\"fritz\"\n name=\"Deep Fritz\"\n rating=\"2700\"\n status=\"Computer\" />\n <player id=\"mertz\"\n name=\"David Mertz\"\n rating=\"1400\"\n status=\"Amateur\" />\n </players>\n <matches>\n <match>\n <Date>2002-10-04</Date>\n <White refid=\"fritz\" />\n <Black refid=\"kramnik\" />\n <Result>Draw</Result>\n </match>\n <match>\n <Date>2002-10-06</Date>\n <White refid=\"kramnik\" />\n <Black refid=\"fritz\" />\n <Result>White</Result>\n </match>\n </matches>\n</club>\n club {\n players {\n player {\n id:\"kramnik\"\n name:\"Vladimir Kramnik\"\n rating:2700\n status:\"GM\"}\n player {\n id:\"fritz\"\n name:\"Deep Fritz\"\n rating:2700\n status:\"Computer\"}\n player {\n id:\"mertz\"\n name:\"David Mertz\"\n rating:1400 \n status:\"Amateur\"}}\n matches {\n match {\n Date{2002-10-04}\n White{refid:\"fritz\"}\n Black{refid:\"kramnik\"}\n Result{\"Draw\"}}\n match {\n Date{2002-10-06}\n White{refid:\"kramnik\"}\n Black{refid:\"fritz\"}\n Result{\"White\"}}}}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44207",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3233/"
] |
44,220 |
<p>I have been told that there is a performance difference between the following code blocks.</p>
<pre><code>foreach (Entity e in entityList)
{
....
}
</code></pre>
<p>and </p>
<pre><code>for (int i=0; i<entityList.Count; i++)
{
Entity e = (Entity)entityList[i];
...
}
</code></pre>
<p>where</p>
<pre><code>List<Entity> entityList;
</code></pre>
<p>I am no CLR expect but from what I can tell they should boil down to basically the same code. Does anybody have concrete (heck, I'd take packed dirt) evidence one way or the other?</p>
|
[
{
"answer_id": 44248,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 0,
"selected": false,
"text": "const int ArraySize = 10;\nint[] values = new int[ArraySize];\n\n//...\n\nfor (int i = 0; i \n\nIn this case, depending on the complexity of the loop body, the compiler might be able to replace the loop with inline calls. I have no idea if the .NET compiler does this, and it's of limited utility if the size of the enumerable type is dynamic.\n\nOne situation where foreach might perform better is with data structures like a linked list where random access means traversing the list; the enumerator used by foreach will probably iterate one item at a time, making each access O(1) and the full loop O(n), but calling the indexer means starting at the head and finding the item at the right index; O(N) each loop for O(n^2).\n\n foreach foreach Personally I don't usually worry about it and use foreach any time I need all items and don't care about the index of the item. If I'm not working with all of the items or I really need to know the index, I use for foreach"
},
{
"answer_id": 44252,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "using(IEnumerator<Entity> e = entityList.GetEnumerator()) {\n while(e.MoveNext()) {\n Entity entity = e.Current;\n ...\n }\n}\n"
},
{
"answer_id": 21084968,
"author": "kavitha Reddy",
"author_id": 3073215,
"author_profile": "https://Stackoverflow.com/users/3073215",
"pm_score": 0,
"selected": false,
"text": "For Loop\nfor loop is used to perform the opreration n times\nfor(int i=0;i<n;i++)\n{\nl=i;\n}\nforeach loop\n\nint[] i={1,2,3,4,5,6}\nforeach loop is used to perform each operation value/object in IEnumarable \nforeach(var k in i)\n{\nl=k;\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2894/"
] |
44,241 |
<p>Is there a way to track which window currently has keyboard focus. I could handle WM_SETFOCUS for every window but I'm wondering if there's an alternative, simpler method (i.e. a single message handler somewhere).</p>
<p>I could use OnIdle() in MFC and call GetFocus() but that seems a little hacky.</p>
|
[
{
"answer_id": 44371,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 0,
"selected": false,
"text": "<snip>\n\nfunction TForm1.GetCurrentHandle: integer;\nvar\n activeWinHandle: HWND;\n focusedThreadID : DWORD;\nbegin\n //return the Windows handle of the currently focused control\n Result := 0;\n activeWinHandle := GetForegroundWindow;\n focusedThreadID := GetWindowThreadProcessID(activeWinHandle,nil);\n if AttachThreadInput(GetCurrentThreadID,focusedThreadID,true) then begin\n try\n Result := GetFocus;\n finally\n AttachThreadInput(GetCurrentThreadID, focusedThreadID, false);\n end;\n end; //if attached\nend;\n\nprocedure TForm1.Timer1Timer(Sender: TObject);\nbegin\n //give notification if the handle changed\n //(this code gets fired by a timer)\n CurrentHandle := GetCurrentHandle;\n if CurrentHandle <> PreviousHandle then begin\n Label1.Caption := 'Last focus change occurred @ ' + DateTimeToStr(Now);\n end;\n PreviousHandle := CurrentHandle;\nend;\n\n<snip>\n"
},
{
"answer_id": 93406,
"author": "olorin",
"author_id": 1098074,
"author_profile": "https://Stackoverflow.com/users/1098074",
"pm_score": 3,
"selected": false,
"text": "public void SubscribeToFocusChange()\n{\n AutomationFocusChangedEventHandler focusHandler \n = new AutomationFocusChangedEventHandler(OnFocusChanged);\n Automation.AddAutomationFocusChangedEventHandler(focusHandler);\n}\n\nprivate void OnFocusChanged(object sender, AutomationFocusChangedEventArgs e)\n{\n AutomationElement focusedElement = sender as AutomationElement;\n //...\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2768/"
] |
44,260 |
<p>We've got an interesting case where we are trying to determine how different instances of our app were launched. Is there any way for .NET to be able to query another running instance and get the command line parameters passed to that instance? I've not been able to find any way to do it in .NET so far, so I thought I'd check here to see if anyone had done anything like this before.</p>
|
[
{
"answer_id": 127201,
"author": "Noah",
"author_id": 4539,
"author_profile": "https://Stackoverflow.com/users/4539",
"pm_score": 0,
"selected": false,
"text": "try\n{\n ManagementScope connectScope = new ManagementScope();\n connectScope.Path = new ManagementPath(@\"\\\\\" + Environment.MachineName + @\"\\root\\CIMV2\");\n\n SelectQuery msQuery = new SelectQuery(\"SELECT * FROM Win32_Process Where Name = '\" + \"PROGRAMNAMEHERE.exe\" + \"'\");\n ManagementObjectSearcher searchProcedure = new ManagementObjectSearcher(connectScope, msQuery);\n\n foreach (ManagementObject item in searchProcedure.Get())\n {\n try \n {\n MessageBox.Show(item[\"CommandLine\"].ToString()); \n }\n catch (SystemException) \n {}\n }\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4539/"
] |
44,261 |
<p>When I open cmd on my laptop it is defaulting to the F: drive. This is troubling me does anyone know how it got that way or how to get it back to where it opens to the C: drive by default?</p>
|
[
{
"answer_id": 44268,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 3,
"selected": true,
"text": "%HOMEDRIVE%\\%HOMEPATH%"
},
{
"answer_id": 88631,
"author": "tsellon",
"author_id": 3575,
"author_profile": "https://Stackoverflow.com/users/3575",
"pm_score": 0,
"selected": false,
"text": "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Command Processor\\AutoRun\n and/or\nHKEY_CURRENT_USER\\Software\\Microsoft\\Command Processor\\AutoRun\n"
},
{
"answer_id": 28885390,
"author": "gdupuis",
"author_id": 2868313,
"author_profile": "https://Stackoverflow.com/users/2868313",
"pm_score": 1,
"selected": false,
"text": "HKEY_CURRENT_USER\\Software\\Microsoft\\Command Processor\\AutoRun\n"
},
{
"answer_id": 34237465,
"author": "Breath Iguana",
"author_id": 5671520,
"author_profile": "https://Stackoverflow.com/users/5671520",
"pm_score": 3,
"selected": false,
"text": "C:\n"
},
{
"answer_id": 60408546,
"author": "jeb",
"author_id": 463115,
"author_profile": "https://Stackoverflow.com/users/463115",
"pm_score": 0,
"selected": false,
"text": "cd /d E:\\myPath\nFOR /F \"delims=\" %%Q in ('dir') do echo - %%Q\n AutoRun=C: C: FOR/F @echo off\nREM *** To enable this script, call it by <scriptName> --install\n\nsetlocal EnableDelayedExpansion\nREM *** ALWAYS make a copy of the complete CMDCMDLINE, else you destroy the original!!!\nset \"_ccl_=!cmdcmdline!\"\n\nREM *** The check is necessary to distinguish between a new cmd.exe instance for a user or for a \"FOR /F\" sub-command\nif \"!_ccl_:~1,-2!\" == \"!comspec!\" (\n REM ***** INTERACTIVE ****\n\n REM *** %1 contains only data, when the script itself was called from the command line\n if \"%~1\" NEQ \"\" (\n goto :direct_call\n )\n\n endlocal\n doskey /macrofile=\"%~dp0\\cmdMacros.mac\"\n echo ********************************************************************\n echo * AutoRun executed from \"%~f0\"\n echo * Macros loaded from \"%~dp0\\cmdMacros.mac\"\n echo ********************************************************************\n cd /d C:\\myPath\n) ELSE (\n REM *** Called by a FOR command, by an explorer click or a drag & drop operation\n REM *** Handle PROBLEMATIC Drag&Drop content, if necessary\n endlocal\n)\nexit /b\n\n\n:direct_call\nif \"%~1\" == \"--install\" (\n reg add \"HKEY_CURRENT_USER\\Software\\Microsoft\\Command Processor\" /v \"AutoRun\" /t REG_SZ /d \"%~f0\"\n exit /b\n) \n\nif \"%~1\" == \"--show\" ( \n reg query \"HKEY_CURRENT_USER\\Software\\Microsoft\\Command Processor\" /v AutoRun\n exit /b\n)\n\nif \"%~1\" == \"--remove\" (\n reg DELETE \"HKEY_CURRENT_USER\\Software\\Microsoft\\Command Processor\" /v AutoRun /f\n)\nexit /b\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] |
44,270 |
<p>What is the best algorithm to take array like below:</p>
<p><code>A {0,1,2,3}</code></p>
<p>I expected to order it like array below:</p>
<p><code>B {3,1,0,2}</code> </p>
<p>Any ideas?</p>
|
[
{
"answer_id": 44296,
"author": "EBGreen",
"author_id": 1358,
"author_profile": "https://Stackoverflow.com/users/1358",
"pm_score": 1,
"selected": false,
"text": "Make an ArrayList\nCopy the contents of the smaller array to the arraylist\nfor each item I in the larger array\n FInd I in the ArrayList\n Append I to a new array\n Remove I from the arraylist\n"
},
{
"answer_id": 44297,
"author": "Eric",
"author_id": 4540,
"author_profile": "https://Stackoverflow.com/users/4540",
"pm_score": 2,
"selected": false,
"text": "List<int> B2 = new List<int>(B);\n List<KeyValuePair<int,int>> swaps = new List<KeyValuePair<int,int>>();\nB2.Sort( delegate( int x, int y ) {\n if( x<y ) return -1;\n if( x==y ) return 0;\n // x and y must be transposed, so assume they will be:\n swaps.Add( new KeyValuePair<int,int>(x,y) );\n return 1;\n});\n swaps.Reverse();\nforeach( KeyValuePair<int,int> x in swaps )\n{\n int t = A[x.key];\n A[x.key] = A[x.value];\n A[x.value] = t;\n}\n"
},
{
"answer_id": 4269553,
"author": "Yuri Astrakhan",
"author_id": 177275,
"author_profile": "https://Stackoverflow.com/users/177275",
"pm_score": 2,
"selected": false,
"text": "var data = new[] { 1, 2, 3, 4, 5 };\nvar customOrder = new[] { 2, 1 };\nArray.Sort(data, new CustomOrderComparer<int>(customOrder));\nforeach (var v in data)\n Console.Write(\"{0},\", v);\n 2,1,3,4,5, public class CustomOrderComparer<TValue> : IComparer<TValue>\n{\n private readonly IComparer<TValue> _fallbackComparer;\n private const int UseDictionaryWhenBigger = 64; // todo - adjust\n\n private readonly IList<TValue> _customOrder;\n private readonly Dictionary<TValue, uint> _customOrderDict;\n\n public CustomOrderComparer(IList<TValue> customOrder, IComparer<TValue> fallbackComparer = null)\n {\n if (customOrder == null) throw new ArgumentNullException(\"customOrder\");\n\n _fallbackComparer = fallbackComparer ?? Comparer<TValue>.Default;\n\n if (UseDictionaryWhenBigger < customOrder.Count)\n {\n _customOrderDict = new Dictionary<TValue, uint>(customOrder.Count);\n for (int i = 0; i < customOrder.Count; i++)\n _customOrderDict.Add(customOrder[i], (uint) i);\n }\n else\n _customOrder = customOrder;\n }\n\n #region IComparer<TValue> Members\n\n public int Compare(TValue x, TValue y)\n {\n uint indX, indY;\n if (_customOrderDict != null)\n {\n if (!_customOrderDict.TryGetValue(x, out indX)) indX = uint.MaxValue;\n if (!_customOrderDict.TryGetValue(y, out indY)) indY = uint.MaxValue;\n }\n else\n {\n // (uint)-1 == uint.MaxValue\n indX = (uint) _customOrder.IndexOf(x);\n indY = (uint) _customOrder.IndexOf(y);\n }\n\n if (indX == uint.MaxValue && indY == uint.MaxValue)\n return _fallbackComparer.Compare(x, y);\n\n return indX.CompareTo(indY);\n }\n\n #endregion\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44270",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] |
44,272 |
<p>This is a php example, but an algorithm for any language would do. What I specifically want to do is bubble up the United States and Canada to the top of the list. Here is an example of the array shortened for brevity. </p>
<pre><code>array(
0 => '-- SELECT --',
1 => 'Afghanistan',
2 => 'Albania',
3 => 'Algeria',
4 => 'American Samoa',
5 => 'Andorra',)
</code></pre>
<p>The id's need to stay intact. So making them -1 or -2 will unfortunately not work.</p>
|
[
{
"answer_id": 44889,
"author": "Michał Niedźwiedzki",
"author_id": 2169,
"author_profile": "https://Stackoverflow.com/users/2169",
"pm_score": 1,
"selected": false,
"text": "$a = array(\n 0 => '- select -',\n 1 => 'Afghanistan',\n 2 => 'Albania',\n 3 => 'Algeria',\n 80 => 'USA'\n);\n\n$temp = array();\nforeach ($a as $k => $v) {\n $v == 'USA'\n ? array_unshift($temp, array($k, $v))\n : array_push($temp, array($k, $v));\n}\nforeach ($temp as $t) {\n list ($k, $v) = $t;\n echo \"$k => $v\\n\";\n}\n 80 => USA\n0 => - select -\n1 => Afghanistan\n2 => Albania\n3 => Algeria\n"
},
{
"answer_id": 8112194,
"author": "hakre",
"author_id": 367456,
"author_profile": "https://Stackoverflow.com/users/367456",
"pm_score": 0,
"selected": false,
"text": "$countries = array(\n 0 => '-- SELECT --',\n 1 => 'Afghanistan',\n 2 => 'Albania',\n 3 => 'Algeria',\n 4 => 'American Samoa',\n 5 => 'Andorra',\n 22 => 'Canada',\n 44 => 'United States',);\n\n# tell what should be upfront (by id)\n$favourites = array(0, 44, 22);\n\n# add favourites at first\n$ordered = array();\nforeach($favourites as $id)\n{\n $ordered[$id] = $countries[$id];\n}\n\n# add everything else\n$ordered += array_diff_assoc($countries, $ordered);\n\n# result\nprint_r($ordered);\n"
},
{
"answer_id": 56250784,
"author": "Rahul",
"author_id": 6556397,
"author_profile": "https://Stackoverflow.com/users/6556397",
"pm_score": 0,
"selected": false,
"text": "array_unshift($queue, \"United States\", \"Canada\");\nprint_r($queue);\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1797/"
] |
44,286 |
<p>Are there any good programs for dealing with reading large CSV files? Some of the datafiles I deal with are in the 1 GB range. They have too many lines for Excel to even deal with. Using Access can be a little slow, as you have to actually import them into a database to work with them directly. Is there a program that can open large CSV files and give you a simple spreadsheet layout to help you easily and quickly scan through the data?</p>
|
[
{
"answer_id": 44955,
"author": "David Locke",
"author_id": 1447,
"author_profile": "https://Stackoverflow.com/users/1447",
"pm_score": 0,
"selected": false,
"text": "from augustus.kernel.unitable import *\na = UniTable().from_csv_file('filename')\nb = a.subtbl(a['key'] == some_value) #creates a subtable\n"
},
{
"answer_id": 45018,
"author": "Jordi Bunster",
"author_id": 4272,
"author_profile": "https://Stackoverflow.com/users/4272",
"pm_score": 4,
"selected": true,
"text": "LOAD DATA INFILE LOAD DATA INFILE INSERT/UPDATE"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1862/"
] |
44,288 |
<p>Comparing string in C# is pretty simple. In fact there are several ways to do it. I have listed some in the block below. What I am curious about are the differences between them and when one should be used over the others? Should one be avoided at all costs? Are there more I haven't listed? </p>
<pre><code>string testString = "Test";
string anotherString = "Another";
if (testString.CompareTo(anotherString) == 0) {}
if (testString.Equals(anotherString)) {}
if (testString == anotherString) {}
</code></pre>
<p>(Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well)</p>
|
[
{
"answer_id": 44301,
"author": "Ed S.",
"author_id": 1053,
"author_profile": "https://Stackoverflow.com/users/1053",
"pm_score": 6,
"selected": false,
"text": ".Equals .CompareTo .Equals == string .Equals Object.ReferenceEquals == =="
},
{
"answer_id": 44303,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 3,
"selected": false,
"text": "CompareTo CompareInfo Equals == Compare == Equals String.Compare StringComparison String.Compare CultureInfo String.Compare"
},
{
"answer_id": 44373,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 9,
"selected": true,
"text": "stringValue.CompareTo(otherStringValue) null CultureInfo.CurrentCulture.CompareInfo.Compare ß SS stringValue.Equals(otherStringValue) null StringComparison ß SS stringValue == otherStringValue stringValue.Equals() == Equals(string a, string b) EqualsHelper .Equals() null null == Object.ReferenceEquals(stringValue, otherStringValue) .CompareTo .Equals"
},
{
"answer_id": 513072,
"author": "max",
"author_id": 59407,
"author_profile": "https://Stackoverflow.com/users/59407",
"pm_score": 6,
"selected": false,
"text": "strA.Equals(strB)\n string.Compare(strA, strB, StringComparison.OrdinalIgnoreCase) == 0\n string.Compare(strA, strB, myCultureInfo) == 0\n CompareOptions compareOptions = CompareOptions.IgnoreCase\n | CompareOptions.IgnoreWidth\n | CompareOptions.IgnoreNonSpace;\nstring.Compare(strA, strB, CultureInfo.CurrentCulture, compareOptions) == 0\n"
},
{
"answer_id": 513103,
"author": "Jonathan C Dickinson",
"author_id": 24064,
"author_profile": "https://Stackoverflow.com/users/24064",
"pm_score": 4,
"selected": false,
"text": "if(object.ReferenceEquals(left, null) && \n object.ReferenceEquals(right, null))\n return true;\nif(object.ReferenceEquals(left, null))\n return right.Equals(left);\nreturn left.Equals(right);\n string a = null;\nstring b = \"foo\";\n\nbool equal = a.Equals(b);\n string a = null;\nstring b = \"foo\";\n\nbool equal = a == b;\n"
},
{
"answer_id": 2515930,
"author": "David",
"author_id": 301718,
"author_profile": "https://Stackoverflow.com/users/301718",
"pm_score": -1,
"selected": false,
"text": "string a = \"myString\";\nstring b = \"myString\";\n\nreturn a==b\n b = \"MYSTRING\";\n a.Equals(b, StringComparison.OrdinalIgnoreCase) \n"
},
{
"answer_id": 17361588,
"author": "Rauld",
"author_id": 634031,
"author_profile": "https://Stackoverflow.com/users/634031",
"pm_score": 2,
"selected": false,
"text": " string s = null;\n string a = \"a\";\n //Throws {\"Object reference not set to an instance of an object.\"}\n if (s.Equals(a))\n Console.WriteLine(\"s is equal to a\");\n //no Exception\n if(s==a)\n Console.WriteLine(\"s is equal to a\");\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2894/"
] |
44,298 |
<p>I have a databound TextBox in my application like so: (The type of <code>Height</code> is <code>decimal?</code>)</p>
<pre class="lang-xml prettyprint-override"><code> <TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged,
ValidatesOnExceptions=True,
Converter={StaticResource NullConverter}}" />
</code></pre>
<pre class="lang-cs prettyprint-override"><code> public class NullableConverter : IValueConverter {
public object Convert(object o, Type type, object parameter, CultureInfo culture) {
return o;
}
public object ConvertBack(object o, Type type, object parameter, CultureInfo culture) {
if (o as string == null || (o as string).Trim() == string.Empty)
return null;
return o;
}
}
</code></pre>
<p>Configured this way, any non-empty strings which cannot be converted to decimal result in a validation error which will immediately highlight the textbox. However, the TextBox can still lose focus and remain in an invalid state. What I would like to do is either:</p>
<ol>
<li>Not allow the TextBox to lose focus until it contains a valid value.</li>
<li>Revert the value in the TextBox to the last valid value.</li>
</ol>
<p>What is the best way to do this?</p>
<p><strong>Update:</strong></p>
<p>I've found a way to do #2. I don't love it, but it works:</p>
<pre><code>private void TextBox_LostKeyboardFocus(object sender, RoutedEventArgs e) {
var box = sender as TextBox;
var binding = box.GetBindingExpression(TextBox.TextProperty);
if (binding.HasError)
binding.UpdateTarget();
}
</code></pre>
<p>Does anyone know how to do this better? (Or do #1.)</p>
|
[
{
"answer_id": 47663,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 3,
"selected": true,
"text": "TextBox PreviewLostKeyBoardFocus <TextBox PreviewLostKeyboardFocus=\"TextBox_PreviewLostKeyboardFocus\" /> \n private void TextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {\n e.Handled = true;\n }\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317/"
] |
44,337 |
<p>As an exercise for myself, I was translating a sample program into various languages. Starting in C#, I had a visitor-pattern interface like so:</p>
<pre><code>interface Visitor
{
void Accept(Bedroom x);
void Accept(Bathroom x);
void Accept(Kitchen x);
void Accept(LivingRoom x);
}
</code></pre>
<p>Moving to ruby (or python, or whatever), I no longer get dispatch from the compiler based on type. Should I do the dispatch in the visitor itself?</p>
<pre><code>class Cleaner
def accept(x)
acceptBedroom(x) if Bedroom === x
acceptBathroom(x) if Bathroom === x
acceptKitchen(x) if Kitchen===x
acceptLivingRoom(x) if LivingRoom===x
end
...
</code></pre>
<p>Or should I do the dispatch in the different specializaions of the room:</p>
<pre><code>class Bathroom<Room
def initialize(name)
super(name)
end
def accept(visitor)
visitor.acceptBathroom(self)
end
end
</code></pre>
<p>Or is there another preferred idiom that is used in dynamic languages?</p>
|
[
{
"answer_id": 47663,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 3,
"selected": true,
"text": "TextBox PreviewLostKeyBoardFocus <TextBox PreviewLostKeyboardFocus=\"TextBox_PreviewLostKeyboardFocus\" /> \n private void TextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {\n e.Handled = true;\n }\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4540/"
] |
44,338 |
<p>I'm trying to be better about unit testing my code, but right now I'm writing a lot of code that deals with remote systems. SNMP, WMI, that sort of thing. With most classes I can mock up objects to test them, but how do you deal with unit testing a real system? For example, if my class goes out and gets the Win32_LogicalDisk object for a server, how could I possibly unit test it?</p>
|
[
{
"answer_id": 44525,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "class LogicalDiskConsumer(object):\n\n def __init__(self, arg1, arg2, LogicalDiskFactory)\n self.arg1=arg1\n self.arg2=arg2\n self.LogicalDisk=LogicalDiskFactory()\n\n def consumedisk(self):\n self.LogicalDisk.someaction()\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4550/"
] |
44,352 |
<p>In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?</p>
|
[
{
"answer_id": 44381,
"author": "Chris AtLee",
"author_id": 4558,
"author_profile": "https://Stackoverflow.com/users/4558",
"pm_score": 5,
"selected": true,
"text": "import inspect\n\ndef get_subclasses(mod, cls):\n \"\"\"Yield the classes in module ``mod`` that inherit from ``cls``\"\"\"\n for name, obj in inspect.getmembers(mod):\n if hasattr(obj, \"__bases__\") and cls in obj.__bases__:\n yield obj\n"
},
{
"answer_id": 44403,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 1,
"selected": false,
"text": "class foo(object): pass\nclass bar(foo): pass\nclass baz(foo): pass\n\nclass grar(Exception): pass\n\ndef find_subclasses(module, clazz):\n for name in dir(module):\n o = getattr(module, name)\n\n try: \n if issubclass(o, clazz):\n yield name, o\n except TypeError: pass\n\n>>> import foo\n>>> list(foo.find_subclasses(foo, foo.foo))\n[('bar', <class 'foo.bar'>), ('baz', <class 'foo.baz'>), ('foo', <class 'foo.foo'>)]\n>>> list(foo.find_subclasses(foo, object))\n[('bar', <class 'foo.bar'>), ('baz', <class 'foo.baz'>), ('foo', <class 'foo.foo'>), ('grar', <class 'foo.grar'>)]\n>>> list(foo.find_subclasses(foo, Exception))\n[('grar', <class 'foo.grar'>)]\n"
},
{
"answer_id": 47032,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 2,
"selected": false,
"text": "def find_subclasses(module, clazz):\n for name in dir(module):\n o = getattr(module, name)\n try:\n if (o != clazz) and issubclass(o, clazz):\n yield name, o\n except TypeError: pass\n"
},
{
"answer_id": 408465,
"author": "runeh",
"author_id": 2906,
"author_profile": "https://Stackoverflow.com/users/2906",
"pm_score": 4,
"selected": false,
"text": "inspect.getmembers() inspect.isclass() def find_subclasses(module, clazz):\n return [\n cls\n for name, cls in inspect.getmembers(module)\n if inspect.isclass(cls) and issubclass(cls, clazz)\n ]\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
44,359 |
<p>I have built a basic data entry application allowing users to browse external content in iframe and enter data quickly from the same page. One of the data variables is the URL.
Ideally I would like to be able to load the iframes current url into a textbox with javascript. I realize now that this is not going to happen due to security issues.</p>
<p>Has anyone done anything on the server side? or know of any .Net browser in browser controls. The ultimate goal is to just give the user an easy method of extracting the url of the page they are viewing in the iframe It doesn't necessarily HAVE to be an iframe, a browser in the browser would be ideal.</p>
<p>Thanks,
Adam</p>
|
[
{
"answer_id": 46361,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<iframe name='myframe' id='myframe' src='http://www.google.com'></iframe>\n document.getElementById('myframe').src\n"
},
{
"answer_id": 47190,
"author": "Jon",
"author_id": 4764,
"author_profile": "https://Stackoverflow.com/users/4764",
"pm_score": -1,
"selected": false,
"text": "<iframe name='frmExternal' id='frmExternal' src='http://www.stackoverflow.com'></frame>\n<input type='text' id='txtUrl' />\n<input type='button' id='btnGetUrl' value='Get URL' onclick='GetIFrameUrl();' />\n\n<script language='javascript' type='text/javascript'>\nfunction GetIFrameUrl()\n{\n if (!document.getElementById)\n {\n return;\n }\n\n var frm = document.getElementById(\"frmExternal\");\n var txt = document.getElementById(\"txtUrl\");\n\n if (frm == null || txt == null)\n {\n // not great user feedback but slightly better than obnoxious script errors\n alert(\"There was a problem with this page, please refresh.\");\n return;\n }\n\n txt.value = frm.src;\n}\n</script>\n"
},
{
"answer_id": 666832,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "document.getElementById('iframeID').contentWindow.location.href\n"
},
{
"answer_id": 836393,
"author": "igorsantos07",
"author_id": 102960,
"author_profile": "https://Stackoverflow.com/users/102960",
"pm_score": 1,
"selected": false,
"text": "iframes frameset <html>\n <head>\n <title>HTA Example</title>\n <HTA:APPLICATION id=\"frames\" border=\"thin\" caption=\"yes\" icon=\"http://www.google.com/favicon.ico\" showintaskbar=\"yes\" singleinstance=\"no\" sysmenu=\"yes\" navigable=\"yes\" contextmenu=\"no\" innerborder=\"no\" scroll=\"auto\" scrollflat=\"yes\" selection=\"yes\" windowstate=\"normal\"></HTA:APPLICATION>\n </head>\n <frameset rows=\"60px, *\">\n <frame src=\"topo.htm\" name=\"topo\" id=\"topo\" application=\"yes\" />\n <frame src=\"http://www.google.com\" name=\"conteudo\" id=\"conteudo\" application=\"yes\" />\n </frameset>\n</html>\n HTA:APPLICATION application=\"yes\" <html>\n <head>\n <title>Topo</title>\n <script type=\"text/javascript\">\n function copia_url() {\n campo.value = parent.conteudo.location;\n }\n </script>\n </head>\n <body style=\"background: lightBlue;\" onload=\"copia_url()\">\n <input type=\"button\" value=\"Copiar URL\" onclick=\"copia_url()\" />\n <input type=\"text\" size=\"120\" id=\"campo\" />\n </body>\n</html>\n"
},
{
"answer_id": 1245166,
"author": "Joaquin Cuenca Abela",
"author_id": 141253,
"author_profile": "https://Stackoverflow.com/users/141253",
"pm_score": 6,
"selected": false,
"text": ".src .documentWindow.location.href iframe documentWindow contentDocument .documentWindow.location.href .contentDocument.location.href src document.getElementById(\"myiframe\").src = 'http://www.google.com/';\n alert(document.getElementById(\"myiframe\").src);\n documentWindow.location.href documentWindow.location.href documentWindow document.getElementById(\"myiframe\").src = 'http://www.google.com/';\nalert(document.getElementById(\"myiframe\").documentWindow.location.href);\nError: Permission denied to get property Location.href\n"
},
{
"answer_id": 17766493,
"author": "H4NIO",
"author_id": 1633403,
"author_profile": "https://Stackoverflow.com/users/1633403",
"pm_score": 2,
"selected": false,
"text": "var iframe = parent.document.getElementById(\"theiframe\");\nvar innerDoc = iframe.contentDocument || iframe.contentWindow.document;\n\nvar currentFrame = innerDoc.location.href;\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4568/"
] |
44,364 |
<p>So, I was reading the Google testing blog, and it says that global state is bad and makes it hard to write tests. I believe it--my code is difficult to test right now. So how do I avoid global state?</p>
<p>The biggest things I use global state (as I understand it) for is managing key pieces of information between our development, acceptance, and production environments. For example, I have a static class named "Globals" with a static member called "DBConnectionString." When the application loads, it determines which connection string to load, and populates Globals.DBConnectionString. I load file paths, server names, and other information in the Globals class.</p>
<p>Some of my functions rely on the global variables. So, when I test my functions, I have to remember to set certain globals first or else the tests will fail. I'd like to avoid this.</p>
<p>Is there a good way to manage state information? (Or am I understanding global state incorrectly?)</p>
|
[
{
"answer_id": 44558,
"author": "JC.",
"author_id": 3615,
"author_profile": "https://Stackoverflow.com/users/3615",
"pm_score": 2,
"selected": false,
"text": "public interface ISettingsProvider\n{\n string ConnectionString { get; }\n}\n\npublic class TestSettings : ISettingsProvider\n{ \n public string ConnectionString { get { return \"testdatabase\"; } };\n}\n\npublic class DataStuff\n{\n private ISettingsProvider settings;\n\n public DataStuff(ISettingsProvider settings)\n {\n this.settings = settings;\n }\n\n public void DoSomething()\n {\n // use settings.ConnectionString\n }\n}\n"
},
{
"answer_id": 21470841,
"author": "Abul Fayes",
"author_id": 2678413,
"author_profile": "https://Stackoverflow.com/users/2678413",
"pm_score": 0,
"selected": false,
"text": "$container = new Container();\ninclude_file('container.php');\n container.add(\"database.driver\", \"mysql\");\ncontainer.add(\"database.name\",\"app\");\n $container.add(new Database($container->get('database.driver', \"database.name\")), 'database');\n$container.add(new Dao($container->get('database')), 'dao');\n$container.add(new Service($container->get('dao')));\n$container.add(new Controller($container->get('service')), 'controller');\n\n$container.add(new FrontController(),'frontController');\n $frontController = $container->get('frontController');\n$controllerClass = $frontController->getController($_SERVER['request_uri']);\n$controllerAction = $frontController->getAction($_SERVER['request_uri']);\n$controller = $container->get('controller');\n$controller->$action();\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44364",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/681/"
] |
44,376 |
<p>How do you shade alternating rows in a SQL Server Reporting Services report?</p>
<hr>
<p><strong>Edit:</strong> There are a bunch of good answers listed below--from <a href="https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#44378">quick</a> and <a href="https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#345935">simple</a> to <a href="https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#83832">complex and comprehensive</a>. Alas, I can choose only one...</p>
|
[
{
"answer_id": 44378,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 9,
"selected": true,
"text": "= IIf(RowNumber(Nothing) Mod 2 = 0, \"Silver\", \"Transparent\")\n = If(RowNumber(Nothing) Mod 2 = 0, \"Silver\", \"Transparent\")\n"
},
{
"answer_id": 83832,
"author": "Catch22",
"author_id": 15428,
"author_profile": "https://Stackoverflow.com/users/15428",
"pm_score": 7,
"selected": false,
"text": "IIF(RowNumber...) Private bOddRow As Boolean\n'*************************************************************************\n' -- Display green-bar type color banding in detail rows\n' -- Call from BackGroundColor property of all detail row textboxes\n' -- Set Toggle True for first item, False for others.\n'*************************************************************************\nFunction AlternateColor(ByVal OddColor As String, _\n ByVal EvenColor As String, ByVal Toggle As Boolean) As String\n If Toggle Then bOddRow = Not bOddRow\n If bOddRow Then\n Return OddColor\n Else\n Return EvenColor\n End If\nEnd Function\n =Code.AlternateColor(\"AliceBlue\", \"White\", True)\n"
},
{
"answer_id": 345935,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "=iif(RunningValue(*group on field*,CountDistinct,\"*parent group name*\") Mod 2,\"White\",\"AliceBlue\")\n =IIF(RunningValue(Fields![Name].Value, CountDistinct, \"NameOfPartnetGroup\") Mod 2, \"White\", \"Wheat\")\n"
},
{
"answer_id": 1224661,
"author": "Beska",
"author_id": 57120,
"author_profile": "https://Stackoverflow.com/users/57120",
"pm_score": 4,
"selected": false,
"text": "Private bOddRow As Boolean\n'*************************************************************************\n' -- Display green-bar type color banding in detail rows\n' -- Call from BackGroundColor property of all detail row textboxes\n' -- Set Toggle True for first item, False for others.\n'*************************************************************************\nFunction AlternateColor(ByVal OddColor As String, _\n ByVal EvenColor As String, ByVal Toggle As Boolean) As String\n If Toggle Then bOddRow = Not bOddRow\n If bOddRow Then\n Return OddColor\n Else\n Return EvenColor\n End If\nEnd Function\n'\nFunction RestartColor(ByVal OddColor As String) As String\n bOddRow = True\n Return OddColor\nEnd Function\n"
},
{
"answer_id": 1478089,
"author": "Sarah Vessels",
"author_id": 38743,
"author_profile": "https://Stackoverflow.com/users/38743",
"pm_score": 3,
"selected": false,
"text": "RowNumber bOddRow Nothing RowNumber =IIf(RowNumber(\"MyColumnGroupName\") Mod 2 = 0, \"AliceBlue\", \"Transparent\")\n"
},
{
"answer_id": 3425830,
"author": "Matt",
"author_id": 413281,
"author_profile": "https://Stackoverflow.com/users/413281",
"pm_score": 2,
"selected": false,
"text": "=IIf(RowNumber(\"DataSet1\") Mod 2 = 1, \"White\",\"Blue\")\n"
},
{
"answer_id": 5563007,
"author": "nonetaku",
"author_id": 528957,
"author_profile": "https://Stackoverflow.com/users/528957",
"pm_score": 3,
"selected": false,
"text": "= IIf(RowNumber(Nothing) Mod 2 = 0, \"Silver\", Nothing)\n"
},
{
"answer_id": 6777983,
"author": "ahmad",
"author_id": 856187,
"author_profile": "https://Stackoverflow.com/users/856187",
"pm_score": 6,
"selected": false,
"text": "=iif(RunningValue(Fields![rowgroupfield].Value.ToString,CountDistinct,Nothing) Mod 2,\"Gainsboro\", \"White\")\n"
},
{
"answer_id": 6941946,
"author": "Michael Eakins",
"author_id": 437301,
"author_profile": "https://Stackoverflow.com/users/437301",
"pm_score": 4,
"selected": false,
"text": "'*************************************************************************\n' -- Display alternate color banding (defined below) in detail rows\n' -- Call from BackgroundColor property of all detail row textboxes\n'*************************************************************************\nFunction AlternateColor(Byval rowNumber as integer) As String\n Dim OddColor As String = \"Green\"\n Dim EvenColor As String = \"White\"\n\n If rowNumber mod 2 = 0 then \n Return EvenColor\n Else\n Return OddColor\n End If\nEnd Function\n =Code.AlternateColor(rownumber(nothing))\n"
},
{
"answer_id": 9510135,
"author": "misha",
"author_id": 1241734,
"author_profile": "https://Stackoverflow.com/users/1241734",
"pm_score": 1,
"selected": false,
"text": "Private bOddRow As Boolean\n'*************************************************************************\n'-- Display green-bar type color banding in detail rows\n'-- Call from BackGroundColor property of all detail row textboxes\n'-- Set Toggle True for first item, False for others.\n'*************************************************************************\n'\nFunction AlternateColor(ByVal OddColor As String, _\n ByVal EvenColor As String, ByVal Toggle As Boolean) As String\n If Toggle Then bOddRow = Not bOddRow\n If bOddRow Then \n Return OddColor\n Else\n Return EvenColor\n End If\n End Function\n '\n Function RestartColor(ByVal OddColor As String) As String\n bOddRow = True\n Return OddColor\n End Function\n"
},
{
"answer_id": 13692016,
"author": "Kyle Hale",
"author_id": 32458,
"author_profile": "https://Stackoverflow.com/users/32458",
"pm_score": 3,
"selected": false,
"text": "=iif(RunningValue(Fields![RowGroupField].Value\n,CountDistinct,Nothing) Mod 2, \"LightSteelBlue\", \"White\") \"=ReportItems!RowGroupColor.Value\""
},
{
"answer_id": 23768811,
"author": "rpyzh",
"author_id": 2664868,
"author_profile": "https://Stackoverflow.com/users/2664868",
"pm_score": 2,
"selected": false,
"text": "countDistinct runningValue runningValue countDistinct countDistinct =iif(\n (RunningValue(Fields![RowGroupField].Value, countDistinct, \"FakeOrRealImmediateParentGroup\")\n + iif(IsNothing(RunningValue(Fields![RowGroupField].Value, First, \"GroupForRowGroupField\")), 1, 0)\n ) mod 2, \"White\", \"LightGrey\")\n"
},
{
"answer_id": 27914710,
"author": "Jeremy Thompson",
"author_id": 495455,
"author_profile": "https://Stackoverflow.com/users/495455",
"pm_score": 1,
"selected": false,
"text": "Private bOddRow As Boolean\nPrivate cellCount as Integer\n\nFunction AlternateColorByColumnCount(ByVal OddColor As String, ByVal EvenColor As String, ByVal ColCount As Integer) As String\n\nif cellCount = ColCount Then \nbOddRow = Not bOddRow\ncellCount = 0\nEnd if \n\ncellCount = cellCount + 1\n\nif bOddRow Then\n Return OddColor\nElse\n Return EvenColor\nEnd If\n\nEnd Function\n =Code.AlternateColorByColumnCount(\"LightGrey\",\"White\", 7)\n"
},
{
"answer_id": 38316880,
"author": "Soy Sauce Johnson",
"author_id": 4342077,
"author_profile": "https://Stackoverflow.com/users/4342077",
"pm_score": 0,
"selected": false,
"text": "= Iif ( RunningValue (Fields!description.Value + Fields!name.Value, CountDistinct, Nothing) Mod 2 = 0,\"#e6eed5\", \"Transparent\")\n"
},
{
"answer_id": 40557573,
"author": "Eneerge",
"author_id": 5003522,
"author_profile": "https://Stackoverflow.com/users/5003522",
"pm_score": 0,
"selected": false,
"text": "Public Dim BGColor As String = \"#ffffff\"\n\nFunction AlternateColor() As String\n If BGColor = \"#cccccc\" Then\n BGColor = \"#ffffff\"\n Return \"#cccccc\"\n Else\n BGColor = \"#cccccc\"\n Return \"#ffffff\"\n End If\nEnd Function\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29/"
] |
44,383 |
<p>I am looking for a method of reading emails using Pop3 in C# 2.0. Currently, I am using code found in <a href="http://www.codeproject.com/KB/IP/Pop3MimeClient.aspx?fid=341657" rel="noreferrer">CodeProject</a>. However, this solution is less than ideal. The biggest problem is that it doesn't support emails written in unicode.</p>
|
[
{
"answer_id": 102135,
"author": "Martin Vobr",
"author_id": 16132,
"author_profile": "https://Stackoverflow.com/users/16132",
"pm_score": 4,
"selected": false,
"text": "// \n// create client, connect and log in \nPop3 client = new Pop3();\nclient.Connect(\"pop3.example.org\");\nclient.Login(\"username\", \"password\");\n\n// get message list \nPop3MessageCollection list = client.GetMessageList();\n\nif (list.Count == 0)\n{\n Console.WriteLine(\"There are no messages in the mailbox.\");\n}\nelse \n{\n // download the first message \n MailMessage message = client.GetMailMessage(list[0].SequenceNumber);\n ...\n}\n\nclient.Disconnect();\n"
},
{
"answer_id": 669567,
"author": "Pawel Lesnikowski",
"author_id": 80894,
"author_profile": "https://Stackoverflow.com/users/80894",
"pm_score": 3,
"selected": false,
"text": "using(Pop3 pop3 = new Pop3())\n{\n pop3.Connect(\"mail.host.com\"); // Connect to server and login\n pop3.Login(\"user\", \"password\");\n\n foreach(string uid in pop3.GetAll())\n {\n IMail email = new MailBuilder()\n .CreateFromEml(pop3.GetMessageByUID(uid));\n Console.WriteLine( email.Subject );\n }\n pop3.Close(false); \n}\n"
},
{
"answer_id": 11553097,
"author": "Higty",
"author_id": 48905,
"author_profile": "https://Stackoverflow.com/users/48905",
"pm_score": 2,
"selected": false,
"text": "using (Pop3Client cl = new Pop3Client()) \n{ \n cl.UserName = \"MyUserName\"; \n cl.Password = \"MyPassword\"; \n cl.ServerName = \"MyServer\"; \n cl.AuthenticateMode = Pop3AuthenticateMode.Pop; \n cl.Ssl = false; \n cl.Authenticate(); \n ///Get first mail of my mailbox \n Pop3Message mg = cl.GetMessage(1); \n String MyText = mg.BodyText; \n ///If the message have one attachment \n Pop3Content ct = mg.Contents[0]; \n ///you can save it to local disk \n ct.DecodeData(\"your file path\"); \n} \n"
},
{
"answer_id": 13145186,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "smtpop.dll using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text; \nusing SmtPop;\n\nnamespace SMT_POP3 {\n\n class Program {\n static void Main(string[] args) {\n SmtPop.POP3Client pop = new SmtPop.POP3Client();\n pop.Open(\"<hostURL>\", 110, \"<username>\", \"<password>\");\n\n // Get message list from POP server\n SmtPop.POPMessageId[] messages = pop.GetMailList();\n if (messages != null) {\n\n // Walk attachment list\n foreach(SmtPop.POPMessageId id in messages) {\n SmtPop.POPReader reader= pop.GetMailReader(id);\n SmtPop.MimeMessage msg = new SmtPop.MimeMessage();\n\n // Read message\n msg.Read(reader);\n if (msg.AddressFrom != null) {\n String from= msg.AddressFrom[0].Name;\n Console.WriteLine(\"from: \" + from);\n }\n if (msg.Subject != null) {\n String subject = msg.Subject;\n Console.WriteLine(\"subject: \"+ subject);\n }\n if (msg.Body != null) {\n String body = msg.Body;\n Console.WriteLine(\"body: \" + body);\n }\n if (msg.Attachments != null && false) {\n // Do something with first attachment\n SmtPop.MimeAttachment attach = msg.Attachments[0];\n\n if (attach.Filename == \"data\") {\n // Read data from attachment\n Byte[] b = Convert.FromBase64String(attach.Body);\n System.IO.MemoryStream mem = new System.IO.MemoryStream(b, false);\n\n //BinaryFormatter f = new BinaryFormatter();\n // DataClass data= (DataClass)f.Deserialize(mem); \n mem.Close();\n } \n\n // Delete message\n // pop.Dele(id.Id);\n }\n }\n } \n pop.Quit();\n }\n }\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/889/"
] |
44,391 |
<p>This is related to <a href="https://stackoverflow.com/questions/43324/can-i-put-an-aspnet-session-id-in-a-hidden-form-field">another question I asked</a>. In summary, I have a special case of a URL where, when a form is POSTed to it, I can't rely on cookies for authentication or to maintain the user's session, but I somehow need to know who they are, and I need to know they're logged in!</p>
<p>I think I came up with a solution to my problem, but it needs fleshing out. Here's what I'm thinking. I create a hidden form field called "username", and place within it the user's username, encrypted. Then, when the form POSTs, even though I don't receive any cookies from the browser, I know they're logged in because I can decrypt the hidden form field and get the username.</p>
<p>The major security flaw I can see is replay attacks. How do I prevent someone from getting ahold of that encrypted string, and POSTing as that user? I know I can use SSL to make it harder to steal that string, and maybe I can rotate the encryption key on a regular basis to limit the amount of time that the string is good for, but I'd really like to find a bulletproof solution. Anybody have any ideas? Does the ASP.Net ViewState prevent replay? If so, how do they do it?</p>
<p><strong>Edit</strong>: I'm hoping for a solution that doesn't require anything stored in a database. Application state would be okay, except that it won't survive an IIS restart or work at all in a web farm or garden scenario. I'm accepting Chris's answer, for now, because I'm not convinced it's even possible to secure this without a database. But if someone comes up with an answer that does not involve the database, I'll accept it!</p>
|
[
{
"answer_id": 2092673,
"author": "awe",
"author_id": 109392,
"author_profile": "https://Stackoverflow.com/users/109392",
"pm_score": 1,
"selected": false,
"text": "LosFormatter private string EncodeText(string text) {\n StringWriter writer = new StringWriter();\n LosFormatter formatter = new LosFormatter();\n formatter.Serialize(writer, text);\n return writer.ToString();\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2527/"
] |
44,394 |
<p>I have a MemoryStream with the contents of a Font File (.ttf) and I would like to be able to create a FontFamily WPF object from that stream <strong>WITHOUT</strong> writing the contents of the stream to disk. I know this is possible with a System.Drawing.FontFamily but I cannot find out how to do it with System.Windows.Media.FontFamily.</p>
<p>Note: I will only have the stream, so I can't pack it as a resource in the application and because of disk permissions issues, will not be able to write the font file to disk for reference as "content"</p>
<p><strong>UPDATE:</strong></p>
<p>The <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.fontfamily?view=netframework-4.6.1" rel="nofollow noreferrer">API docs</a> how describe how an application resource can be used, though it is not clear to me whether that is an Embedded resource in the assembly or a file on disk.</p>
<blockquote>
<p>You can use a base URI value when you reference a font that is packaged as part of the application. For example, the base URI value can be a "pack://application" URI, which lets you reference fonts that are packaged as application resources. The following code example shows a font reference that is composed of a base URI value and a relative URI value.</p>
</blockquote>
|
[
{
"answer_id": 65662363,
"author": "Patrick Klug",
"author_id": 10779,
"author_profile": "https://Stackoverflow.com/users/10779",
"pm_score": 2,
"selected": false,
"text": "public static void Load(MemoryStream stream)\n{\n byte[] streamData = new byte[stream.Length];\n stream.Read(streamData, 0, streamData.Length);\n IntPtr data = Marshal.AllocCoTaskMem(streamData.Length); // Very important.\n Marshal.Copy(streamData, 0, data, streamData.Length);\n PrivateFontCollection pfc = new PrivateFontCollection();\n pfc.AddMemoryFont(data, streamData.Length);\n MemoryFonts.Add(pfc); // Your own collection of fonts here.\n Marshal.FreeCoTaskMem(data); // Very important.\n}\n\npublic static System.Windows.Media.FontFamily LoadFont(int fontId)\n{\n if (!Exists(fontId))\n {\n return null;\n }\n /*\n NOTE:\n This is basically how you convert a System.Drawing.FontFamily to System.Windows.Media.FontFamily, using PrivateFontCollection.\n */\n return new System.Windows.Media.FontFamily(MemoryFonts[fontId].Families[0].Name);\n}\n System.Drawing.PrivateFontCollection System.Drawing.Font MemoryStream Families[0].Name System.Windows.Media.FontFamily"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4572/"
] |
44,396 |
<p>I use Eclipse, Maven, and Java in my development. I use Maven to download dependencies (jar files and javadoc when available) and Maven's eclipse plug-in to generate the .project and .classpath files for Eclipse. When the dependency downloaded does not have attached javadoc I manually add a link for the javadoc in the .classpath file so that I can see the javadoc for the dependency in Eclipse. Then when I run Maven's eclipse plugin to regenerate the .classpath file it of course wipes out that change.</p>
<p>Is there a way to configure Maven's eclipse plug-in to automatically add classpath attributes for javadoc when running Maven's eclipse plug-in? </p>
<p>I'm only interested in answers where the javadoc and/or sources are not provided for the dependency in the maven repository, which is the case most often for me. Using downloadSources and/or downloadJavadocs properties won't help this problem.</p>
|
[
{
"answer_id": 44405,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": -1,
"selected": false,
"text": "-DdownloadSources=true"
},
{
"answer_id": 97168,
"author": "ddimitrov",
"author_id": 18187,
"author_profile": "https://Stackoverflow.com/users/18187",
"pm_score": 5,
"selected": false,
"text": "mvn eclipse:eclipse -DdownloadSources=true -DdownloadJavadocs=true \n <project>\n [...]\n <build>\n [...]\n <plugins>\n [...]\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-eclipse-plugin</artifactId>\n <configuration>\n <downloadSources>true</downloadSources>\n <downloadJavadocs>true</downloadJavadocs>\n </configuration>\n </plugin>\n [...]\n </plugins>\n [...]\n </build>\n [...]\n</project>\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4476/"
] |
44,401 |
<p>I've got a sign up form that requires the user to enter their email and password, both are in two separate text boxes. I want to provide a button that the user can click so that the password (which is masked) will appear in a popup when the user clicks the button.</p>
<p>Currently my JavaScript code for this is as follows:</p>
<pre><code> function toggleShowPassword() {
var button = $get('PASSWORD_TEXTBOX_ID');
var password;
if (button)
{
password = button.value;
alert(password);
button.value = password;
}
}
</code></pre>
<p>The problem is that every time the user clicks the button, the password is cleared in both Firefox and IE. I want them to be able to see their password in clear text to verify without having to retype their password.</p>
<p>My questions are:</p>
<ol>
<li><p>Why does the password field keep getting reset with each button click?</p></li>
<li><p>How can I make it so the password field is NOT cleared once the user has seen his/her password in clear text?</p></li>
</ol>
|
[
{
"answer_id": 44436,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 1,
"selected": false,
"text": "button.value = password;\n password.value alert() function toggleShowPassword() { \n var button = $get('PASSWORD_TEXTBOX_ID');\n if (button)\n {\n alert(button.value);\n } \n button.value = \"blah\""
},
{
"answer_id": 44442,
"author": "Rytis",
"author_id": 979,
"author_profile": "https://Stackoverflow.com/users/979",
"pm_score": 0,
"selected": false,
"text": "button.value = password;"
},
{
"answer_id": 44458,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 1,
"selected": false,
"text": "<input type=\"button\" value=\"Show My Password\" onclick=\"toggleShowPassword()\"/>\n"
},
{
"answer_id": 44462,
"author": "JesDaw",
"author_id": 4440,
"author_profile": "https://Stackoverflow.com/users/4440",
"pm_score": 1,
"selected": false,
"text": "<input type=\"button\" onclick=\"toggleShowPassword();\">\n"
},
{
"answer_id": 44468,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 2,
"selected": true,
"text": "<html>\n <head>\n <script type=\"text/javascript\" src=\"prototype.js\"></script>\n <script type=\"text/javascript\">\n function toggleShowPassword() { \n var textBox = $('PasswordText');\n if (textBox)\n {\n alert(textBox.value); \n } \n }\n </script>\n </head>\n <body>\n <input type=\"password\" id=\"PasswordText\" /><input type=\"button\" onclick=\"toggleShowPassword();\" value=\"Show Password\" />\n </body>\n</html>\n"
},
{
"answer_id": 44549,
"author": "eviljack",
"author_id": 750,
"author_profile": "https://Stackoverflow.com/users/750",
"pm_score": 0,
"selected": false,
"text": " OnClientClick=\"myOnClick()\"\n OnClientClick=\"return myOnClick()\"\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/750/"
] |
44,408 |
<p>I would like to generate a random floating point number between 2 values. What is the best way to do this in C#?</p>
|
[
{
"answer_id": 44424,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 2,
"selected": false,
"text": "// generate a random number starting with 5 and less than 15\nRandom r = new Random();\nint num = r.Next(5, 15); \n"
},
{
"answer_id": 44428,
"author": "Eric",
"author_id": 4540,
"author_profile": "https://Stackoverflow.com/users/4540",
"pm_score": 4,
"selected": false,
"text": "System.Random r = new System.Random();\n\ndouble rnd( double a, double b )\n{\n return a + r.NextDouble()*(b-a);\n}\n"
},
{
"answer_id": 44430,
"author": "enigmatic",
"author_id": 443575,
"author_profile": "https://Stackoverflow.com/users/443575",
"pm_score": 1,
"selected": false,
"text": "Random randNum = new Random();\nrandNum. NextDouble(Min, Max);\n"
},
{
"answer_id": 44461,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 7,
"selected": true,
"text": "NextDouble"
},
{
"answer_id": 44472,
"author": "Sameer Alibhai",
"author_id": 2343,
"author_profile": "https://Stackoverflow.com/users/2343",
"pm_score": 1,
"selected": false,
"text": "byte[] salt = new byte[8];\nRNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();\nrng.GetBytes(salt);\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064/"
] |
44,421 |
<p>I have a web application developed with ASP.net and C# that is running on my companies' intranet. Because all the users for this application are all using Microsoft Outlook without exception, I would like for the the application to open up an Outlook message on the client-side. <strong>I understand that Office is designed to be run on the desktop and not from a server, however I have no trouble creating a Word or Excel document on the client-side.</strong> </p>
<p>I have code that instantiates the Outlook object using the Microsoft.Office.Interop.Outlook namespace and Outlook installed on the server. When I try to run the code from the server, I get a DCOM source error message that states "The machine-default permission settings do not grant Local Activation permission for the COM Server application with CLSID {000C101C-0000-0000-C000-000000000046} to the user This security permission can be modified using the Component Services administrative tool." I have modified the permissions using the Component Services tool, but still get this same error. </p>
<p>Is there a way to overcome this or is this a fruitless exercise because Outlook cannot be opened on the client side from the server-side code?</p>
<p>Mailto will not work due to the extreme length that the emails can obtain. Also, the user that sends it needs add in eye-candy to the text for the recipients.</p>
|
[
{
"answer_id": 44452,
"author": "Doozer",
"author_id": 4581,
"author_profile": "https://Stackoverflow.com/users/4581",
"pm_score": 1,
"selected": false,
"text": "mailto:[email protected]?subject=This%20is%20the%20subject&body=Hello%20there!\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
] |
44,453 |
<p>I've got a web application working using VB and Ajax. I'm using updatepanels to avoid the irritating "flicker" on postbacks to the server. </p>
<p>I would like to have a button control defined within the updatepanel itself (tried moving it outside and got some catastrophic error, so left it there) that makes the current panel not visible and a sibling panel visible. This works with the exception that the button must be clicked twice. Not double clicked, but clicked once than clicked again. </p>
<p>In setting breakpoints I discovered the code behind that's attached to the button is actually being executed on the first click, but the panels don't switch as expected. If I click the same button OR worse yet, a different button, the expected behavior of the second panel appearing occurs. However, with the second button being clicked there's an unwanted bonus of a third panel being displayed, the third panel being made visible due to the second button being clicked.</p>
<p>I'm assuming this behavior is due to the updatepanel and its Ajax nature. Is there a way to avoid the second click? Am I misusing the updatepanel? I really wanted to use a modal popup (right out of the AjaxToolKit) but had problems with posting back the data so I opted for this approach. Any insights, assistance, even criticism would be welcome as this has plagued me long enough. Thanks</p>
|
[
{
"answer_id": 259156,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 0,
"selected": false,
"text": "protected override void OnInit(EventArgs e)\n{\n var scriptManager = ScriptManager.GetCurrent(this);\n // or this.Page in a UserControl, etc.\n\n scriptManager.RegisterPostBackControl(someButton);\n scriptManager.RegisterPostBackControl(someOtherButton);\n // etc. for each control that needs to update something outside the UpdatePanel\n}\n"
},
{
"answer_id": 20674021,
"author": "Quintin Humphreys",
"author_id": 3117866,
"author_profile": "https://Stackoverflow.com/users/3117866",
"pm_score": 0,
"selected": false,
"text": "myControl.id=\"newID\"\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
44,470 |
<p>Every time I publish the application in <a href="http://en.wikipedia.org/wiki/ClickOnce" rel="nofollow noreferrer">ClickOnce</a> I get get it to update the revision number by one. Is there a way to get this change automatically to change the version number in AssemblyInfo.cs file (all our error reporting looks at the Assembly Version)?</p>
|
[
{
"answer_id": 152430,
"author": "Rinat Abdullin",
"author_id": 47366,
"author_profile": "https://Stackoverflow.com/users/47366",
"pm_score": 2,
"selected": false,
"text": "-v -mv"
},
{
"answer_id": 152493,
"author": "Jason Stangroome",
"author_id": 20819,
"author_profile": "https://Stackoverflow.com/users/20819",
"pm_score": 6,
"selected": true,
"text": "AfterCompile <MSBuild Projects=\"$(SolutionRoot)\\MyProject\\Myproject.csproj\"\n Properties=\"PublishDir=$(OutDir)\\myProjectPublish\\;\n ApplicationVersion=$(PublishApplicationVersion);\n Configuration=$(Configuration);Platform=$(Platform)\"\n Targets=\"Publish\" />\n PublishApplicationVersion if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)\n{\n Debug.WriteLine(System.Deployment.Application.ApplicationDeployment.\n CurrentDeployment.CurrentVersion);\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
] |
44,476 |
<p>I'm trying to convert a multipage color tiff file to a c# CompressionCCITT3 tiff in C#. I realize that I need to make sure that all pixels are 1 bit. I have not found a useful example of this online.</p>
|
[
{
"answer_id": 1364055,
"author": "plinth",
"author_id": 20481,
"author_profile": "https://Stackoverflow.com/users/20481",
"pm_score": 1,
"selected": false,
"text": "FileSystemImageSource source = new FileSystemImageSource(\"path-to-your-file.tif\", true); // true = loop over all frames\n// tiff encoder will auto-select an appropriate compression - CCITT4 for 1 bit.\nTiffEncoder encoder = new TiffEncoder();\nencoder.Append = true;\n\n// DynamicThresholdCommand is very good for documents. For pictures, use DitherCommand\nDynamicThresholdCommand threshold = new DynamicThresholdCommand();\n\nusing (FileStream outstm = new FileStream(\"path-to-output.tif\", FileMode.Create)) {\n while (source.HasMoreImages()) {\n AtalaImage image = source.AcquireNext();\n AtalaImage finalImage = image;\n // convert when needed.\n if (image.PixelFormat != PixelFormat.Pixel1bppIndexed) {\n finalImage = threshold.Apply().Image;\n }\n encoder.Save(outstm, finalImage, null);\n if (finalImage != image) {\n finalImage.Dispose();\n }\n source.Release(image);\n }\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/178/"
] |
44,481 |
<p>For this directory structure:</p>
<pre><code>.
|-- README.txt
|-- firstlevel.rb
`-- lib
|-- models
| |-- foo
| | `-- fourthlevel.rb
| `-- thirdlevel.rb
`-- secondlevel.rb
3 directories, 5 files
</code></pre>
<p>The glob would match: </p>
<pre><code>firstlevel.rb
lib/secondlevel.rb
lib/models/thirdlevel.rb
lib/models/foo/fourthlevel.rb
</code></pre>
|
[
{
"answer_id": 44486,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 1,
"selected": false,
"text": "Dir.glob('**/*.rb') perhaps?\n"
},
{
"answer_id": 44494,
"author": "Chris AtLee",
"author_id": 4558,
"author_profile": "https://Stackoverflow.com/users/4558",
"pm_score": 2,
"selected": false,
"text": "**/*.rb"
},
{
"answer_id": 44599,
"author": "quackingduck",
"author_id": 3624,
"author_profile": "https://Stackoverflow.com/users/3624",
"pm_score": 0,
"selected": false,
"text": "bash zsh ls **/*.rb\n ruby ruby -e \"puts Dir.glob('**/*.rb')\"\n"
},
{
"answer_id": 44651,
"author": "Nick",
"author_id": 1236,
"author_profile": "https://Stackoverflow.com/users/1236",
"pm_score": 3,
"selected": true,
"text": "find . -name '*.rb' -type f\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3624/"
] |
44,509 |
<p>Our company has multiple domains set up with one website hosted on each of the domains. At this time, each domain has its own authentication which is done via cookies. </p>
<p>When someone logged on to one domain needs to access anything from the other, the user needs to log in again using different credentials on the other website, located on the other domain. </p>
<p>I was thinking of moving towards single sign on (SSO), so that this hassle can be eliminated. I would appreciate any ideas on how this could be achieved, as I do not have any experience in this regard.</p>
<p>Thanks.</p>
<p><strong>Edit:</strong>
The websites are mix of internet (external) and intranet (internal-used within the company) sites.</p>
|
[
{
"answer_id": 44596,
"author": "jason saldo",
"author_id": 1293,
"author_profile": "https://Stackoverflow.com/users/1293",
"pm_score": 4,
"selected": false,
"text": "mail.xyz.example www.xyz.example logon.xyz.example abc.example xyz.example www.tre.example"
},
{
"answer_id": 45010,
"author": "grom",
"author_id": 486,
"author_profile": "https://Stackoverflow.com/users/486",
"pm_score": 7,
"selected": false,
"text": "login.mydomain.example master_login.php client_login.php login.mydomain.example/master_login.php client.mydomain.example/client_login.php master_login.php client1.abc.example client2.xyz.example login.mydomain.example"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1311/"
] |
44,532 |
<p>Do you attach the images? </p>
<p>Use absolute urls? </p>
<p>How do you best avoid getting flagged as spam? </p>
|
[
{
"answer_id": 45118,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 3,
"selected": false,
"text": "<img src=\"cid:imagefilename.jpg\" />\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1797/"
] |
44,542 |
<p>Can someome provide code or pseudo-code for how the paging links on StackOverflow are generated?</p>
<p>I keep racking my brain but can't think of a decent way to build the dynamic links that always show the 2 pages around the current, plus the first and last.</p>
<p>Example: <code>1 ... 5 6 7 ... 593</code></p>
|
[
{
"answer_id": 44614,
"author": "Ian",
"author_id": 4396,
"author_profile": "https://Stackoverflow.com/users/4396",
"pm_score": 2,
"selected": false,
"text": "numPages = ceiling(totalRecords / numPerPage)"
},
{
"answer_id": 44627,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 1,
"selected": false,
"text": "public void PageLinks(int currentPage, int lastPage) {\n if (currentPage > 2) \n Add('[1]', '...');\n for(int i=Math.Max(1, currentPage-1); i< Math.Min(currentPage+1, lastPage); i++)\n Add('[i]');\n if (currentPage < lastPage-1)\n Add('...', '[lastpage]');\n}\n"
},
{
"answer_id": 44844,
"author": "Bill",
"author_id": 102,
"author_profile": "https://Stackoverflow.com/users/102",
"pm_score": 7,
"selected": true,
"text": "function printPageLinksFirstTry(num totalPages, num currentPage)\n if ( currentPage > 1 )\n print \"Prev\"\n print \"1\"\n print \"...\"\n print currentPage - 1\n print currentPage\n print currentPage + 1\n print \"...\"\n print totalPages\n if ( currentPage < totalPages )\n print \"Next\"\nendFunction\n function printPageLinksHandleCloseToEnds(num totalPages, num currentPage)\n if ( currentPage > 1 )\n print \"Prev\"\n print \"1\"\n if ( currentPage > 2 )\n print \"...\"\n if ( currentPage > 2 )\n print currentPage - 1\n print currentPage\n if ( currentPage < totalPages - 1 )\n print currentPage + 1\n if ( currentPage < totalPages - 1 )\n print \"...\"\n print totalPages\n if ( currentPage < totalPages )\n print \"Next\"\nendFunction\n function printPageLinksCleanedUp(num totalPages, num currentPage)\n if ( currentPage > 1 )\n print \"Prev\"\n print \"1\"\n if ( currentPage > 2 )\n print \"...\"\n print currentPage - 1\n print currentPage\n if ( currentPage < totalPages - 1 )\n print currentPage + 1\n print \"...\"\n print totalPages\n if ( currentPage < totalPages )\n print \"Next\"\nendFunction\n function printPageLinksFinal(num totalPages, num currentPage)\n if ( totalPages == 1 )\n return\n\n if ( currentPage > 1 )\n print \"Prev\"\n\n print \"1\"\n\n if ( currentPage > 2 )\n print \"...\"\n print currentPage - 1\n\n if ( currentPage != 1 and currentPage != totalPages )\n print currentPage\n\n if ( currentPage < totalPages - 1 )\n print currentPage + 1\n print \"...\"\n\n print totalPages\n\n if ( currentPage < totalPages )\n print \"Next\"\n\nendFunction\n function printPageLinksFinalReally(num totalPages, num currentPage)\n if ( totalPages == 1 )\n return\n\n if ( currentPage > 1 )\n print \"Prev\"\n\n print \"1\"\n\n if ( currentPage > 2 )\n print \"...\"\n if ( currentPage == totalPages and totalPages > 3 )\n print currentPage - 2\n print currentPage - 1\n\n if ( currentPage != 1 and currentPage != totalPages )\n print currentPage\n\n if ( currentPage < totalPages - 1 )\n print currentPage + 1\n if ( currentPage == 1 and totalPages > 3 )\n print currentPage + 2\n print \"...\"\n\n print totalPages\n\n if ( currentPage < totalPages )\n print \"Next\"\n\nendFunction\n"
},
{
"answer_id": 2847286,
"author": "Just a learner",
"author_id": 170931,
"author_profile": "https://Stackoverflow.com/users/170931",
"pm_score": 0,
"selected": false,
"text": "package com.edde;\n\n/**\n * @author Yang Shuai\n */\npublic class Pager {\n\n /**\n * This is a method used to display the paging links(pagination or sometimes called pager).\n * The totalPages are the total page you need to display. You can get this value using the\n * formula:\n * \n * total_pages = total_records / items_per_page\n * \n * This methods is just a pseudo-code.\n * \n * \n * @param totalPages how many pages you need to display\n * @param currentPage you are in which page now\n */\n public static void printPageLinks(int totalPages, int currentPage) {\n\n // how many pages to display before and after the current page\n int x = 2;\n\n // if we just have one page, show nothing\n if (totalPages == 1) {\n return;\n }\n\n // if we are not at the first page, show the \"Prev\" button\n if (currentPage > 1) {\n System.out.print(\"Prev\");\n }\n\n // always display the first page\n if (currentPage == 1) {\n System.out.print(\" [1]\");\n } else {\n System.out.print(\" 1\");\n }\n\n // besides the first and last page, how many pages do we need to display?\n int how_many_times = 2 * x + 1;\n\n // we use the left and right to restrict the range that we need to display\n int left = Math.max(2, currentPage - 2 * x - 1);\n int right = Math.min(totalPages - 1, currentPage + 2 * x + 1);\n\n // the upper range restricted by left and right are more loosely than we need,\n // so we further restrict this range we need to display\n while (right - left > 2 * x) {\n if (currentPage - left < right - currentPage) {\n right--;\n right = right < currentPage ? currentPage : right;\n } else {\n left++;\n left = left > currentPage ? currentPage : left;\n }\n }\n\n // do we need display the left \"...\"\n if (left >= 3) {\n System.out.print(\" ...\");\n }\n\n // now display the middle pages, we display how_many_times pages from page left\n for (int i = 1, out = left; i <= how_many_times; i++, out++) {\n // there are some pages we need not to display\n if (out > right) {\n continue;\n }\n\n // display the actual page\n if (out == currentPage) {\n System.out.print(\" [\" + out + \"]\");\n } else {\n System.out.print(\" \" + out);\n }\n }\n\n // do we need the right \"...\"\n if (totalPages - right >= 2) {\n System.out.print(\" ...\");\n }\n\n // always display the last page\n if (currentPage == totalPages) {\n System.out.print(\" [\" + totalPages + \"]\");\n } else {\n System.out.print(\" \" + totalPages);\n }\n\n // if we are not at the last page, then display the \"Next\" button\n if (currentPage < totalPages) {\n System.out.print(\" Next\");\n }\n System.out.println();\n }\n\n public static void main(String[] args) {\n // printPageLinks(50, 3);\n help(500);\n }\n\n public static void test(int n) {\n for (int i = 1; i <= n; i++) {\n printPageLinks(n, i);\n }\n System.out.println(\"------------------------------\");\n }\n\n public static void help(int n) {\n for (int i = 1; i <= n; i++) {\n test(i);\n }\n }\n\n public static void help(int from, int to) {\n for (int i = from; i <= to; i++) {\n test(i);\n }\n }\n\n}\n"
},
{
"answer_id": 51988336,
"author": "Tsvetan Filev",
"author_id": 475733,
"author_profile": "https://Stackoverflow.com/users/475733",
"pm_score": 0,
"selected": false,
"text": "// Input\ntotal_items // Number of rows, records etc. from db, file or whatever\nper_page // num items per page\npage // current page\nvisible_pages // number of visible pages\n\n// Calculations\nlastPage = ceil(total_items / per_page);\nprevPage = page - 1 < 1 ? 0 : page - 1;\nnextPage = page + 1 > lastPage ? 0 : page + 1;\nhalfpages = ceil(visible_pages / 2);\nstartPage = page - halfpages < 1 ? 1 : page - halfpages;\nendPage = startPage + visible_pages - 1;\nif(endPage > lastPage) {\n startPage -= endPage - lastPage;\n startPage = startPage < 1 ? 1 : startPage;\n endPage = startPage + visible_pages > lastPage ? lastPage : startPage + visible_pages - 1;\n}\n\n// Output\nlastPage // Total number of pages\nprevPage // Previous page number (if 0 there is no prev page)\nnextPage // Next page number (if 0 there is no next page)\nstartPage // First visible page\nendPage // Last visible page\n if prevPage\n [1] [prevPage] \nendif\n\n[startPage] ... [endPage] \n\nif nextPage\n [nextPage] [lastPage] \nendif\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1097/"
] |
44,554 |
<p>As <a href="https://blog.stackoverflow.com/2008/09/podcast-20/">Jeff Atwood asked</a>: "What’s your logging philosophy? Should all code be littered with <code>.logthis()</code> and <code>.logthat()</code> calls? Or do you inject logging after the fact somehow?"</p>
|
[
{
"answer_id": 44577,
"author": "Pierre Arnaud",
"author_id": 4597,
"author_profile": "https://Stackoverflow.com/users/4597",
"pm_score": 1,
"selected": false,
"text": "System.Diagnostics.Assert"
},
{
"answer_id": 549143,
"author": "Bob Moore",
"author_id": 9368,
"author_profile": "https://Stackoverflow.com/users/9368",
"pm_score": 4,
"selected": false,
"text": "#define DEBUG_ERROR 1\n#define DEBUG_BASIC 2\n#define DEBUG_DETAIL 4\n#define DEBUG_MSG_BASIC 8\n#define DEBUG_MSG_POLL 16\n#define DEBUG_MSG_STATUS 32\n#define DEBUG_METRICS 64\n#define DEBUG_EXCEPTION 128\n#define DEBUG_STATE_CHANGE 256\n#define DEBUG_DB_READ 512\n#define DEBUG_DB_WRITE 1024\n#define DEBUG_SQL_TEXT 2048\n#define DEBUG_MSG_CONTENTS 4096\n"
},
{
"answer_id": 33783287,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "log_once"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] |
44,569 |
<p>I have never used octal numbers in my code nor come across any code that used it (hexadecimal and bit twiddling notwithstanding).</p>
<p>I started programming in C/C++ about 1994 so maybe I'm too young for this? Does older code use octal? C includes support for these by prepending a 0, but where is the code that uses these base 8 number literals?</p>
|
[
{
"answer_id": 44575,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "chmod mkdir"
},
{
"answer_id": 44590,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 7,
"selected": true,
"text": "0x492492\n 022222222\n 010 010 010 010 010 010 010 010\n"
},
{
"answer_id": 1619498,
"author": "Tim",
"author_id": 188691,
"author_profile": "https://Stackoverflow.com/users/188691",
"pm_score": 5,
"selected": false,
"text": "0"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2543/"
] |
44,617 |
<p>I would like to be able to add a "message" to a unit test, such that it actually appears within the TestResult.xml file generated by NUnit. For example, this is currently generated:</p>
<pre><code><results>
<test-case name="MyNamespace.Tests.MyTest" executed="True" success="True" time="0.203" asserts="4" />
</results>
</code></pre>
<p>I would like to be able to have an additional attribute (or node as the case may be), such as:</p>
<pre><code><results>
<test-case name="MyNamespace.Tests.MyTest" executed="True" success="True" time="0.203" asserts="4" message="Tested that some condition was met." />
</results>
</code></pre>
<p>The idea is that "message" above would somehow be defined within the test method itself (in my case, generated at run-time). Is there a property somewhere that I'm missing to be able to do something like this?</p>
|
[
{
"answer_id": 339415,
"author": "Cpt. Jack Sparrow",
"author_id": 43050,
"author_profile": "https://Stackoverflow.com/users/43050",
"pm_score": 3,
"selected": false,
"text": "Assert.AreEqual(250.00, destination.Balance, \"some message here\");\n"
},
{
"answer_id": 48751457,
"author": "J-Roel",
"author_id": 5687137,
"author_profile": "https://Stackoverflow.com/users/5687137",
"pm_score": 0,
"selected": false,
"text": "[TestFixture]\npublic class TestBase\n{\n\n public IWebDriver driver;\n\n //[OneTimeSetUp] and [OneTimeTearDown] go here if needed\n\n [SetUp]\n public void Setup(){\n driver = Shortcuts.SetDriver(\"my browser\");\n }\n\n [TearDown]\n public void TearDown()\n {\n driver.Quit();\n Comment(\"@Result: \" + TestContext.CurrentContext.Result.Outcome.ToString());\n }\n\n public void Comment(string _comment)\n {\n TestContext.Out.WriteLine(_comment);\n }\n public void Error(string _error)\n {\n TestContext.Error.WriteLine(_error);\n }\n\n}\n //Role Management\npublic class RoleManagementTests : TestBase\n{\n [TestCase]\n public void RoleManagement_7777_1()\n {\n Comment(\"Expected: User has the ability to view all roles in the system.\");\n //Test goes here\n }\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2696/"
] |
44,656 |
<p>The code that I want to write is like this:</p>
<pre><code>void MethodOnThreadA()
{
for (;;)
{
// Do stuff
if (ErrorConditionMet)
ThrowOnThread(threadB, new MyException(...));
}
}
void MethodOnThreadB()
{
try
{
for (;;)
{
// Do stuff
}
}
catch (MyException ex)
{
// Do the right thing for this exception.
}
}
</code></pre>
<p>I know I can have thread B periodically check, in thread safe way, to see if a flag has been set by thread A, but that makes the code more complicated. Is there a better mechanism that I can use?</p>
<p>Here is a more fleshed out example of periodically checking:</p>
<pre><code>Dictionary<Thread, Exception> exceptionDictionary = new Dictionary<Thread, Exception>();
void ThrowOnThread(Thread thread, Exception ex)
{
// the exception passed in is going to be handed off to another thread,
// so it needs to be thread safe.
lock (exceptionDictionary)
{
exceptionDictionary[thread] = ex;
}
}
void ExceptionCheck()
{
lock (exceptionDictionary)
{
Exception ex;
if (exceptionDictionary.TryGetValue(Thread.CurrentThread, out ex))
throw ex;
}
}
void MethodOnThreadA()
{
for (;;)
{
// Do stuff
if (ErrorConditionMet)
ThrowOnThread(threadB, new MyException(...));
}
}
void MethodOnThreadB()
{
try
{
for (;;)
{
// Do stuff
ExceptionCheck();
}
}
catch (MyException ex)
{
// Do the right thing for this exception.
}
}
</code></pre>
|
[
{
"answer_id": 44761,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": true,
"text": "At some random time, throw an exception on thread B:\n try {\n //do stuff\n} finally {\n CloseResourceOne();\n // ThreadA's exception gets thrown NOW, in the middle \n // of our finally block and resource two NEVER gets closed.\n // Obviously this is BAD, and the only way to stop is to NOT throw\n // exceptions across threads\n CloseResourceTwo();\n}\n"
},
{
"answer_id": 44852,
"author": "Rob",
"author_id": 1006,
"author_profile": "https://Stackoverflow.com/users/1006",
"pm_score": 0,
"selected": false,
"text": "At some random time, throw an exception on thread C:\n try {\n Signal thread C that exceptions may be thrown\n //do stuff, without needing to check exit conditions\n Signal thread C that exceptions may no longer be thrown\n}\ncatch {\n // exception/interrupt occurred handle...\n}\nfinally {\n // ...and clean up\n CloseResourceOne();\n CloseResourceTwo();\n}\n while(thread-B-wants-exceptions) {\n try {\n Thread.Sleep(1) \n }\n catch {\n // exception was thrown...\n if Thread B still wants to handle exceptions\n throw-in-B\n }\n }\n"
},
{
"answer_id": 3436002,
"author": "GenericProgrammer",
"author_id": 178196,
"author_profile": "https://Stackoverflow.com/users/178196",
"pm_score": 2,
"selected": false,
"text": "// Obviously this is BAD, and the only way to stop is to NOT throw\n// exceptions across threads\n PrepareConstrainedRegions SafeHandle PrepareConstrainedRegions public MySafeHandle AllocateHandle()\n{\n // Allocate SafeHandle first to avoid failure later.\n MySafeHandle sh = new MySafeHandle();\n\n RuntimeHelpers.PrepareConstrainedRegions();\n try { }\n finally // this finally block is atomic an uninterruptible by inter-thread exceptions\n {\n MyStruct myStruct = new MyStruct();\n NativeAllocateHandle(ref myStruct);\n sh.SetHandle(myStruct.m_outputHandle);\n }\n\n return sh;\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4592/"
] |
44,660 |
<p>I need to write a program that can sift through specially-formatted text files (essentially CSV files with a fixed set of column types that have different delimiters for some columns ... comma in most places, colons in others) to search for formatting errors. I figure regular expressions will be the way to go.</p>
<p>The question: Is there a good regex library for VB6?</p>
<p>Thank you!</p>
<p>Edit: Holy crap, 3 responses in under an hour. Thanks a ton, folks! I've heard such good things about Regex Buddy from Jeff's postings / podcasting, that I will have to take a look.</p>
|
[
{
"answer_id": 30513515,
"author": "Michael Kropat",
"author_id": 27581,
"author_profile": "https://Stackoverflow.com/users/27581",
"pm_score": 2,
"selected": false,
"text": "Dim matcher As RegExp\nSet matcher = New RegExp\nmatcher.Pattern = \"^super cool string$\"\nIf matcher.Test(someString) Then\n '...do something...\nEnd If\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4602/"
] |
44,693 |
<p>In C++, what alternatives do I have for exposing a collection, from the point of view of performance and data integrity?</p>
<p>My problem is that I want to return an internal list of data to the caller, but I don't want to generate a copy. Thant leaves me with either returning a reference to the list, or a pointer to the list. However, I'm not crazy about letting the caller change the data, I just want to let it read the data. </p>
<ul>
<li>Do I have to choose between performance and data integrity? </li>
<li>If so, is in general better to go one way or is it particular to the case? </li>
<li>Are there other alternatives?</li>
</ul>
|
[
{
"answer_id": 44697,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 2,
"selected": false,
"text": "const std::vector<mydata>& getData()\n{\n return _myPrivateData;\n}\n const_cast"
},
{
"answer_id": 44762,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": true,
"text": "begin() end() class Blah\n{\npublic:\n typedef std::vector<mydata> mydata_collection;\n typedef myDataCollection::const_iterator mydata_const_iterator;\n\n // ...\n\n mydata_const_iterator data_begin() const \n { return myPreciousData.begin(); }\n mydata_const_iterator data_end() const \n { return myPreciousData.end(); }\n\nprivate:\n mydata_collection myPreciousData;\n};\n Blah blah;\nfor (Blah::mydata_const_iterator itr = blah.data_begin();\n itr != blah.data_end();\n ++itr)\n{\n // ...\n}\n"
},
{
"answer_id": 44785,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "std::list const_cast std::list boost::shared_ptr"
},
{
"answer_id": 44797,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "const std::vector<T>& getData() { return mData; }\n const T* getDataAt(size_t index)\n{\n return &mData[index];\n}\n typedef vector<T>::const_iterator range_iterator_type;\nboost::iterator_range< range_iterator_type >& getDataRange()\n{\n return boost::iterator_range(mData.begin(), mData.end());\n}\n"
},
{
"answer_id": 45064,
"author": "David Joyner",
"author_id": 1146,
"author_profile": "https://Stackoverflow.com/users/1146",
"pm_score": 3,
"selected": false,
"text": "#include <algorithm>\n#include <boost/function.hpp>\n\nclass Blah\n{\n public:\n void for_each_data(const std::function<void(const mydata&)>& f) const\n {\n std::for_each(myPreciousData.begin(), myPreciousData.end(), f);\n }\n\n private:\n typedef std::vector<mydata> mydata_collection;\n mydata_collection myPreciousData;\n};\n"
},
{
"answer_id": 968346,
"author": "Agnel Kurian",
"author_id": 45603,
"author_profile": "https://Stackoverflow.com/users/45603",
"pm_score": 0,
"selected": false,
"text": "const MyClass tmp;\nfor(int i = 0; i < n; i++){\n tmp = elements[i];\n callback(tmp);\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3081/"
] |
44,713 |
<p>How can I create an empty one-dimensional string array?</p>
|
[
{
"answer_id": 44720,
"author": "ZombieSheep",
"author_id": 377,
"author_profile": "https://Stackoverflow.com/users/377",
"pm_score": 1,
"selected": false,
"text": "string[] newArray = new string[0];\n List<string>\n newListOfString.ToArray();\n"
},
{
"answer_id": 44725,
"author": "Chris Zwiryk",
"author_id": 734,
"author_profile": "https://Stackoverflow.com/users/734",
"pm_score": 3,
"selected": false,
"text": "Dim myArray(9) as String\n Dim myArray() as String\n ReDim myArray(9) as String\n Dim myList as New List(Of String)\nmyList.Add(\"foo\")\nmyList.Add(\"bar\")\n myList.ToArray()\n"
},
{
"answer_id": 44827,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "Dim s(0) As String System.Collections.Specialized.StringCollection System.Collections.Generic.List(Of String) Dim s As String()\n Dim t() As String\n"
},
{
"answer_id": 44830,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 6,
"selected": false,
"text": "Dim myArray(10) as String Dim str(-1) as String ' -1 + 1 = 0, so this has 0 elements\nDim str() as String = New String() { } ' implicit size, initialized to empty\n"
},
{
"answer_id": 26910445,
"author": "Michael Johnson",
"author_id": 3596159,
"author_profile": "https://Stackoverflow.com/users/3596159",
"pm_score": 2,
"selected": false,
"text": "Dim strings() As String = {}\n MessageBox.Show(\"count: \" + strings.Count.ToString)\n"
},
{
"answer_id": 28195263,
"author": "JustinMichel",
"author_id": 1469095,
"author_profile": "https://Stackoverflow.com/users/1469095",
"pm_score": 3,
"selected": false,
"text": "Dim strings() as String = {}\nDim strings as String() = {}\n"
},
{
"answer_id": 51678152,
"author": "Scott Mitchell",
"author_id": 2657744,
"author_profile": "https://Stackoverflow.com/users/2657744",
"pm_score": 2,
"selected": false,
"text": "Dim strEmpty() As String = Enumerable.Empty(Of String).ToArray\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3821/"
] |
44,715 |
<p>Ruby setters—whether created by <code>(c)attr_accessor</code> or manually—seem to be the only methods that need <code>self.</code> qualification when accessed within the class itself. This seems to put Ruby alone the world of languages:</p>
<ul>
<li>All methods need <code>self</code>/<code>this</code> (like Perl, and I think Javascript)</li>
<li>No methods require <code>self</code>/<code>this</code> is (C#, Java)</li>
<li>Only setters need <code>self</code>/<code>this</code> (Ruby?)</li>
</ul>
<p>The best comparison is C# vs Ruby, because both languages support accessor methods which work syntactically just like class instance variables: <code>foo.x = y</code>, <code>y = foo.x</code> . C# calls them properties.</p>
<p>Here's a simple example; the same program in Ruby then C#:</p>
<pre><code>class A
def qwerty; @q; end # manual getter
def qwerty=(value); @q = value; end # manual setter, but attr_accessor is same
def asdf; self.qwerty = 4; end # "self." is necessary in ruby?
def xxx; asdf; end # we can invoke nonsetters w/o "self."
def dump; puts "qwerty = #{qwerty}"; end
end
a = A.new
a.xxx
a.dump
</code></pre>
<p>take away the <code>self.qwerty =()</code> and it fails (Ruby 1.8.6 on Linux & OS X). Now C#:</p>
<pre><code>using System;
public class A {
public A() {}
int q;
public int qwerty {
get { return q; }
set { q = value; }
}
public void asdf() { qwerty = 4; } // C# setters work w/o "this."
public void xxx() { asdf(); } // are just like other methods
public void dump() { Console.WriteLine("qwerty = {0}", qwerty); }
}
public class Test {
public static void Main() {
A a = new A();
a.xxx();
a.dump();
}
}
</code></pre>
<p>Question: Is this true? Are there other occasions besides setters where self is necessary? I.e., are there other occasions where a Ruby method <em>cannot</em> be invoked <em>without</em> self?</p>
<p>There are certainly lots of cases where self <em>becomes</em> necessary. This is not unique to Ruby, just to be clear:</p>
<pre><code>using System;
public class A {
public A() {}
public int test { get { return 4; }}
public int useVariable() {
int test = 5;
return test;
}
public int useMethod() {
int test = 5;
return this.test;
}
}
public class Test {
public static void Main() {
A a = new A();
Console.WriteLine("{0}", a.useVariable()); // prints 5
Console.WriteLine("{0}", a.useMethod()); // prints 4
}
}
</code></pre>
<p>Same ambiguity is resolved in same way. But while subtle I'm asking about the case where </p>
<ul>
<li>A method <em>has</em> been defined, and</li>
<li><em>No</em> local variable has been defined, and</li>
</ul>
<p>we encounter</p>
<pre><code>qwerty = 4
</code></pre>
<p>which is ambiguous—is this a method invocation or an new local variable assignment?</p>
<hr>
<p>@Mike Stone</p>
<p>Hi! I understand and appreciate the points you've made and your
example was great. Believe me when I say, if I had enough reputation,
I'd vote up your response. Yet we still disagree: </p>
<ul>
<li>on a matter of semantics, and</li>
<li>on a central point of fact</li>
</ul>
<p>First I claim, not without irony, we're having a semantic debate about the
meaning of 'ambiguity'.</p>
<p>When it comes to parsing and programming language semantics (the subject
of this question), surely you would admit a broad spectrum of the notion
'ambiguity'. Let's just adopt some random notation: </p>
<ol>
<li>ambiguous: lexical ambiguity (lex must 'look ahead')</li>
<li>Ambiguous: grammatical ambiguity (yacc must defer to parse-tree analysis)</li>
<li>AMBIGUOUS: ambiguity knowing everything at the moment of execution</li>
</ol>
<p>(and there's junk between 2-3 too). All these categories are resolved by
gathering more contextual info, looking more and more globally. So when you
say,</p>
<blockquote>
<p>"qwerty = 4" is UNAMBIGUOUS in C#
when there is no variable defined...</p>
</blockquote>
<p>I couldn't agree more. But by the same token, I'm saying </p>
<blockquote>
<p>"qwerty = 4" is un-Ambiguous in ruby
(as it now exists)</p>
<p>"qwerty = 4" is Ambiguous in C#</p>
</blockquote>
<p>And we're not yet contradicting each other. Finally, here's where we really
disagree: Either ruby could or could not be implemented without any further
language constructs such that,</p>
<blockquote>
<p>For "qwerty = 4," ruby UNAMBIGUOUSLY
invokes an existing setter if there<br>
is no local variable defined</p>
</blockquote>
<p>You say no. I say yes; another ruby could exist which behaves exactly like
the current in every respect, <em>except</em> "qwerty = 4" defines a new
variable when no setter and no local exists, it invokes the setter if one
exists, and it assigns to the local if one exists. I fully accept that I
could be wrong. In fact, a reason why I might be wrong would be interesting.</p>
<p>Let me explain.</p>
<p>Imagine you are writing a new OO language with accessor methods looking
like instances vars (like ruby & C#). You'd probably start with
conceptual grammars something like:</p>
<pre><code> var = expr // assignment
method = expr // setter method invocation
</code></pre>
<p>But the parser-compiler (not even the runtime) will puke, because even after
all the input is grokked there's no way to know which grammar is pertinent.
You're faced which a classic choice. I can't be sure of the details, but
basically ruby does this:</p>
<pre><code> var = expr // assignment (new or existing)
// method = expr, disallow setter method invocation without .
</code></pre>
<p>that is why it's un-Ambiguous, while and C# does this:</p>
<pre><code> symbol = expr // push 'symbol=' onto parse tree and decide later
// if local variable is def'd somewhere in scope: assignment
// else if a setter is def'd in scope: invocation
</code></pre>
<p>For C#, 'later' is still at compile time.</p>
<p>I'm sure ruby could do the same, but 'later' would have to be at runtime, because
as ben points out you don't know until the statement is executed which case
applies.</p>
<p>My question was never intended to mean "do I really need the 'self.'?" or "what
potential ambiguity is being avoided?" Rather I wanted to know why was this
particular choice made? Maybe it's not performance. Maybe it just got the job
done, or it was considered best to always allow a 1-liner local to override a
method (a pretty rare case requirement) ...</p>
<p>But I'm sort of suggesting that the most dynamical language might be the one which
postpones this decision the longest, and chooses semantics based on the most contextual
info: so if you have no local and you defined a setter, it would use the setter. Isn't
this why we like ruby, smalltalk, objc, because method invocation is decided at runtime,
offering maximum expressiveness?</p>
|
[
{
"answer_id": 44779,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 6,
"selected": false,
"text": "qwerty = 4 qwerty self. self. class A\n def test\n 4\n end\n def use_variable\n test = 5\n test\n end\n def use_method\n test = 5\n self.test\n end\nend\na = A.new\na.use_variable # returns 5\na.use_method # returns 4\n test self. this."
},
{
"answer_id": 23448046,
"author": "Ajedi32",
"author_id": 1157054,
"author_profile": "https://Stackoverflow.com/users/1157054",
"pm_score": 4,
"selected": false,
"text": "variable = some_value class ExampleClass\n attr_reader :last_set\n def method_missing(name, *args)\n if name.to_s =~ /=$/\n @last_set = args.first\n else\n super\n end\n end\n\n def some_method\n some_variable = 5 # Set a local variable? Or call method_missing?\n puts some_variable\n end\nend\n self some_method NameError: undefined local variable or method 'some_variable' example = ExampleClass.new\nexample.blah = 'Some text'\nexample.last_set #=> \"Some text\"\nexample.some_method # prints \"5\"\nexample.last_set #=> \"Some text\"\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4615/"
] |
44,757 |
<p>I heard on a recent podcast (Polymorphic) that it is possible to cache a user control as opposed to the entire page. </p>
<p>I think my header control which displays static content and my footer control could benefit from being cached. </p>
<p>How can I go about caching just those controls?</p>
|
[
{
"answer_id": 44770,
"author": "Mike",
"author_id": 4523,
"author_profile": "https://Stackoverflow.com/users/4523",
"pm_score": 3,
"selected": true,
"text": "VaryByParam VaryByControl"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/648/"
] |
44,771 |
<p>Ok, so my method in my webservice requires a type to be passed, it is called in the ServiceMethod property of the AutoCompleteExtender, I am fuzzy about how I should do that so I called it like this:</p>
<pre><code>ServiceMethod="DropDownLoad<<%=(typeof)subCategory%>>"
</code></pre>
<p>where subCategory is a page property that looks like this:</p>
<pre><code>protected SubCategory subCategory
{
get
{
var subCategory = NHibernateObjectHelper.LoadDataObject<SubCategory>(Convert.ToInt32(Request.QueryString["SCID"]));
return subCategory;
}
}
</code></pre>
|
[
{
"answer_id": 44923,
"author": "bentford",
"author_id": 946,
"author_profile": "https://Stackoverflow.com/users/946",
"pm_score": 2,
"selected": true,
"text": "[WebMethod]\npublic string[] GetSearchList(string prefixText, int count)\n{\n}\n\n[WebMethod]\npublic string[] GetSearchList2<T>(string prefixText, int count)\n{\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4140/"
] |
44,777 |
<p>I'm sending mail from my C# Application, using the SmtpClient. Works great, but I have to decide if I want to send the mail as Plain Text or HTML. I wonder, is there a way to send both? I think that's called multipart.</p>
<p>I googled a bit, but most examples essentially did not use SmtpClient but composed the whole SMTP-Body themselves, which is a bit "scary", so I wonder if something is built in the .net Framework 3.0?</p>
<p>If not, is there any really well used/robust Third Party Library for sending e-Mails?</p>
|
[
{
"answer_id": 44877,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 6,
"selected": false,
"text": "MailMessage msg = new MailMessage(username, nu.email, subject, body);\nmsg.BodyEncoding = Encoding.UTF8;\nmsg.SubjectEncoding = Encoding.UTF8;\n\nAlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlContent);\nhtmlView.ContentType = new System.Net.Mime.ContentType(\"text/html\");\nmsg.AlternateViews.Add(htmlView);\n"
},
{
"answer_id": 1323191,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "MediaTypeNames.Text.Html MediaTypeNames.Text.Plain \"text/html\" \"text/plain\" System.Net.Mime AlternateView htmlView = AlternateView.CreateAlternateViewFromString(htmlContent, null, MediaTypeNames.Text.Html);\n"
},
{
"answer_id": 38023731,
"author": "user1852503",
"author_id": 1852503,
"author_profile": "https://Stackoverflow.com/users/1852503",
"pm_score": 3,
"selected": false,
"text": "// do not do this: \nvar msg = new MailMessage(model.From, model.To);\nmsg.Body = compiledHtml; \n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44777",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
44,778 |
<p>What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, <code>['a', 'b', 'c']</code> to <code>'a,b,c'</code>? (The cases <code>['s']</code> and <code>[]</code> should be mapped to <code>'s'</code> and <code>''</code>, respectively.)</p>
<p>I usually end up using something like <code>''.join(map(lambda x: x+',',l))[:-1]</code>, but also feeling somewhat unsatisfied.</p>
|
[
{
"answer_id": 44781,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 11,
"selected": true,
"text": "my_list = ['a', 'b', 'c', 'd']\nmy_string = ','.join(my_list)\n 'a,b,c,d'\n my_string = ','.join(map(str, my_list)) \n"
},
{
"answer_id": 44788,
"author": "jmanning2k",
"author_id": 1480,
"author_profile": "https://Stackoverflow.com/users/1480",
"pm_score": 6,
"selected": false,
"text": "map lambda >>> foo = ['a', 'b', 'c']\n>>> print(','.join(foo))\na,b,c\n>>> print(','.join([]))\n\n>>> print(','.join(['a']))\na\n >>> ','.join([str(x) for x in foo])\n >>> ','.join(str(x) for x in foo)\n"
},
{
"answer_id": 44791,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 4,
"selected": false,
"text": "\",\".join(l)\n"
},
{
"answer_id": 44794,
"author": "David Singer",
"author_id": 4618,
"author_profile": "https://Stackoverflow.com/users/4618",
"pm_score": 1,
"selected": false,
"text": "','.join(foo) >>> ','.join([''])\n''\n>>> ','.join(['s'])\n's'\n>>> ','.join(['a','b','c'])\n'a,b,c'\n ','.join([str(x) for x in foo])\n csv"
},
{
"answer_id": 44878,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 3,
"selected": false,
"text": "from itertools import imap\nl = [1, \"foo\", 4 ,\"bar\"]\n\",\".join(imap(str, l))\n"
},
{
"answer_id": 46233,
"author": "Aaron Maenpaa",
"author_id": 2603,
"author_profile": "https://Stackoverflow.com/users/2603",
"pm_score": 4,
"selected": false,
"text": ">>> l = [1, \"foo\", 4 ,\"bar\"]\n>>> \",\".join(str(bit) for bit in l)\n'1,foo,4,bar' \n"
},
{
"answer_id": 65255,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "l=['a', 1, 'b', 2]\n\nprint str(l)[1:-1]\n\nOutput: \"'a', 1, 'b', 2\"\n"
},
{
"answer_id": 156851,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 4,
"selected": false,
"text": ">>> alist = ['a', 1, (2, 'b')]\n >>> \", \".join(map(str, alist))\n\"a, 1, (2, 'b')\"\n >>> import io\n>>> s = io.StringIO()\n>>> print(*alist, file=s, sep=', ', end='')\n>>> s.getvalue()\n\"a, 1, (2, 'b')\"\n"
},
{
"answer_id": 35319592,
"author": "Ricky Sahu",
"author_id": 1484447,
"author_profile": "https://Stackoverflow.com/users/1484447",
"pm_score": 5,
"selected": false,
"text": "\",\".join(l) import StringIO\nimport csv\n\nl = ['list','of','[\"\"\"crazy\"quotes\"and\\'',123,'other things']\n\nline = StringIO.StringIO()\nwriter = csv.writer(line)\nwriter.writerow(l)\ncsvcontent = line.getvalue()\n# 'list,of,\"[\"\"\"\"\"\"crazy\"\"quotes\"\"and\\'\",123,other things\\r\\n'\n"
},
{
"answer_id": 43978261,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": ">>> myList = [['Apple'],['Orange']]\n>>> myList = ','.join(map(str, [i[0] for i in myList])) \n>>> print \"Output:\", myList\nOutput: Apple,Orange\n >>> myList = [['Apple'],['Orange']]\n>>> myList = ','.join(map(str, [type(i) == list and i[0] for i in myList])) \n>>> print \"Output:\", myList\nOutput: Apple,Orange\n myList = ['Apple','Orange']\nmyList = ','.join(map(str, myList)) \nprint \"Output:\", myList\nOutput: Apple,Orange\n"
},
{
"answer_id": 44085343,
"author": "Shameem",
"author_id": 6690588,
"author_profile": "https://Stackoverflow.com/users/6690588",
"pm_score": 3,
"selected": false,
"text": ">>> my_list = ['A', '', '', 'D', 'E',]\n>>> \",\".join([str(i) for i in my_list if i])\n'A,D,E'\n my_list 'A,,,D,E'"
},
{
"answer_id": 48137821,
"author": "Roberto",
"author_id": 5548995,
"author_profile": "https://Stackoverflow.com/users/5548995",
"pm_score": -1,
"selected": false,
"text": ">>> from itertools import imap, ifilter\n>>> l = ['a', '', 'b', 1, None]\n>>> ','.join(imap(str, ifilter(lambda x: x, l)))\na,b,1\n>>> m = ['a', '', None]\n>>> ','.join(imap(str, ifilter(lambda x: x, m)))\n'a'\n >>> ','.join(ifilter(lambda x: x, l))\n"
},
{
"answer_id": 50912527,
"author": "Ron Kalian",
"author_id": 7134286,
"author_profile": "https://Stackoverflow.com/users/7134286",
"pm_score": 1,
"selected": false,
"text": "csv l import csv\nwith open('some.csv', 'w', newline='') as f:\n writer = csv.writer(f)\n writer.writerow(l) # this will output l as a single row. \n writer.writerows(iterable) StringIO"
},
{
"answer_id": 62599395,
"author": "faiz-e",
"author_id": 10014426,
"author_profile": "https://Stackoverflow.com/users/10014426",
"pm_score": 2,
"selected": false,
"text": "','.join([str(word) for word in wordList])\n wordList = ['USD', 'EUR', 'JPY', 'NZD', 'CHF', 'CAD']\nstringText = ''\n\nfor word in wordList:\n stringText += word + ','\n\nstringText = stringText[:-2] # get rid of last comma\nprint(stringText)\n"
},
{
"answer_id": 70126183,
"author": "Cristián Vargas Acevedo",
"author_id": 4450951,
"author_profile": "https://Stackoverflow.com/users/4450951",
"pm_score": 0,
"selected": false,
"text": "l = [\"foo\" , \"baar\" , 6]\nwhere_clause = \"..... IN (\"+(','.join([ f\"'{x}'\" for x in l]))+\")\"\n>> \"..... IN ('foo','baar','6')\"\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4285/"
] |
44,780 |
<p>What's the best way to implement a SQL script that will grant select, references, insert, update, and delete permissions to a database role on all the user tables in a database?</p>
<p>Ideally, this script could be run multiple times, as new tables were added to the database. SQL Server Management Studio generates scripts for individual database objects, but I'm looking for more of a "fire-and-forget" script.</p>
|
[
{
"answer_id": 45907,
"author": "ninesided",
"author_id": 1030,
"author_profile": "https://Stackoverflow.com/users/1030",
"pm_score": 2,
"selected": true,
"text": " IF EXISTS (\n SELECT 1 FROM sysobjects\n WHERE name = 'sp_grantastic'\n AND type = 'P'\n)\nDROP PROCEDURE sp_grantastic\nGO\nCREATE PROCEDURE sp_grantastic\nAS\nDECLARE\n @object_name VARCHAR(30)\n,@time VARCHAR(8)\n,@rights VARCHAR(20)\n,@role VARCHAR(20)\n\nDECLARE c_objects CURSOR FOR\n SELECT name\n FROM sysobjects\n WHERE type IN ('P', 'U', 'V')\n FOR READ ONLY\n\nBEGIN\n\n SELECT @rights = 'ALL'\n ,@role = 'PUBLIC'\n\n OPEN c_objects\n WHILE (1=1)\n BEGIN\n FETCH c_objects INTO @object_name\n IF @@SQLSTATUS <> 0 BREAK\n\n SELECT @time = CONVERT(VARCHAR, GetDate(), 108)\n PRINT '[%1!] hitting up object %2!', @time, @object_name\n EXECUTE('GRANT '+ @rights +' ON '+ @object_name+' TO '+@role)\n\n END\n\n PRINT '[%1!] fin!', @time\n\n CLOSE c_objects\n DEALLOCATE CURSOR c_objects\nEND\nGO\nGRANT ALL ON sp_grantastic TO PUBLIC\nGO\n EXEC sp_grantastic\n"
},
{
"answer_id": 45920,
"author": "Pascal Paradis",
"author_id": 1291,
"author_profile": "https://Stackoverflow.com/users/1291",
"pm_score": 0,
"selected": false,
"text": "CREATE PROCEDURE dbo.SP_GrantFullAccess \n @username varchar(300)\nAS\n\nDECLARE @on varchar(300) \nDECLARE @count int\nSET @count = 0\n\nPRINT 'Granting access to user ' + @username + ' on the following objects:'\n\nDECLARE c CURSOR FOR \nSELECT name FROM sysobjects WHERE type IN('U', 'V', 'SP', 'P') ORDER BY name\nOPEN c \nFETCH NEXT FROM c INTO @on \nWHILE @@FETCH_STATUS = 0 \nBEGIN \n SET @count = @count + 1\n EXEC('GRANT ALL ON [' + @on + '] TO [' + @username + ']') \n --PRINT 'GRANT ALL ON [' + @on + '] TO ' + @username\n PRINT @on\n FETCH NEXT FROM c INTO @on \nEND \nCLOSE c \nDEALLOCATE c\n\nPRINT 'Granted access to ' + cast(@count as varchar(4)) + ' object(s).'\nGO\n"
},
{
"answer_id": 52897,
"author": "Martynnw",
"author_id": 5466,
"author_profile": "https://Stackoverflow.com/users/5466",
"pm_score": 1,
"selected": false,
"text": "EXECUTE sp_MSforeachtable @command1=' Grant Select on ? to RoleName'\n EXECUTE sp_MSforeachtable @command1=' Grant Select on ? to RoleName; Grant Delete on ? to RoleName;'\n"
},
{
"answer_id": 1663058,
"author": "CSecord",
"author_id": 201157,
"author_profile": "https://Stackoverflow.com/users/201157",
"pm_score": 0,
"selected": false,
"text": "use [YourDb]\nGO\nexec sp_MSforeachtable @command1=\n \"GRANT DELETE, INSERT, REFERENCES, SELECT, UPDATE ON ? TO Admins, Mgmt\",\n @whereand = \" and o.name like 'tbl_%'\"\nGO\n\nuse [YourDb]\nGO\nexec sp_MSforeachtable @command1=\n \"GRANT REFERENCES, SELECT ON ? TO Employee, public\",\n @whereand = \" and o.name like 'tbl_%'\"\nGO\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3475/"
] |
44,787 |
<p>Scenario: You have an ASP.Net webpage that should display the next image in a series of images. If 1.jpg is currently loaded, the refresh should load 2.jpg.<br>
Assuming I would use this code, where do you get the current images name.</p>
<pre><code>string currImage = MainPic.ImageUrl.Replace(".jpg", "");
currImage = currImage.Replace("~/Images/", "");
int num = (Convert.ToInt32(currImage) + 1) % 3;
MainPic.ImageUrl = "~/Images/" + num.ToString() + ".jpg";
</code></pre>
<p>The problem with the above code is that the webpage used is the default site with the image set to 1.jpg, so the loaded image is always 2.jpg.<br>
So in the process of loading the page, is it possible to pull the last image used from the pages properties?</p>
|
[
{
"answer_id": 44804,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 3,
"selected": false,
"text": "ViewState var lastPicNum = (int)ViewState[\"lastPic\"];\nlastPicNum++;\n\nMainPic.ImageUrl = string.Format(\"~/Images/{0}.jpg\", lastPicNum);\n\nViewState[\"lastPic\"] = lastPicNum;\n"
},
{
"answer_id": 44810,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 4,
"selected": true,
"text": "int num = 1;\n\nif(Session[\"ImageNumber\"] != null)\n{\n num = Convert.ToInt32(Session[\"ImageNumber\"]) + 1;\n}\n\nSession[\"ImageNumber\"] = num;\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4298/"
] |
44,795 |
<p>I'm on .NET 2.0, running under Medium Trust (so <a href="http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx" rel="nofollow noreferrer">TimeZoneInfo</a> and the Registry are not allowed options). I'm asking the user for two dates and a time zone, and would really love to be able to automatically determine whether I need to adjust the time zone for DST. </p>
<p>This probably isn't even a valid scenario unless I have some <em>very</em> robust support, a la <a href="http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx" rel="nofollow noreferrer">TimeZoneInfo</a>, to differentiate between all of the different varieties of Time Zones in the first place.</p>
|
[
{
"answer_id": 44819,
"author": "Domenic",
"author_id": 3191,
"author_profile": "https://Stackoverflow.com/users/3191",
"pm_score": 0,
"selected": false,
"text": "TimeZoneInfo TimeZoneInfo"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2688/"
] |
44,799 |
<p>We're currently building an application that executes a number of external tools. We often have to pass information entered into our system by users to these tools.</p>
<p>Obviously, this is a big security nightmare waiting to happen.</p>
<p>Unfortunately, we've not yet found any classes in the .NET Framework that execute command line programs while providing the same kind of guards against injection attacks as the IDbCommand objects do for databases.</p>
<p>Right now, we're using a very primitive string substitution which I suspect is rather insufficient:</p>
<blockquote>
<pre><code>protected virtual string Escape(string value)
{
return value
.Replace(@"\", @"\\")
.Replace(@"$", @"\$")
.Replace(@"""", @"\""")
.Replace("`", "'")
;
}
</code></pre>
</blockquote>
<p>What do you guys do to prevent command-line injection attacks? We're planning to implement a regex that is very strict and only allows a very small subset of characters through, but I was wondering if there was a better way.</p>
<p>Some clarifications:</p>
<ul>
<li>Some of these tools do not have APIs we can program against. If they did, we wouldn't be having this problem.</li>
<li>The users don't pick tools to execute, they enter meta-data which the tools we've chosen use (for example, injecting meta data such as copyright notices into target files). </li>
</ul>
|
[
{
"answer_id": 48832,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 2,
"selected": false,
"text": "\n#include <iostream>\n#include <string>\n#include <windows.h>\n#include <cstdlib>\nusing namespace std;\n\n// Escape and quote string for use as Windows command line argument\nstring qEscape(const string& s) {\n string result(\"\\\"\");\n for (string::const_iterator i = s.begin(); i != s.end(); ++i) {\n const char c = *i;\n const string::const_iterator next = i + 1;\n if (c == '\"' || (c == '\\\\' && (next == s.end() || *next == '\"'))) {\n result += '\\\\';\n }\n result += c;\n }\n result += '\"';\n return result;\n}\n\nint main() {\n // Argument value to pass: c:\\program files\\test\\test.exe\n const string safe_program = qEscape(\"c:\\\\program files\\\\test\\\\test.exe\");\n cout << safe_program << \" \";\n\n // Argument value to pass: You're the \"best\" around.\n const string safe_arg0 = qEscape(\"You're the \\\"best\\\" around.\");\n\n // Argument value to pass: \"Nothing's\" gonna ever keep you down.\n const string safe_arg1 = qEscape(\"\\\"Nothing's\\\" gonna ever keep you down.\");\n\n const string safe_args = safe_arg0 + \" \" + safe_arg1;\n cout << safe_args << \"\\n\\n\";\n\n // c:\\program files\\test\\ to pass.\n const string bs_at_end_example = qEscape(\"c:\\\\program files\\\\test\\\\\");\n cout << bs_at_end_example << \"\\n\\n\";\n\n const int result = reinterpret_cast<int>(ShellExecute(NULL, \"open\", safe_program.c_str(), safe_args.c_str(), NULL, SW_SHOWNORMAL));\n if (result < 33) {\n cout << \"ShellExecute failed with Error code \" << result << \"\\n\";\n return EXIT_FAILURE;\n }\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
] |
44,803 |
<p>Scenario: Document library in SharePoint with column x of "Person or Group" type. From within a VBA macro (or VSTO add-in) we're trying to access the MetaProperty on the document to set/get the user name. Any attempt to access the value via the ContentTypeProperties collection throws a </p>
<blockquote>
<p>Type MisMatch error (13).</p>
</blockquote>
<p>The Type property of the MetaProperty object says it's <code>msoMetaPropertyTypeUser</code>. I cannot find any examples of how to work with MetaProperties of this type. Anyone have any experience with this?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 48832,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 2,
"selected": false,
"text": "\n#include <iostream>\n#include <string>\n#include <windows.h>\n#include <cstdlib>\nusing namespace std;\n\n// Escape and quote string for use as Windows command line argument\nstring qEscape(const string& s) {\n string result(\"\\\"\");\n for (string::const_iterator i = s.begin(); i != s.end(); ++i) {\n const char c = *i;\n const string::const_iterator next = i + 1;\n if (c == '\"' || (c == '\\\\' && (next == s.end() || *next == '\"'))) {\n result += '\\\\';\n }\n result += c;\n }\n result += '\"';\n return result;\n}\n\nint main() {\n // Argument value to pass: c:\\program files\\test\\test.exe\n const string safe_program = qEscape(\"c:\\\\program files\\\\test\\\\test.exe\");\n cout << safe_program << \" \";\n\n // Argument value to pass: You're the \"best\" around.\n const string safe_arg0 = qEscape(\"You're the \\\"best\\\" around.\");\n\n // Argument value to pass: \"Nothing's\" gonna ever keep you down.\n const string safe_arg1 = qEscape(\"\\\"Nothing's\\\" gonna ever keep you down.\");\n\n const string safe_args = safe_arg0 + \" \" + safe_arg1;\n cout << safe_args << \"\\n\\n\";\n\n // c:\\program files\\test\\ to pass.\n const string bs_at_end_example = qEscape(\"c:\\\\program files\\\\test\\\\\");\n cout << bs_at_end_example << \"\\n\\n\";\n\n const int result = reinterpret_cast<int>(ShellExecute(NULL, \"open\", safe_program.c_str(), safe_args.c_str(), NULL, SW_SHOWNORMAL));\n if (result < 33) {\n cout << \"ShellExecute failed with Error code \" << result << \"\\n\";\n return EXIT_FAILURE;\n }\n}\n"
}
] |
2008/09/04
|
[
"https://Stackoverflow.com/questions/44803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4544/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.