qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
191,351
<p>I am trying to rename all the files present in a Windows directory using <strong>FOR</strong> command as follows at the command prompt:</p> <pre><code>for %1 in (*.*) do ren %1 test%1 </code></pre> <p>E.g. This renames a file <strong>enc1.ctl</strong> to <strong>testenc1.ctl</strong> <strong>enc2.ctl</strong> to <strong>testenc2.ctl</strong> </p> <p>Thats not what i want. What i want is <strong>enc1.ctl</strong> renamed to <strong>test1.ctl</strong> <strong>enc2.ctl</strong> renamed to <strong>test2.ctl</strong> </p> <p>How do i do that?</p> <hr> <p>@Akelunuk: Thanks, that w kind of works but i have files names as </p> <p><strong>h263_enc_random_pixels_1.ctl , h263_enc_random_pixels_2.ctl</strong> which i want to rename to</p> <p><strong>test1.ctl and test2.ctl</strong> respectively </p> <p>Then how?</p>
[ { "answer_id": 191420, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 2, "selected": true, "text": "<p>If you know the number of files, (say 10), you can use</p>\n\n<pre><code>for /L %1 in (1,1,10) do ren enc%1.ctl test%1.ctl\n</code></pre>\n" }, { "answer_id": 191451, "author": "akalenuk", "author_id": 25459, "author_profile": "https://Stackoverflow.com/users/25459", "pm_score": 2, "selected": false, "text": "<p>I've got it! </p>\n\n<pre><code>for %1 in (.) do ren %1 t%1\n</code></pre>\n\n<p>and then:</p>\n\n<pre><code>ren tenc*.* test*.*\n</code></pre>\n" }, { "answer_id": 191620, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "<p>I am not sure if it is possible in batch, but then again I never mastered this primitive language... :-P</p>\n\n<p>If CMD isn't mandatory, but you can't use a good file renamer, you can do that with WSH:</p>\n\n<pre><code>var path= \"E:/tmp\";\n\nvar fso = WScript.CreateObject(\"Scripting.FileSystemObject\");\nvar folder = fso.GetFolder(path);\nvar files = new Enumerator(folder.files);\nfor (; !files.atEnd(); files.moveNext())\n{\n var file = files.item();\n var fileName = file.Name;\n var p = /^enc(\\d+)\\.ctl$/.exec(fileName);\n if (p != null)\n {\n var newFileName = \"test\" + p[1] + \".ctl\";\n // Optional feedback\n WScript.echo(fileName + \" -----&gt; \" + newFileName);\n file.Move(newFileName);\n }\n}\n</code></pre>\n\n<p>Of course, put that in a file.js<br>\nI actually tested with <code>file.Copy(file.ParentFolder + \"/SO/\" + newFileName);</code> to avoid loosing files...</p>\n\n<p>HTH.</p>\n" }, { "answer_id": 39759575, "author": "Yousef Rabby RJ", "author_id": 6896699, "author_profile": "https://Stackoverflow.com/users/6896699", "pm_score": 0, "selected": false, "text": "<p>This renames all files in directory for filter file types with PREFIX and today's date and time</p>\n\n<pre><code>@echo ON\ncls\nfor %%a in (*.pdf) do (set myfiledate=%%~ta echo !myfiledate!)\n\necho Date format = %myfiledate%\necho dd = %myfiledate:~0,2%\necho mm = %myfiledate:~3,2%\necho yyyy = %myfiledate:~6,4%\necho.\necho Time format = %myfiledate%\necho hh = %myfiledate:~11,2%\necho mm = %myfiledate:~14,2%\necho AM = %myfiledate:~17,2%\necho.\necho Timestamp = %myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%\nECHO \"TEST...\" &gt; \"test-%myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-TIME-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%.txt\"\nPAUSE\n</code></pre>\n\n<p>This echos successfuly the date modified and time as a postfix but doesnt parse the info into the rename. I cant figure out why, but it is very close. Maybe someone cant tweak to suit your purpose.</p>\n\n<pre><code>@echo ON\nsetlocal\ncls\nfor %%a in (*.pdf) do (set myfiledate=%%~ta echo !myfiledate!)\n\n:DATETIME\necho Date format = %myfiledate%\necho dd = %myfiledate:~0,2%\necho mm = %myfiledate:~3,2%\necho yyyy = %myfiledate:~6,4%\n\necho Time format = %myfiledate%\necho hh = %myfiledate:~11,2%\necho mm = %myfiledate:~14,2%\necho AM = %myfiledate:~17,2%\n = %myfiledate:~17,2%\necho.\n\necho Timestamp = %myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%\nECHO \"TEST...\" &gt; \"test-%myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-TIME-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%.txt\"\n\nfor /f \"delims=\" %%a in ('dir *.pdf /t:a /a:-d /b /s') do call :RENAME \"%%a\"\n\n:RENAME\nREM for /f \"tokens=1-6 delims=/ \" %%a in ('dir %%a /t:w^|find \"/\"') do (\nren %%a \"3DC-test-OFF-ELE-%myfiledate:~0,2%_%myfiledate:~3,2%_%myfiledate:~6,4%-TIME-%myfiledate:~11,2%_%myfiledate:~14,2%_%myfiledate:~17,2%~x1\")\nPAUSE\nGOTO :EOF\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191351", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2759376/" ]
I am trying to rename all the files present in a Windows directory using **FOR** command as follows at the command prompt: ``` for %1 in (*.*) do ren %1 test%1 ``` E.g. This renames a file **enc1.ctl** to **testenc1.ctl** **enc2.ctl** to **testenc2.ctl** Thats not what i want. What i want is **enc1.ctl** renamed to **test1.ctl** **enc2.ctl** renamed to **test2.ctl** How do i do that? --- @Akelunuk: Thanks, that w kind of works but i have files names as **h263\_enc\_random\_pixels\_1.ctl , h263\_enc\_random\_pixels\_2.ctl** which i want to rename to **test1.ctl and test2.ctl** respectively Then how?
If you know the number of files, (say 10), you can use ``` for /L %1 in (1,1,10) do ren enc%1.ctl test%1.ctl ```
191,359
<p>I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part.</p> <p>I'd like to do the equivalent of:</p> <pre><code>iconv -t utf-8 $file &gt; converted/$file # this is shell code </code></pre> <p>Thanks!</p>
[ { "answer_id": 191403, "author": "DzinX", "author_id": 18745, "author_profile": "https://Stackoverflow.com/users/18745", "pm_score": 7, "selected": true, "text": "<p>You can use the <a href=\"https://docs.python.org/2/library/codecs.html\" rel=\"noreferrer\">codecs module</a>, like this:</p>\n\n<pre><code>import codecs\nBLOCKSIZE = 1048576 # or some other, desired size in bytes\nwith codecs.open(sourceFileName, \"r\", \"your-source-encoding\") as sourceFile:\n with codecs.open(targetFileName, \"w\", \"utf-8\") as targetFile:\n while True:\n contents = sourceFile.read(BLOCKSIZE)\n if not contents:\n break\n targetFile.write(contents)\n</code></pre>\n\n<p><strong>EDIT</strong>: added <code>BLOCKSIZE</code> parameter to control file chunk size.</p>\n" }, { "answer_id": 191455, "author": "Staale", "author_id": 3355, "author_profile": "https://Stackoverflow.com/users/3355", "pm_score": 5, "selected": false, "text": "<p>This worked for me in a small test:</p>\n\n<pre><code>sourceEncoding = \"iso-8859-1\"\ntargetEncoding = \"utf-8\"\nsource = open(\"source\")\ntarget = open(\"target\", \"w\")\n\ntarget.write(unicode(source.read(), sourceEncoding).encode(targetEncoding))\n</code></pre>\n" }, { "answer_id": 192086, "author": "Sébastien RoccaSerra", "author_id": 2797, "author_profile": "https://Stackoverflow.com/users/2797", "pm_score": 4, "selected": false, "text": "<p>Thanks for the replies, it works!</p>\n\n<p>And since the source files are in mixed formats, I added a list of source formats to be tried in sequence (<code>sourceFormats</code>), and on <code>UnicodeDecodeError</code> I try the next format:</p>\n\n<pre><code>from __future__ import with_statement\n\nimport os\nimport sys\nimport codecs\nfrom chardet.universaldetector import UniversalDetector\n\ntargetFormat = 'utf-8'\noutputDir = 'converted'\ndetector = UniversalDetector()\n\ndef get_encoding_type(current_file):\n detector.reset()\n for line in file(current_file):\n detector.feed(line)\n if detector.done: break\n detector.close()\n return detector.result['encoding']\n\ndef convertFileBestGuess(filename):\n sourceFormats = ['ascii', 'iso-8859-1']\n for format in sourceFormats:\n try:\n with codecs.open(fileName, 'rU', format) as sourceFile:\n writeConversion(sourceFile)\n print('Done.')\n return\n except UnicodeDecodeError:\n pass\n\ndef convertFileWithDetection(fileName):\n print(\"Converting '\" + fileName + \"'...\")\n format=get_encoding_type(fileName)\n try:\n with codecs.open(fileName, 'rU', format) as sourceFile:\n writeConversion(sourceFile)\n print('Done.')\n return\n except UnicodeDecodeError:\n pass\n\n print(\"Error: failed to convert '\" + fileName + \"'.\")\n\n\ndef writeConversion(file):\n with codecs.open(outputDir + '/' + fileName, 'w', targetFormat) as targetFile:\n for line in file:\n targetFile.write(line)\n\n# Off topic: get the file list and call convertFile on each file\n# ...\n</code></pre>\n\n<p>(EDIT by Rudro Badhon: this incorporates the original try multiple formats until you don't get an exception as well as an alternate approach that uses chardet.universaldetector)</p>\n" }, { "answer_id": 9200298, "author": "Ricardo", "author_id": 583064, "author_profile": "https://Stackoverflow.com/users/583064", "pm_score": 2, "selected": false, "text": "<p>To guess what's the source encoding you can use the <code>file</code> *nix command.</p>\n\n<p>Example:</p>\n\n<pre><code>$ file --mime jumper.xml\n\njumper.xml: application/xml; charset=utf-8\n</code></pre>\n" }, { "answer_id": 41535910, "author": "MojiProg", "author_id": 3454902, "author_profile": "https://Stackoverflow.com/users/3454902", "pm_score": 2, "selected": false, "text": "<p>This is a <strong>Python3</strong> function for converting any text file into the one with UTF-8 encoding. (without using unnecessary packages)</p>\n\n<pre><code>def correctSubtitleEncoding(filename, newFilename, encoding_from, encoding_to='UTF-8'):\n with open(filename, 'r', encoding=encoding_from) as fr:\n with open(newFilename, 'w', encoding=encoding_to) as fw:\n for line in fr:\n fw.write(line[:-1]+'\\r\\n')\n</code></pre>\n\n<p>You can use it easily in a loop to convert a list of files.</p>\n" }, { "answer_id": 53553157, "author": "DEX Data Explorers", "author_id": 10726534, "author_profile": "https://Stackoverflow.com/users/10726534", "pm_score": 0, "selected": false, "text": "<p>This is my brute force method. It also takes care of mingled \\n and \\r\\n in the input.</p>\n\n<pre><code> # open the CSV file\n inputfile = open(filelocation, 'rb')\n outputfile = open(outputfilelocation, 'w', encoding='utf-8')\n for line in inputfile:\n if line[-2:] == b'\\r\\n' or line[-2:] == b'\\n\\r':\n output = line[:-2].decode('utf-8', 'replace') + '\\n'\n elif line[-1:] == b'\\r' or line[-1:] == b'\\n':\n output = line[:-1].decode('utf-8', 'replace') + '\\n'\n else:\n output = line.decode('utf-8', 'replace') + '\\n'\n outputfile.write(output)\n outputfile.close()\nexcept BaseException as error:\n cfg.log(self.outf, \"Error(18): opening CSV-file \" + filelocation + \" failed: \" + str(error))\n self.loadedwitherrors = 1\n return ([])\ntry:\n # open the CSV-file of this source table\n csvreader = csv.reader(open(outputfilelocation, \"rU\"), delimiter=delimitervalue, quoting=quotevalue, dialect=csv.excel_tab)\nexcept BaseException as error:\n cfg.log(self.outf, \"Error(19): reading CSV-file \" + filelocation + \" failed: \" + str(error))\n</code></pre>\n" }, { "answer_id": 53851783, "author": "Sole Sensei", "author_id": 9026554, "author_profile": "https://Stackoverflow.com/users/9026554", "pm_score": 4, "selected": false, "text": "<p>Answer for <strong>unknown source encoding type</strong></p>\n\n<p>based on <a href=\"https://stackoverflow.com/a/192086/9026554\">@Sébastien RoccaSerra</a></p>\n\n<p><strong>python3.6</strong></p>\n\n<pre><code>import os \nfrom chardet import detect\n\n# get file encoding type\ndef get_encoding_type(file):\n with open(file, 'rb') as f:\n rawdata = f.read()\n return detect(rawdata)['encoding']\n\nfrom_codec = get_encoding_type(srcfile)\n\n# add try: except block for reliability\ntry: \n with open(srcfile, 'r', encoding=from_codec) as f, open(trgfile, 'w', encoding='utf-8') as e:\n text = f.read() # for small files, for big use chunks\n e.write(text)\n\n os.remove(srcfile) # remove old encoding file\n os.rename(trgfile, srcfile) # rename new encoding\nexcept UnicodeDecodeError:\n print('Decode Error')\nexcept UnicodeEncodeError:\n print('Encode Error')\n</code></pre>\n" }, { "answer_id": 67268768, "author": "Cesc", "author_id": 7535684, "author_profile": "https://Stackoverflow.com/users/7535684", "pm_score": 3, "selected": false, "text": "<p>You can use this <em>one liner</em> (assuming you want to convert from <em>utf16</em> to <em>utf8</em>)</p>\n<pre><code> python -c &quot;from pathlib import Path; path = Path('yourfile.txt') ; path.write_text(path.read_text(encoding='utf16'), encoding='utf8')&quot;\n</code></pre>\n<p>Where <code>yourfile.txt</code> is a path to your <em>$file</em>.</p>\n<p>For this to work you need <em>python 3.4</em> or newer (probably nowadays you do).</p>\n<p>Below a more readable version of the code above</p>\n<pre class=\"lang-py prettyprint-override\"><code>from pathlib import Path\npath = Path(&quot;yourfile.txt&quot;)\npath.write_text(path.read_text(encoding=&quot;utf16&quot;), encoding=&quot;utf8&quot;)\n</code></pre>\n" }, { "answer_id": 70404526, "author": "jamlee", "author_id": 4268594, "author_profile": "https://Stackoverflow.com/users/4268594", "pm_score": 0, "selected": false, "text": "<p>convert all file in a dir to utf-8 encode. it is recursive and can filter file by suffix. thanks @Sole Sensei</p>\n<pre><code># pip install -i https://pypi.tuna.tsinghua.edu.cn/simple chardet\nimport os\nimport re\nfrom chardet import detect\n\n\ndef get_file_list(d):\n result = []\n for root, dirs, files in os.walk(d):\n dirs[:] = [d for d in dirs if d not in ['venv', 'cmake-build-debug']]\n for filename in files:\n # your filter\n if re.search(r'(\\.c|\\.cpp|\\.h|\\.txt)$', filename):\n result.append(os.path.join(root, filename))\n return result\n\n\n# get file encoding type\ndef get_encoding_type(file):\n with open(file, 'rb') as f:\n raw_data = f.read()\n return detect(raw_data)['encoding']\n\n\nif __name__ == &quot;__main__&quot;:\n file_list = get_file_list('.')\n for src_file in file_list:\n print(src_file)\n trg_file = src_file + '.swp'\n from_codec = get_encoding_type(src_file)\n try:\n with open(src_file, 'r', encoding=from_codec) as f, open(trg_file, 'w', encoding='utf-8') as e:\n text = f.read()\n e.write(text)\n os.remove(src_file)\n os.rename(trg_file, src_file)\n except UnicodeDecodeError:\n print('Decode Error')\n except UnicodeEncodeError:\n print('Encode Error')\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2797/" ]
I need to convert a bunch of files to utf-8 in Python, and I have trouble with the "converting the file" part. I'd like to do the equivalent of: ``` iconv -t utf-8 $file > converted/$file # this is shell code ``` Thanks!
You can use the [codecs module](https://docs.python.org/2/library/codecs.html), like this: ``` import codecs BLOCKSIZE = 1048576 # or some other, desired size in bytes with codecs.open(sourceFileName, "r", "your-source-encoding") as sourceFile: with codecs.open(targetFileName, "w", "utf-8") as targetFile: while True: contents = sourceFile.read(BLOCKSIZE) if not contents: break targetFile.write(contents) ``` **EDIT**: added `BLOCKSIZE` parameter to control file chunk size.
191,364
<p>Trying to debug an issue with a server and my only log file is a 20GB log file (with no timestamps even! Why do people use <code>System.out.println()</code> as logging? In production?!)</p> <p>Using grep, I've found an area of the file that I'd like to take a look at, line 347340107.</p> <p>Other than doing something like</p> <pre><code>head -&lt;$LINENUM + 10&gt; filename | tail -20 </code></pre> <p>... which would require <code>head</code> to read through the first 347 million lines of the log file, is there a quick and easy command that would dump lines 347340100 - 347340200 (for example) to the console?</p> <p><strong>update</strong> I totally forgot that grep can print the context around a match ... this works well. Thanks!</p>
[ { "answer_id": 191385, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "<p>with GNU-grep you could just say </p>\n\n<pre>grep --context=10 ...</pre>\n" }, { "answer_id": 191397, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 5, "selected": false, "text": "<p>What about:</p>\n\n<pre><code>tail -n +347340107 filename | head -n 100\n</code></pre>\n\n<p>I didn't test it, but I think that would work.</p>\n" }, { "answer_id": 191440, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 2, "selected": false, "text": "<p>With <code>sed -e '1,N d; M q'</code> you'll print lines N+1 through M. This is probably a bit better then <code>grep -C</code> as it doesn't try to match lines to a pattern.</p>\n" }, { "answer_id": 191449, "author": "Sklivvz", "author_id": 7028, "author_profile": "https://Stackoverflow.com/users/7028", "pm_score": 9, "selected": false, "text": "<p>I found two other <a href=\"http://www.unix.com/unix-dummies-questions-answers/21027-how-do-you-specific-lines-file.html\" rel=\"noreferrer\">solutions</a> if you know the line number but nothing else (no grep possible):</p>\n<p>Assuming you need lines 20 to 40,</p>\n<pre><code>sed -n '20,40p;41q' file_name\n</code></pre>\n<p>or</p>\n<pre><code>awk 'FNR&gt;=20 &amp;&amp; FNR&lt;=40' file_name\n</code></pre>\n<p>When using <code>sed</code> it is more efficient to quit processing after having printed the last line than continue processing until the end of the file. This is especially important in the case of large files and printing lines at the beginning. In order to do so, the <code>sed</code> command above introduces the instruction <code>41q</code> in order to stop processing after line 41 because in the example we are interested in lines 20-40 only. You will need to change the 41 to whatever the last line you are interested in is, plus one.</p>\n" }, { "answer_id": 191797, "author": "Luka Marinko", "author_id": 19814, "author_profile": "https://Stackoverflow.com/users/19814", "pm_score": 4, "selected": false, "text": "<p>I'd first split the file into few smaller ones like this</p>\n\n<pre><code>$ split --lines=50000 /path/to/large/file /path/to/output/file/prefix\n</code></pre>\n\n<p>and then grep on the resulting files.</p>\n" }, { "answer_id": 204790, "author": "unwind", "author_id": 28169, "author_profile": "https://Stackoverflow.com/users/28169", "pm_score": 5, "selected": false, "text": "<p>No there isn't, files are not line-addressable.</p>\n\n<p>There is no constant-time way to find the start of line <em>n</em> in a text file. You must stream through the file and count newlines.</p>\n\n<p>Use the simplest/fastest tool you have to do the job. To me, using <code>head</code> makes <em>much</em> more sense than <code>grep</code>, since the latter is way more complicated. I'm not saying \"<code>grep</code> is slow\", it really isn't, but I would be surprised if it's faster than <code>head</code> for this case. That'd be a bug in <code>head</code>, basically.</p>\n" }, { "answer_id": 17367226, "author": "WCC", "author_id": 1102552, "author_profile": "https://Stackoverflow.com/users/1102552", "pm_score": 7, "selected": false, "text": "<pre><code># print line number 52\nsed -n '52p' # method 1\nsed '52!d' # method 2\nsed '52q;d' # method 3, efficient on large files \n</code></pre>\n\n<p><em><strong>method 3 efficient on large files</em></strong></p>\n\n<p>fastest way to display specific lines</p>\n" }, { "answer_id": 18092983, "author": "pixelbeat", "author_id": 4421, "author_profile": "https://Stackoverflow.com/users/4421", "pm_score": 2, "selected": false, "text": "<p>sed will need to read the data too to count the lines.\nThe only way a shortcut would be possible would there to be context/order in the file to operate on. For example if there were log lines prepended with a fixed width time/date etc.\nyou could use the <strong>look</strong> unix utility to binary search through the files for particular dates/times</p>\n" }, { "answer_id": 18093093, "author": "sehe", "author_id": 85371, "author_profile": "https://Stackoverflow.com/users/85371", "pm_score": 4, "selected": false, "text": "<p>I prefer just going into <code>less</code> and </p>\n\n<ul>\n<li>typing <kbd>5</kbd><kbd>0</kbd><kbd>%</kbd> to goto halfway the file, </li>\n<li><kbd>43210</kbd><kbd>G</kbd> to go to line 43210</li>\n<li><code>:43210</code> to do the same </li>\n</ul>\n\n<p>and stuff like that.</p>\n\n<p>Even better: hit <kbd>v</kbd> to start editing (in vim, of course!), at that location. Now, note that <code>vim</code> has the same key bindings!</p>\n" }, { "answer_id": 28302773, "author": "Keithel", "author_id": 2701456, "author_profile": "https://Stackoverflow.com/users/2701456", "pm_score": 2, "selected": false, "text": "<p>Building on Sklivvz' answer, here's a nice function one can put in a <code>.bash_aliases</code> file. It is efficient on huge files when printing stuff from the front of the file.</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>function middle()\n{\n startidx=$1\n len=$2\n endidx=$(($startidx+$len))\n filename=$3\n\n awk \"FNR&gt;=${startidx} &amp;&amp; FNR&lt;=${endidx} { print NR\\\" \\\"\\$0 }; FNR&gt;${endidx} { print \\\"END HERE\\\"; exit }\" $filename\n}\n</code></pre>\n" }, { "answer_id": 28383283, "author": "osirisgothra", "author_id": 549506, "author_profile": "https://Stackoverflow.com/users/549506", "pm_score": 1, "selected": false, "text": "<p>To display a line from a <code>&lt;textfile&gt;</code> by its <code>&lt;line#&gt;</code>, just do this:</p>\n\n<pre><code>perl -wne 'print if $. == &lt;line#&gt;' &lt;textfile&gt;\n</code></pre>\n\n<p>If you want a more powerful way to show a range of lines with regular expressions -- I won't say why grep is a bad idea for doing this, it should be fairly obvious -- this simple expression will show you your range in a single pass which is what you want when dealing with ~20GB text files:</p>\n\n<pre><code>perl -wne 'print if m/&lt;regex1&gt;/ .. m/&lt;regex2&gt;/' &lt;filename&gt;\n</code></pre>\n\n<p>(tip: if your regex has <code>/</code> in it, use something like <code>m!&lt;regex&gt;!</code> instead)</p>\n\n<p>This would print out <code>&lt;filename&gt;</code> starting with the line that matches <code>&lt;regex1&gt;</code> up until (and including) the line that matches <code>&lt;regex2&gt;</code>.</p>\n\n<p>It doesn't take a wizard to see how a few tweaks can make it even more powerful. </p>\n\n<p>Last thing: perl, since it is a mature language, has many hidden enhancements to favor speed and performance. With this in mind, it makes it the obvious choice for such an operation since it was originally developed for handling large log files, text, databases, etc.</p>\n" }, { "answer_id": 31723186, "author": "Ramana Reddy", "author_id": 4894197, "author_profile": "https://Stackoverflow.com/users/4894197", "pm_score": 2, "selected": false, "text": "<p>Use</p>\n\n<pre><code>x=`cat -n &lt;file&gt; | grep &lt;match&gt; | awk '{print $1}'`\n</code></pre>\n\n<p>Here you will get the line number where the match occurred.</p>\n\n<p>Now you can use the following command to print 100 lines</p>\n\n<pre><code>awk -v var=\"$x\" 'NR&gt;=var &amp;&amp; NR&lt;=var+100{print}' &lt;file&gt;\n</code></pre>\n\n<p>or you can use \"sed\" as well</p>\n\n<pre><code>sed -n \"${x},${x+100}p\" &lt;file&gt;\n</code></pre>\n" }, { "answer_id": 33272897, "author": "Fritz Dodoo", "author_id": 5474151, "author_profile": "https://Stackoverflow.com/users/5474151", "pm_score": 0, "selected": false, "text": "<p>You could try this command: </p>\n\n<pre><code>egrep -n \"*\" &lt;filename&gt; | egrep \"&lt;line number&gt;\"\n</code></pre>\n" }, { "answer_id": 36179770, "author": "dagelf", "author_id": 764312, "author_profile": "https://Stackoverflow.com/users/764312", "pm_score": 0, "selected": false, "text": "<p>Easy with perl! If you want to get line 1, 3 and 5 from a file, say /etc/passwd:</p>\n\n<pre><code>perl -e 'while(&lt;&gt;){if(++$l~~[1,3,5]){print}}' &lt; /etc/passwd\n</code></pre>\n" }, { "answer_id": 38250006, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 4, "selected": false, "text": "<p>You can use the <a href=\"https://en.wikipedia.org/wiki/Ex_(text_editor)\" rel=\"noreferrer\"><code>ex</code></a> command, a standard Unix editor (part of Vim now), e.g.</p>\n\n<ul>\n<li><p>display a single line (e.g. 2nd one):</p>\n\n<pre><code>ex +2p -scq file.txt\n</code></pre>\n\n<p>corresponding sed syntax: <code>sed -n '2p' file.txt</code></p></li>\n<li><p>range of lines (e.g. 2-5 lines):</p>\n\n<pre><code>ex +2,5p -scq file.txt\n</code></pre>\n\n<p>sed syntax: <code>sed -n '2,5p' file.txt</code></p></li>\n<li><p>from the given line till the end (e.g. 5th to the end of the file):</p>\n\n<pre><code>ex +5,p -scq file.txt\n</code></pre>\n\n<p>sed syntax: <code>sed -n '2,$p' file.txt</code></p></li>\n<li><p>multiple line ranges (e.g. 2-4 and 6-8 lines):</p>\n\n<pre><code>ex +2,4p +6,8p -scq file.txt\n</code></pre>\n\n<p>sed syntax: <code>sed -n '2,4p;6,8p' file.txt</code></p></li>\n</ul>\n\n<p>Above commands can be tested with the following test file:</p>\n\n<pre><code>seq 1 20 &gt; file.txt\n</code></pre>\n\n<hr>\n\n<p>Explanation:</p>\n\n<ul>\n<li><code>+</code> or <code>-c</code> followed by the command - execute the (vi/vim) command after file has been read,</li>\n<li><code>-s</code> - silent mode, also uses current terminal as a default output,</li>\n<li><code>q</code> followed by <code>-c</code> is the command to quit editor (add <code>!</code> to do force quit, e.g. <code>-scq!</code>).</li>\n</ul>\n" }, { "answer_id": 48709493, "author": "eel ghEEz", "author_id": 80772, "author_profile": "https://Stackoverflow.com/users/80772", "pm_score": 0, "selected": false, "text": "<p>I am surprised only one other answer (by Ramana Reddy) suggested to add line numbers to the output. The following searches for the required line number and colours the output.</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>file=FILE\nlineno=LINENO\nwb=\"107\"; bf=\"30;1\"; rb=\"101\"; yb=\"103\"\ncat -n ${file} | { GREP_COLORS=\"se=${wb};${bf}:cx=${wb};${bf}:ms=${rb};${bf}:sl=${yb};${bf}\" grep --color -C 10 \"^[[:space:]]\\\\+${lineno}[[:space:]]\"; }\n</code></pre>\n" }, { "answer_id": 49246288, "author": "Odeyin", "author_id": 9482464, "author_profile": "https://Stackoverflow.com/users/9482464", "pm_score": 3, "selected": false, "text": "<p>Get <a href=\"https://beyondgrep.com/install/\" rel=\"nofollow noreferrer\"><code>ack</code></a></p>\n\n<p>Ubuntu/Debian install:</p>\n\n<pre><code>$ sudo apt-get install ack-grep\n</code></pre>\n\n<p>Then run:</p>\n\n<pre><code>$ ack --lines=$START-$END filename\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>$ ack --lines=10-20 filename\n</code></pre>\n\n<p>From <code>$ man ack</code>:</p>\n\n<pre><code>--lines=NUM\n Only print line NUM of each file. Multiple lines can be given with multiple --lines options or as a comma separated list (--lines=3,5,7). --lines=4-7 also works. \n The lines are always output in ascending order, no matter the order given on the command line.\n</code></pre>\n" }, { "answer_id": 50940642, "author": "Roopa", "author_id": 6774155, "author_profile": "https://Stackoverflow.com/users/6774155", "pm_score": 4, "selected": false, "text": "<p>If your line number is 100 to read </p>\n\n<pre><code>head -100 filename | tail -1\n</code></pre>\n" }, { "answer_id": 71393963, "author": "jarppa", "author_id": 1609063, "author_profile": "https://Stackoverflow.com/users/1609063", "pm_score": 1, "selected": false, "text": "<p>print line 5</p>\n<pre><code>sed -n '5p' file.txt\nsed '5q' file.txt\n</code></pre>\n<p>print everything else than line 5</p>\n<pre><code>`sed '5d' file.txt\n</code></pre>\n<p>and my creation using google</p>\n<pre><code>#!/bin/bash\n#removeline.sh\n#remove deleting it comes move line xD\n\nusage() { # Function: Print a help message.\n echo &quot;Usage: $0 -l LINENUMBER -i INPUTFILE [ -o OUTPUTFILE ]&quot;\n echo &quot;line is removed from INPUTFILE&quot;\n echo &quot;line is appended to OUTPUTFILE&quot;\n}\nexit_abnormal() { # Function: Exit with error.\n usage\n exit 1\n}\n\nwhile getopts l:i:o:b flag\ndo\n case &quot;${flag}&quot; in\n l) line=${OPTARG};;\n i) input=${OPTARG};;\n o) output=${OPTARG};;\n esac\ndone\n\nif [ -f tmp ]; then\necho &quot;Temp file:tmp exist. delete it yourself :)&quot;\nexit\nfi\n\nif [ -f &quot;$input&quot; ]; then\n re_isanum='^[0-9]+$'\n if ! [[ $line =~ $re_isanum ]] ; then\n echo &quot;Error: LINENUMBER must be a positive, whole number.&quot;\n exit 1\n elif [ $line -eq &quot;0&quot; ]; then\n echo &quot;Error: LINENUMBER must be greater than zero.&quot;\n exit_abnormal\n fi\n if [ ! -z $output ]; then\n sed -n &quot;${line}p&quot; $input &gt;&gt; $output\n fi\n if [ ! -z $input ]; then\n # remove this sed command and this comes move line to other file\n sed &quot;${line}d&quot; $input &gt; tmp &amp;&amp; cp tmp $input\n fi\nfi\n\nif [ -f tmp ]; then\nrm tmp\nfi\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
Trying to debug an issue with a server and my only log file is a 20GB log file (with no timestamps even! Why do people use `System.out.println()` as logging? In production?!) Using grep, I've found an area of the file that I'd like to take a look at, line 347340107. Other than doing something like ``` head -<$LINENUM + 10> filename | tail -20 ``` ... which would require `head` to read through the first 347 million lines of the log file, is there a quick and easy command that would dump lines 347340100 - 347340200 (for example) to the console? **update** I totally forgot that grep can print the context around a match ... this works well. Thanks!
with GNU-grep you could just say ``` grep --context=10 ... ```
191,368
<p>I can reset FPU's CTRL registers with this:</p> <p><a href="http://support.microsoft.com/kb/326219" rel="nofollow noreferrer">http://support.microsoft.com/kb/326219</a></p> <p>But how can I save current registers, and restore them later?</p> <p>It's from .net code..</p> <p>What I'm doing, is from Delphi calling an .net dll as an COM module. Checking the <kbd>Ctrl</kbd> registers in delphi yield one value, checking with controlfp in the .net code gives another value. What I need, is in essential is to do this:</p> <pre><code>_controlfp(_CW_DEFAULT, 0xfffff); </code></pre> <p>So my floatingpoint calculations in the .net code does not crash, but I want to restore the <kbd>Ctrl</kbd> registers when returning.</p> <p>Maybe I don't? Maybe Delphi is resetting them when needed? I blogged about this problem <a href="http://blog.neslekkim.net/2008/10/fpu-issues-when-interoping-delphi-and.html" rel="nofollow noreferrer">here</a>.</p>
[ { "answer_id": 191454, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 3, "selected": false, "text": "<p>Same function you use to change them: <code>_controlfp()</code>. If you pass in a mask of 0, the current value won't be altered, but it <em>will</em> be returned - save it, and use a second call to <code>_controlfp()</code> to restore it later.</p>\n" }, { "answer_id": 198658, "author": "Jim", "author_id": 22722, "author_profile": "https://Stackoverflow.com/users/22722", "pm_score": 4, "selected": true, "text": "<pre><code>uses\n SysUtils;\n\nvar\n SavedCW: Word;\nbegin\n SavedCW := Get8087CW;\n try\n Set8087CW($027f);\n // Call .NET code here\n finally\n Set8087CW(SavedCW);\n end;\nend;\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3308/" ]
I can reset FPU's CTRL registers with this: <http://support.microsoft.com/kb/326219> But how can I save current registers, and restore them later? It's from .net code.. What I'm doing, is from Delphi calling an .net dll as an COM module. Checking the `Ctrl` registers in delphi yield one value, checking with controlfp in the .net code gives another value. What I need, is in essential is to do this: ``` _controlfp(_CW_DEFAULT, 0xfffff); ``` So my floatingpoint calculations in the .net code does not crash, but I want to restore the `Ctrl` registers when returning. Maybe I don't? Maybe Delphi is resetting them when needed? I blogged about this problem [here](http://blog.neslekkim.net/2008/10/fpu-issues-when-interoping-delphi-and.html).
``` uses SysUtils; var SavedCW: Word; begin SavedCW := Get8087CW; try Set8087CW($027f); // Call .NET code here finally Set8087CW(SavedCW); end; end; ```
191,376
<p>I am still trying to wrap my head around design patterns and for the second time I'm coming up against the same problem that seems to be crying out for a pattern solution. </p> <p>I have an accounts system with multiple account types. We have restaurant, hotel, service_provider, and consumer account types. Im sure there will be more business account types in the future, and of course there's a global administrator account.</p> <p>So what I'm wondering is how to implement the switching of account types. Eg. each account will have one or more profiles, but the profile will be different depending on the account type. What kind class relationships should I use here to deal with the multiple types of account - polymorphism or inheritance?</p> <p>It seems like maybe there should be an abstract base Profile class that the other profiles should extend, but I'm not sure how to implement that (eg a join table between profile types and account types?).</p> <p>It also feels like an opportunity to implement the factory pattern, I'm just not sure really how to go about it.</p> <p>Any ideas please?</p> <pre><code>* * </code></pre> <p><em>Edited to provide some examples as suggested:</em></p> <pre><code>Account -&gt; hasMany -&gt; Users Account -&gt; belongsTo -&gt; AccountType Account -&gt; hasOne -&gt; Profile </code></pre> <p>The profile is different depending on what type of account it is, eg an account of type restaurant will have a menu, a wine list etc, an account of type hotel will have room types, amenities, an account of type consumer will have personal tastes, home country etc.</p> <p>The question was what design pattern would best implement these relationships. </p> <p>Hope thats clearer, thanks!</p>
[ { "answer_id": 191386, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 1, "selected": false, "text": "<p>I'd suggest aggregation rather than inheritance here for the relationship between account and profile, but have an Account base class that is inherited into multiple account types.</p>\n\n<p>The account contains a profile object, which can be set in the constructor of each polymorphic account type. </p>\n\n<p>You could wrap the account creation in a factory or virtual constructor pattern as well.</p>\n" }, { "answer_id": 192666, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "<p>thanks for the examples; you may be trying to make this harder than it is. Would the following work?</p>\n\n<pre><code>User &lt;&lt;--&gt; Account\nAccount &lt;&lt;--&gt; AccountType\nAccount &lt;--&gt; Profile\nProfile &lt;&lt;--&gt; ProfileType\n</code></pre>\n\n<p>I question the account-profile 1:1 relationship, it seems likely that an account may end up with more than one profile, or that a profile might belong to a user instead of an account, but i don't really know what a profile is/does in this context</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am still trying to wrap my head around design patterns and for the second time I'm coming up against the same problem that seems to be crying out for a pattern solution. I have an accounts system with multiple account types. We have restaurant, hotel, service\_provider, and consumer account types. Im sure there will be more business account types in the future, and of course there's a global administrator account. So what I'm wondering is how to implement the switching of account types. Eg. each account will have one or more profiles, but the profile will be different depending on the account type. What kind class relationships should I use here to deal with the multiple types of account - polymorphism or inheritance? It seems like maybe there should be an abstract base Profile class that the other profiles should extend, but I'm not sure how to implement that (eg a join table between profile types and account types?). It also feels like an opportunity to implement the factory pattern, I'm just not sure really how to go about it. Any ideas please? ``` * * ``` *Edited to provide some examples as suggested:* ``` Account -> hasMany -> Users Account -> belongsTo -> AccountType Account -> hasOne -> Profile ``` The profile is different depending on what type of account it is, eg an account of type restaurant will have a menu, a wine list etc, an account of type hotel will have room types, amenities, an account of type consumer will have personal tastes, home country etc. The question was what design pattern would best implement these relationships. Hope thats clearer, thanks!
I'd suggest aggregation rather than inheritance here for the relationship between account and profile, but have an Account base class that is inherited into multiple account types. The account contains a profile object, which can be set in the constructor of each polymorphic account type. You could wrap the account creation in a factory or virtual constructor pattern as well.
191,383
<p>For PHP</p> <p>I have a date I want line wrapped.</p> <p>I have $date = '2008-09-28 9:19 pm'; I need the first space replaced with a br to become </p> <pre><code>2008-09-28&lt;br&gt;9:19 pm </code></pre> <p>If it wasn't for that second space before PM, I would just str_replace() it. </p>
[ { "answer_id": 191386, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 1, "selected": false, "text": "<p>I'd suggest aggregation rather than inheritance here for the relationship between account and profile, but have an Account base class that is inherited into multiple account types.</p>\n\n<p>The account contains a profile object, which can be set in the constructor of each polymorphic account type. </p>\n\n<p>You could wrap the account creation in a factory or virtual constructor pattern as well.</p>\n" }, { "answer_id": 192666, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "<p>thanks for the examples; you may be trying to make this harder than it is. Would the following work?</p>\n\n<pre><code>User &lt;&lt;--&gt; Account\nAccount &lt;&lt;--&gt; AccountType\nAccount &lt;--&gt; Profile\nProfile &lt;&lt;--&gt; ProfileType\n</code></pre>\n\n<p>I question the account-profile 1:1 relationship, it seems likely that an account may end up with more than one profile, or that a profile might belong to a user instead of an account, but i don't really know what a profile is/does in this context</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13704/" ]
For PHP I have a date I want line wrapped. I have $date = '2008-09-28 9:19 pm'; I need the first space replaced with a br to become ``` 2008-09-28<br>9:19 pm ``` If it wasn't for that second space before PM, I would just str\_replace() it.
I'd suggest aggregation rather than inheritance here for the relationship between account and profile, but have an Account base class that is inherited into multiple account types. The account contains a profile object, which can be set in the constructor of each polymorphic account type. You could wrap the account creation in a factory or virtual constructor pattern as well.
191,399
<p>How do I change the Read-only file attribute for each file in a folder using c#?</p> <p>Thanks</p>
[ { "answer_id": 191423, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 4, "selected": false, "text": "<pre><code>foreach (string fileName in System.IO.Directory.GetFiles(path))\n{\n System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName);\n\n fileInfo.Attributes |= System.IO.FileAttributes.ReadOnly;\n // or\n fileInfo.IsReadOnly = true;\n}\n</code></pre>\n" }, { "answer_id": 191432, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 2, "selected": false, "text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.io.file.setattributes.aspx\" rel=\"nofollow noreferrer\">File.SetAttributes</a> in a loop iterating over <a href=\"http://msdn.microsoft.com/en-us/library/07wt70x2.aspx\" rel=\"nofollow noreferrer\">Directory.GetFiles</a></p>\n" }, { "answer_id": 191460, "author": "mathieu", "author_id": 971, "author_profile": "https://Stackoverflow.com/users/971", "pm_score": 3, "selected": false, "text": "<p>You can try this : iterate on each file and subdirectory :</p>\n\n<pre><code>public void Recurse(DirectoryInfo directory)\n{\n foreach (FileInfo fi in directory.GetFiles())\n {\n fi.IsReadOnly = false; // or true\n }\n\n foreach (DirectoryInfo subdir in directory.GetDirectories())\n {\n Recurse(subdir);\n }\n}\n</code></pre>\n" }, { "answer_id": 17674053, "author": "Mike", "author_id": 1699543, "author_profile": "https://Stackoverflow.com/users/1699543", "pm_score": 1, "selected": false, "text": "<p>If you wanted to remove the readonly attributes using pattern matching (e.g. all files in the folder with a .txt extension) you could try something like this:</p>\n\n<pre><code>Directory.EnumerateFiles(path, \"*.txt\").ToList().ForEach(file =&gt; new FileInfo(file).Attributes = FileAttributes.Normal);\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I change the Read-only file attribute for each file in a folder using c#? Thanks
``` foreach (string fileName in System.IO.Directory.GetFiles(path)) { System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileName); fileInfo.Attributes |= System.IO.FileAttributes.ReadOnly; // or fileInfo.IsReadOnly = true; } ```
191,400
<p>I have around 25 worksheets in my workbook (Excel spreadsheet). Is there a way I can protect all the 25 worksheets in single click ? or this feature is not available and I will have to write a VBA code to accomplish this. I need very often to protect all sheets and unprotect all sheets and doing individually is time consuming</p>
[ { "answer_id": 191416, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 5, "selected": true, "text": "<p>I don't believe there's a way to do it without using VBA. If you are interested in a VBA solution, here is the code:</p>\n\n<pre><code>Dim ws as Worksheet\nDim pwd as String\n\npwd = \"\" ' Put your password here\nFor Each ws In Worksheets\n ws.Protect Password:=pwd\nNext ws\n</code></pre>\n\n<p>Unprotecting is virtually the same:</p>\n\n<pre><code>Dim ws as Worksheet\nDim pwd as String\n\npwd = \"\" ' Put your password here\nFor Each ws In Worksheets\n ws.Unprotect Password:=pwd\nNext ws\n</code></pre>\n" }, { "answer_id": 191437, "author": "Steven Robbins", "author_id": 26507, "author_profile": "https://Stackoverflow.com/users/26507", "pm_score": 2, "selected": false, "text": "<p>Don't think there's a button to do it, but it's simple enough code:</p>\n\n<p>For Each protSheet In Worksheets\n protSheet.Protect Password := \"boo\"\nNext protSheet</p>\n" }, { "answer_id": 400148, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You can protect the workbook rather than each sheet and this will stop changes being made across the entire workbook</p>\n" }, { "answer_id": 34207413, "author": "ChrisB", "author_id": 5640342, "author_profile": "https://Stackoverflow.com/users/5640342", "pm_score": 2, "selected": false, "text": "<p>You can protect all worksheets from user changes but still allow VBA scripts to make changes with the \"UserInterfaceOnly\" option. This workaround lets you run any VBA script on the worksheets without having to protect and unprotect each time:</p>\n\n<pre><code>Dim ws as Worksheet\nDim pwd as String\n\npwd = \"\" ' Put your password here\nor Each ws In Worksheets\n ws.Protect Password:=pwd, UserInterfaceOnly:=True\nNext ws\n</code></pre>\n\n<p>Unprotecting is the same as the solution offered by Ben Hoffstein:</p>\n\n<pre><code>Dim ws as Worksheet\nDim pwd as String\n\npwd = \"\" ' Put your password here\nFor Each ws In Worksheets\n ws.Unprotect Password:=pwd\nNext ws\n</code></pre>\n\n<p>You can access this macro with a button/shortcut. In Excel 2010 you right-click on the Quick Access toolbar and select \"Customize Quick Access Toolbar\". In the drop down menu to choose commands, select \"Macros\". Then click the VBA script you created to protect (or unprotect). Finally click the \"Add > >\" button and then \"OK\" to save it.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17266/" ]
I have around 25 worksheets in my workbook (Excel spreadsheet). Is there a way I can protect all the 25 worksheets in single click ? or this feature is not available and I will have to write a VBA code to accomplish this. I need very often to protect all sheets and unprotect all sheets and doing individually is time consuming
I don't believe there's a way to do it without using VBA. If you are interested in a VBA solution, here is the code: ``` Dim ws as Worksheet Dim pwd as String pwd = "" ' Put your password here For Each ws In Worksheets ws.Protect Password:=pwd Next ws ``` Unprotecting is virtually the same: ``` Dim ws as Worksheet Dim pwd as String pwd = "" ' Put your password here For Each ws In Worksheets ws.Unprotect Password:=pwd Next ws ```
191,404
<p>I have been asking myself this question for a long time now. Thought of posting it. C# doesn't support Multiple Inheritance(this is the fact). All classes created in C# derive out of 'Object' class(again a fact).</p> <p>So if C# does not support Multiple inheritance, then how are we able to extend a class even though it already extends Object class?</p> <p>Illustating with an example: </p> <ol> <li>class A : object - Class A created.</li> <li>class B : object - Class B created.</li> <li>class A : B - this again is supported. What happens to the earlier association to object.</li> </ol> <p>We are able to use object class methods in A after step 3. So is the turned to multi level inheritance. If that is the case, then</p> <ol> <li>class A : B</li> <li>class C : B</li> <li>class A : C - I must be able to access class B's methods in A. Which is not the case?</li> </ol> <p>Can anyone please explain?</p>
[ { "answer_id": 191418, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "<p>You're confusing mutliple inheritance with an inheritance tree. You can inherit from something other than Object. It's just that Object is sitting way up there at the top of your tree. And someone can inherit your class, but because Object is still up there at the top that class will also inherit from object. Your \"Multi-level\" inheritance is not multiple inheritance.</p>\n\n<p>Multiple inheritance is when you inherit from two different trees, and .Net actually does support this after a fashion via interfaces.</p>\n" }, { "answer_id": 191450, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 0, "selected": false, "text": "<p>Given below.</p>\n\n<pre><code>public class A : B\n{\n\n}\n\npublic class B : C\n{\n public int BProperty { get; set; }\n}\n\npublic class C\n{\n public int CProperty { get; set; }\n}\n\npublic class Test\n{\n public void TestStuff()\n {\n A a = new A();\n\n // These are valid.\n a.CProperty = 1;\n a.BProperty = 2;\n }\n\n}\n</code></pre>\n\n<p>This is valid. Object is a base for C in this case.</p>\n" }, { "answer_id": 191466, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 2, "selected": false, "text": "<p>All classes <em>ultimately</em> derive from Object.</p>\n\n<pre><code>public class A\n</code></pre>\n\n<p>is implicitly equivalent to</p>\n\n<pre><code>public class A : System.Object\n</code></pre>\n\n<p>When you derive from another class</p>\n\n<pre><code>public class A : B\n</code></pre>\n\n<p>where</p>\n\n<pre><code>public class B : System.Object\n</code></pre>\n\n<p>B becomes the parent class, and Object becomes the grandparent class.</p>\n\n<p>And so on.</p>\n\n<p>So it is the parent, grandparent, great-grandparent (etc) class of all other classes.</p>\n" }, { "answer_id": 191475, "author": "epotter", "author_id": 26339, "author_profile": "https://Stackoverflow.com/users/26339", "pm_score": 0, "selected": false, "text": "<p>In the example, the reason that B can extend A is because A extends Object. A class can only specify one parent class, but that class must either be object or have object as one of its ancestors. </p>\n" }, { "answer_id": 191513, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 0, "selected": false, "text": "<p>A class inherits from object <strong>if you do not specify a base class</strong>. Thus:</p>\n\n<pre><code>class C {}\n</code></pre>\n\n<p>is the same as </p>\n\n<pre><code>class C : Object {}\n</code></pre>\n\n<p>However, <strong>if you specify a base class, it will inherit from that class instead of Object</strong>. Thus,</p>\n\n<pre><code>class B : C {}\n</code></pre>\n\n<p>B directly inherits from C instead of Object. Another example,</p>\n\n<pre><code>class A : B {}\n</code></pre>\n\n<p>In this case, A inherits from B instead of Object. To summarize, in this hierarchy:</p>\n\n<pre><code>class C {}\nclass B : C {}\nclass A : B {}\n</code></pre>\n\n<p>Class A derives from B, which derives from C. So Class A is indirectly derived from C because B is derived from C. C also derived from Object which in not explicitly specified but it is there by default. So A is indirectly derived from Object too.</p>\n" }, { "answer_id": 191521, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 4, "selected": true, "text": "<p>Joel's answer is correct. There is a difference between multiple inheritance and an inhertance tree (or derivation chain). In your example, you actually show an inhertance tree: One object inherits (derives) from another object higher in the tree. Multiple inheritance allows one object to inherit from multiple base classes.</p>\n\n<p>Take, for example, the following tree:</p>\n\n<pre><code>public class BaseClass { }\n\npublic class SpecialBaseClass : BaseClass {}\n\npublic class SpecialtyDerivedClass : SpecialBaseClass {}\n</code></pre>\n\n<p>This is perfectly valid and says that SpecialtyDerivedClass inherits from SpecialBaseClass (SpecialtyDerivedClass' parent) which, in turn, derives from BaseClass (SpecialtyDerivedClass' grandparent).</p>\n\n<p>Under the idea of multiple inheritance, the example would look like this:</p>\n\n<pre><code>public class BaseClass { }\n\npublic class SpecialBaseClass {}\n\npublic class SpecialtyDerivedClass : BaseClass, SpecialBaseClass {}\n</code></pre>\n\n<p>This is not allowed in .NET, but it says that SpecialityDerivedClass inherits from both BaseClass and SpecialBaseClass (which are both parents).</p>\n\n<p>.NET does allow a form of multiple inheritance by allowing you to inherit from more than one interface. Changing the example above slightly:</p>\n\n<pre><code>public class BaseClass { }\n\npublic interface ISpecialBase {}\n\npublic interface ISpecialDerived {}\n\npublic class SpecialtyDerivedClass : BaseClass, ISpecialBase, ISpecialDerived {}\n</code></pre>\n\n<p>This says that SpecialtyDerivedClass inherits from BaseClass (it's parent) and also ISpecialBase and ISpecialDerived (also parent's but more like step-parents as interfaces can't specify functionality).</p>\n" }, { "answer_id": 191551, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "<p>A class in C# can only have one parent, but it can have multiple ancestors. You can implement multiple interfaces, but that only means that your class agrees to implement the signatures defined by those interfaces. You don't actually inherit any functionality from those interfaces.</p>\n" }, { "answer_id": 191588, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 2, "selected": false, "text": "<p>One way to look at it is this: C# has an inheritance <em>tree</em>, while C++ (or other muliple-inheritance languages) has an inheritance <em>lattice</em>.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21995/" ]
I have been asking myself this question for a long time now. Thought of posting it. C# doesn't support Multiple Inheritance(this is the fact). All classes created in C# derive out of 'Object' class(again a fact). So if C# does not support Multiple inheritance, then how are we able to extend a class even though it already extends Object class? Illustating with an example: 1. class A : object - Class A created. 2. class B : object - Class B created. 3. class A : B - this again is supported. What happens to the earlier association to object. We are able to use object class methods in A after step 3. So is the turned to multi level inheritance. If that is the case, then 1. class A : B 2. class C : B 3. class A : C - I must be able to access class B's methods in A. Which is not the case? Can anyone please explain?
Joel's answer is correct. There is a difference between multiple inheritance and an inhertance tree (or derivation chain). In your example, you actually show an inhertance tree: One object inherits (derives) from another object higher in the tree. Multiple inheritance allows one object to inherit from multiple base classes. Take, for example, the following tree: ``` public class BaseClass { } public class SpecialBaseClass : BaseClass {} public class SpecialtyDerivedClass : SpecialBaseClass {} ``` This is perfectly valid and says that SpecialtyDerivedClass inherits from SpecialBaseClass (SpecialtyDerivedClass' parent) which, in turn, derives from BaseClass (SpecialtyDerivedClass' grandparent). Under the idea of multiple inheritance, the example would look like this: ``` public class BaseClass { } public class SpecialBaseClass {} public class SpecialtyDerivedClass : BaseClass, SpecialBaseClass {} ``` This is not allowed in .NET, but it says that SpecialityDerivedClass inherits from both BaseClass and SpecialBaseClass (which are both parents). .NET does allow a form of multiple inheritance by allowing you to inherit from more than one interface. Changing the example above slightly: ``` public class BaseClass { } public interface ISpecialBase {} public interface ISpecialDerived {} public class SpecialtyDerivedClass : BaseClass, ISpecialBase, ISpecialDerived {} ``` This says that SpecialtyDerivedClass inherits from BaseClass (it's parent) and also ISpecialBase and ISpecialDerived (also parent's but more like step-parents as interfaces can't specify functionality).
191,413
<p>I'm just starting to wean myself from ASP.NET UpdatePanels. I'm using jQuery and jTemplates to bind the results of a web service to a grid, and everything works fine. </p> <p>Here's the thing: I'm trying to show a spinner GIF while the table is being refreshed (à la UpdateProgress in ASP.NET) I've got it all working, except that the spinner is frozen. To see what's going on, I've tried moving the spinner out from the update progress div and out on the page where I can see it the whole time. It spins and spins until the refresh starts, and stays frozen until the refresh is done, and then starts spinning again. Not really what you want from a 'please wait' spinner!</p> <p>This is in IE7 - haven't had a chance to test in other browsers yet. Any thoughts? Is the ajax call or the client-side databinding so resource-intensive that the browser is unable to tend to its animated GIFs?</p> <h3>Update</h3> <p>Here's the code that refreshes the grid. Not sure if this is synchronous or asynchronous.</p> <pre><code>updateConcessions = function(e) { $.ajax({ type: "POST", url: "Concessions.aspx/GetConcessions", data: "{'Countries':'ga'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { applyTemplate(msg); }, error: function(XMLHttpRequest, textStatus, errorThrown) { } }); } applyTemplate = function(msg) { $('div#TemplateTarget').setTemplate($('div#TemplateSource').html()); $('div#TemplateTarget').processTemplate(msg); } </code></pre> <h3>Update 2</h3> <p>I just checked the <a href="http://docs.jquery.com/Ajax/jQuery.ajax#options" rel="noreferrer">jQuery documentation</a> and the <code>$.ajax()</code> method is asynchronous by default. Just for kicks I added this</p> <pre><code>$.ajax({ async: true, ... </code></pre> <p>and it didn't make any difference.</p>
[ { "answer_id": 191435, "author": "Steve g", "author_id": 12092, "author_profile": "https://Stackoverflow.com/users/12092", "pm_score": 0, "selected": false, "text": "<p>Are you doing a synchronous call or asynchronous call? synchronous calls do cause the browser to seemingly lock up for the duration of the call. The other possibility is that the system is very busy doing whatever work it is doing.</p>\n" }, { "answer_id": 191459, "author": "Chris Pietschmann", "author_id": 7831, "author_profile": "https://Stackoverflow.com/users/7831", "pm_score": 1, "selected": false, "text": "<p>I have seen this behavior in the past when making AJAX calls. I believe this is related to the fact that browsers are only single threaded, so when the AJAX call is returned the thread is working on the call, so consequentially the animated GIF needs to stop momentarily.</p>\n" }, { "answer_id": 191677, "author": "David", "author_id": 26144, "author_profile": "https://Stackoverflow.com/users/26144", "pm_score": 3, "selected": false, "text": "<p>I don't remember precisely what caused it, but we had a similar issue with IE6 in a busy box and we fixed it with this incredible hack in the Javascript:</p>\n\n<pre><code>setTimeout(\"document.images['BusyImage'].src=document.images['BusyImage'].src\",10);\n</code></pre>\n\n<p>That just sets the image source to what it was before, but it is apparently enough to jostle IE out of its stupor.</p>\n\n<p>edit: I think I remember what was causing this: We were loading the animation into a div with display: none. IE loads it and doesn't start the animation, because it's hidden. Unfortunately it doesn't start the animation when you set the containing block to display: block, so we used the above line of code to trick IE into reloading the image.</p>\n" }, { "answer_id": 191761, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 3, "selected": false, "text": "<p>Are you sure that its during the AJAX call that the GIF isn't spinning?</p>\n\n<p>In your concessions.aspx place this line somewhere in the handling of GetConcessions:-</p>\n\n<pre><code>System.Threading.Thread.Sleep(5000);\n</code></pre>\n\n<p>I suspect that the gif spins for 5 seconds then freezes whilst IE renders and paints the result.</p>\n" }, { "answer_id": 191887, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 6, "selected": true, "text": "<p>It's not the Ajax call that's freezing the browser. It's the success handler (applyTemplate). Inserting HTML into a document like that can freeze IE, depending on how much HTML there is. It's because the IE UI is single threaded; if you notice, the actual IE menus are frozen too while this is happening.</p>\n\n<p>As a test, try:</p>\n\n<pre><code>applyTemplate = function(msg) {\n return;\n}\n</code></pre>\n" }, { "answer_id": 3135298, "author": "Matt", "author_id": 378354, "author_profile": "https://Stackoverflow.com/users/378354", "pm_score": 2, "selected": false, "text": "<p>I had a similar problem with the browser freezing. If you are developing and testing locally, for some reason it freezes the web browser. After uploading my code to a web server it started to work. I hope this helps, because it took me hours to figure it out for myself.</p>\n" }, { "answer_id": 4921060, "author": "Javier Mateos", "author_id": 606388, "author_profile": "https://Stackoverflow.com/users/606388", "pm_score": 2, "selected": false, "text": "<p>well, this is for many reasons. First at all, when the ajax call back of the server, you will sense a few miliseconds your gif frozen, but not many relevant. After you will start to process information, and depending of the objects that you manipulate and how you do it, you will have more o less time your gif frozen. This is because the thread is busy processing information. Example if you have 1000 objects and your do a order, and move information, and also you use jquery and append, insert, $.each commands, you will senses a gif frozen. Sometimes it's imposible avoid all the frozen gifs, but yu can limit the time to a few miliseconds doing this: Make a list of response ajax, and process it each 2 seconds (with this you will have the results in a alone array and you wil call it with one setInterval and you avoid the bottle neck of try process one response when the before response is still processing). if you use JQuery don't use $.each, use for. Don't use dom manipulation (append,insert,etc..), use html(). In resume do less code, refactor, and procdess all the response (if you did more of 1) like only 1. Sorry for my english.</p>\n" }, { "answer_id": 12202877, "author": "ruffrey", "author_id": 985414, "author_profile": "https://Stackoverflow.com/users/985414", "pm_score": 3, "selected": false, "text": "<p>The image freezes because while it is hidden the animation is disabled by IE.</p>\n\n<p>To fix this, append the loading image instead of unhiding it:</p>\n\n<pre><code>function showLoader(callback){\n $('#wherever').append(\n '&lt;img class=\"waiting\" src=\"/path/to/gif.gif\" /&gt;'\n );\n\n callback();\n}\n\nfunction finishForm(){\n var passed = formValidate(document.forms.clientSupportReq);\n\n if(passed)\n {\n $('input#subm')\n .val('Uploading...')\n .attr('disabled','disabled');\n $('input#res').hide();\n }\n\n return passed;\n}\n$(function(){\n // on submit\n $('form#formid').submit(function(){\n var l = showLoader( function(){\n finishForm() \n });\n\n if(!l){\n $('.waiting').remove();\n }\n\n return l;\n });\n});\n</code></pre>\n" }, { "answer_id": 13923877, "author": "user1650613", "author_id": 1650613, "author_profile": "https://Stackoverflow.com/users/1650613", "pm_score": 2, "selected": false, "text": "<p>I know the question was regarding asynchronous ajax calls. However I wanted to add that I have found the following in my tests regarding synchronous ajax calls:</p>\n\n<p>For Synchronous ajax calls. While the call is in progress (i.e. waiting for the server to respond). For the test i put a delay in the server response on the server. </p>\n\n<p>Firefox 17.0.1 - animated gif continues to animate properly.</p>\n\n<p>Chrome v23 - animated gif stops animation while the request is in progress.</p>\n" }, { "answer_id": 25200809, "author": "Siri How", "author_id": 3094578, "author_profile": "https://Stackoverflow.com/users/3094578", "pm_score": 1, "selected": false, "text": "<p>dennismonsewicz's answer is greate. Use spin.js and the site <a href=\"http://fgnass.github.com/spin.js/\" rel=\"nofollow\">http://fgnass.github.com/spin.js/</a> shows the step which is quite easy.\nUnder heavy process we should use CSS animations.\nNo JS driven animations and GIFs should be used becacuse of the single thread limit otherwise the animation will freeze. CSS animations are separated from the UI thread.</p>\n" }, { "answer_id": 30917147, "author": "Venkat", "author_id": 2551594, "author_profile": "https://Stackoverflow.com/users/2551594", "pm_score": -1, "selected": false, "text": "<p>Browsers are single-threaded and multi-threaded.</p>\n<p>For any browser :\nWhen you a called a function that contains a nested ajax function</p>\n<p>java/servlet/jsp/Controller &gt;\nkeep Thread.sleep(5000); in servlet to understand the async in ajax when\ntrue or false.</p>\n<pre><code> function ajaxFn(){\n $('#status').html('WAIT... &lt;img id=&quot;theImg&quot; src=&quot;page-loader.gif&quot; alt=&quot;preload&quot; width=&quot;30&quot; height=&quot;30&quot;/&gt;');\n $('#status').css(&quot;color&quot;,&quot;red&quot;);\n $.ajax({\n url:&quot;MyServlet&quot;,\n method: &quot;POST&quot;,\n data: { name: $(&quot;textarea&quot;).val(),\n id : $(&quot;input[type=text]&quot;).val() },\n //async: false,\n success:function(response){\n //alert(response); //response is &quot;welcome to..&quot;\n $(&quot;#status&quot;).text(response);\n $('#status').css(&quot;color&quot;,&quot;green&quot;);\n },\n complete:function(x,y){\n //alert(y)\n },\n error:function(){\n $(&quot;#status&quot;).text(&quot;?&quot;);\n }\n });\n}\n \n</code></pre>\n" }, { "answer_id": 33142061, "author": "yesnik", "author_id": 1921272, "author_profile": "https://Stackoverflow.com/users/1921272", "pm_score": 0, "selected": false, "text": "<p>Wrapping ajax call in <strong>setTimeout</strong> function helped me to prevent freezing of gif-animation:</p>\n\n<pre><code>setTimeout(function() {\n $.get('/some_link', function (response) {\n // some actions\n });\n}, 0);\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
I'm just starting to wean myself from ASP.NET UpdatePanels. I'm using jQuery and jTemplates to bind the results of a web service to a grid, and everything works fine. Here's the thing: I'm trying to show a spinner GIF while the table is being refreshed (à la UpdateProgress in ASP.NET) I've got it all working, except that the spinner is frozen. To see what's going on, I've tried moving the spinner out from the update progress div and out on the page where I can see it the whole time. It spins and spins until the refresh starts, and stays frozen until the refresh is done, and then starts spinning again. Not really what you want from a 'please wait' spinner! This is in IE7 - haven't had a chance to test in other browsers yet. Any thoughts? Is the ajax call or the client-side databinding so resource-intensive that the browser is unable to tend to its animated GIFs? ### Update Here's the code that refreshes the grid. Not sure if this is synchronous or asynchronous. ``` updateConcessions = function(e) { $.ajax({ type: "POST", url: "Concessions.aspx/GetConcessions", data: "{'Countries':'ga'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { applyTemplate(msg); }, error: function(XMLHttpRequest, textStatus, errorThrown) { } }); } applyTemplate = function(msg) { $('div#TemplateTarget').setTemplate($('div#TemplateSource').html()); $('div#TemplateTarget').processTemplate(msg); } ``` ### Update 2 I just checked the [jQuery documentation](http://docs.jquery.com/Ajax/jQuery.ajax#options) and the `$.ajax()` method is asynchronous by default. Just for kicks I added this ``` $.ajax({ async: true, ... ``` and it didn't make any difference.
It's not the Ajax call that's freezing the browser. It's the success handler (applyTemplate). Inserting HTML into a document like that can freeze IE, depending on how much HTML there is. It's because the IE UI is single threaded; if you notice, the actual IE menus are frozen too while this is happening. As a test, try: ``` applyTemplate = function(msg) { return; } ```
191,421
<p>I am using SQL Server 2005. I want to constrain the values in a column to be unique, while allowing NULLS.</p> <p>My current solution involves a unique index on a view like so:</p> <pre><code>CREATE VIEW vw_unq WITH SCHEMABINDING AS SELECT Column1 FROM MyTable WHERE Column1 IS NOT NULL CREATE UNIQUE CLUSTERED INDEX unq_idx ON vw_unq (Column1) </code></pre> <p>Any better ideas? </p>
[ { "answer_id": 191520, "author": "willasaywhat", "author_id": 12234, "author_profile": "https://Stackoverflow.com/users/12234", "pm_score": 6, "selected": true, "text": "<p>Pretty sure you can't do that, as it violates the purpose of uniques.</p>\n\n<p>However, this person seems to have a decent work around:\n<a href=\"http://sqlservercodebook.blogspot.com/2008/04/multiple-null-values-in-unique-index-in.html\" rel=\"noreferrer\">http://sqlservercodebook.blogspot.com/2008/04/multiple-null-values-in-unique-index-in.html</a></p>\n" }, { "answer_id": 191729, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 6, "selected": false, "text": "<p>The calculated column trick is widely known as a \"nullbuster\"; my notes credit Steve Kass:</p>\n\n<pre><code>CREATE TABLE dupNulls (\npk int identity(1,1) primary key,\nX int NULL,\nnullbuster as (case when X is null then pk else 0 end),\nCONSTRAINT dupNulls_uqX UNIQUE (X,nullbuster)\n)\n</code></pre>\n" }, { "answer_id": 3191576, "author": "Phil Haselden", "author_id": 1899, "author_profile": "https://Stackoverflow.com/users/1899", "pm_score": 7, "selected": false, "text": "<p>Using SQL Server 2008, you can <a href=\"https://learn.microsoft.com/en-us/sql/relational-databases/indexes/create-filtered-indexes\" rel=\"noreferrer\">create a filtered index</a>.</p>\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE UNIQUE INDEX AK_MyTable_Column1 ON MyTable (Column1) WHERE Column1 IS NOT NULL\n</code></pre>\n<p>Another option is a trigger to check uniqueness, but this could affect performance.</p>\n" }, { "answer_id": 28688808, "author": "roy", "author_id": 760150, "author_profile": "https://Stackoverflow.com/users/760150", "pm_score": -1, "selected": false, "text": "<p>Strictly speaking, a unique nullable column (or set of columns) can be NULL (or a record of NULLs) only once, since having the same value (and this includes NULL) more than once obviously violates the unique constraint.</p>\n\n<p>However, that doesn't mean the concept of \"unique nullable columns\" is valid; to actually implement it in any relational database we just have to bear in mind that this kind of databases are meant to be normalized to properly work, and normalization usually involves the addition of several (non-entity) extra tables to establish relationships between the entities.</p>\n\n<p>Let's work a basic example considering only one \"unique nullable column\", it's easy to expand it to more such columns.</p>\n\n<p>Suppose we the information represented by a table like this:</p>\n\n<pre><code>create table the_entity_incorrect\n(\n id integer,\n uniqnull integer null, /* we want this to be \"unique and nullable\" */\n primary key (id)\n);\n</code></pre>\n\n<p>We can do it by putting uniqnull apart and adding a second table to establish a relationship between uniqnull values and the_entity (rather than having uniqnull \"inside\" the_entity):</p>\n\n<pre><code>create table the_entity\n(\n id integer,\n primary key(id)\n);\n\ncreate table the_relation\n(\n the_entity_id integer not null,\n uniqnull integer not null,\n\n unique(the_entity_id),\n unique(uniqnull),\n /* primary key can be both or either of the_entity_id or uniqnull */\n primary key (the_entity_id, uniqnull), \n foreign key (the_entity_id) references the_entity(id)\n);\n</code></pre>\n\n<p>To associate a value of uniqnull to a row in the_entity we need to also add a row in the_relation.</p>\n\n<p>For rows in the_entity were no uniqnull values are associated (i.e. for the ones we would put NULL in the_entity_incorrect) we simply do not add a row in the_relation.</p>\n\n<p>Note that values for uniqnull will be unique for all the_relation, and also notice that for each value in the_entity there can be at most one value in the_relation, since the primary and foreign keys on it enforce this.</p>\n\n<p>Then, if a value of 5 for uniqnull is to be associated with an the_entity id of 3, we need to:</p>\n\n<pre><code>start transaction;\ninsert into the_entity (id) values (3); \ninsert into the_relation (the_entity_id, uniqnull) values (3, 5);\ncommit;\n</code></pre>\n\n<p>And, if an id value of 10 for the_entity has no uniqnull counterpart, we only do:</p>\n\n<pre><code>start transaction;\ninsert into the_entity (id) values (10); \ncommit;\n</code></pre>\n\n<p>To denormalize this information and obtain the data a table like the_entity_incorrect would hold, we need to:</p>\n\n<pre><code>select\n id, uniqnull\nfrom\n the_entity left outer join the_relation\non\n the_entity.id = the_relation.the_entity_id\n;\n</code></pre>\n\n<p>The \"left outer join\" operator ensures all rows from the_entity will appear in the result, putting NULL in the uniqnull column when no matching columns are present in the_relation.</p>\n\n<p>Remember, any effort spent for some days (or weeks or months) in designing a well normalized database (and the corresponding denormalizing views and procedures) will save you years (or decades) of pain and wasted resources.</p>\n" }, { "answer_id": 66320752, "author": "Martin Staufcik", "author_id": 1882699, "author_profile": "https://Stackoverflow.com/users/1882699", "pm_score": 1, "selected": false, "text": "<p>It is possible to use <strong>filter predicates</strong> to specify which rows to include in the index.</p>\n<p>From the <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/statements/create-index-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\">documentation</a>:</p>\n<blockquote>\n<p>WHERE &lt;filter_predicate&gt; Creates a filtered index by specifying which\nrows to include in the index. The filtered index must be a\nnonclustered index on a table. Creates filtered statistics for the\ndata rows in the filtered index.</p>\n</blockquote>\n<p>Example:</p>\n<pre><code>CREATE TABLE Table1 (\n NullableCol int NULL\n)\n\nCREATE UNIQUE INDEX IX_Table1 ON Table1 (NullableCol) WHERE NullableCol IS NOT NULL;\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20959/" ]
I am using SQL Server 2005. I want to constrain the values in a column to be unique, while allowing NULLS. My current solution involves a unique index on a view like so: ``` CREATE VIEW vw_unq WITH SCHEMABINDING AS SELECT Column1 FROM MyTable WHERE Column1 IS NOT NULL CREATE UNIQUE CLUSTERED INDEX unq_idx ON vw_unq (Column1) ``` Any better ideas?
Pretty sure you can't do that, as it violates the purpose of uniques. However, this person seems to have a decent work around: <http://sqlservercodebook.blogspot.com/2008/04/multiple-null-values-in-unique-index-in.html>
191,428
<p>Is it possible to change the language of system messages from PostgreSQL?</p> <p>In MSSQL for instance this is possible with the SQL statement <a href="http://msdn.microsoft.com/en-us/library/ms174398.aspx" rel="noreferrer">SET LANGUAGE</a>.</p>
[ { "answer_id": 191958, "author": "Milen A. Radev", "author_id": 15785, "author_profile": "https://Stackoverflow.com/users/15785", "pm_score": 6, "selected": false, "text": "<pre><code>SET lc_messages TO 'en_US.UTF-8';\n</code></pre>\n\n<p>More info on requirements and limitations <a href=\"http://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-LC-MESSAGES\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 36998716, "author": "user1", "author_id": 2377652, "author_profile": "https://Stackoverflow.com/users/2377652", "pm_score": 5, "selected": false, "text": "<p>Milen's answer didn't work for me.</p>\n\n<p>I got it working by modifying a file <code>postgresql.conf</code>. If you're on Linux, write:</p>\n\n<pre><code>sudo find / -iname postgresql.conf\n</code></pre>\n\n<p>I had mine in <code>/var/lib/pgsql/data</code>.\nThen edit the file and search for a variable <code>lc_messages</code> and change it to your preferred language, e.g. <code>'en_US.UTF-8'</code>.</p>\n\n<p>If PostgreSQL stops working and you check in its log that you have an error that looks like this:</p>\n\n<pre><code>invalid value for parameter \"lc_messages\": \"en_US.UTF-8\"\n</code></pre>\n\n<p>You have to edit <code>/etc/locale.gen</code> and uncomment line with encoding from the error message (e.g. <code>en_US.UTF-8</code>). Then you have to run <code>locale-gen</code> (as root) to update the locales. Finally, to check if the locale is set you can run <code>locale -a</code>.</p>\n\n<p>Or, if you want the language to be English, you can just set <code>lc_messages = 'C'</code>.</p>\n" }, { "answer_id": 56811670, "author": "AndreKR", "author_id": 476074, "author_profile": "https://Stackoverflow.com/users/476074", "pm_score": 5, "selected": false, "text": "<p>For me neither Milen A. Radev's nor user1's answer worked - editing <code>PostgreSQL\\11\\data\\postgresql.conf</code> had absolutely no effect. Even after setting <code>lc_messages = 'random value'</code> PostgreSQL would still start.</p>\n\n<p>What helped was to delete <code>PostgreSQL\\11\\share\\locale\\*\\LC_MESSAGES</code>, after that I finally got English messages.</p>\n" }, { "answer_id": 59288926, "author": "Birgit Vera Schmidt", "author_id": 1961209, "author_profile": "https://Stackoverflow.com/users/1961209", "pm_score": 3, "selected": false, "text": "<p>In my case (on Windows Server 2019) I managed to change language by creating a system environment variable \"LC_MESSAGES\" with value \"English\":</p>\n\n<pre><code>setx LC_MESSAGES English /m\n</code></pre>\n\n<p>(Solution taken from <a href=\"https://stackoverflow.com/a/31605952/1961209\">here</a>)</p>\n" }, { "answer_id": 69787330, "author": "invzbl3", "author_id": 8370915, "author_profile": "https://Stackoverflow.com/users/8370915", "pm_score": 1, "selected": false, "text": "<p>I've reproduced the same issue with naming of <code>PostgreSQL</code> error messages which were specifically displayed in <code>Intellij IDEA</code> similar to:</p>\n<p><a href=\"https://i.stack.imgur.com/U5JbJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/U5JbJ.png\" alt=\"enter image description here\" /></a></p>\n<p>the only solution for me was <a href=\"https://stackoverflow.com/questions/191428/change-language-of-system-and-error-messages-in-postgresql#comment121662022_56811670\">renaming</a> <code>C:\\Program Files\\PostgreSQL\\13\\share\\locale</code> folder to another default name.</p>\n<p>then as result changed to:</p>\n<p><a href=\"https://i.stack.imgur.com/0qi6f.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0qi6f.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>To be noticed:</strong> it wasn't related to <code>Intellij Idea</code> configurations at all, because I tested different answers (and other non-related to <code>IDE</code> answers), e.g., like:</p>\n<ol>\n<li><a href=\"https://intellij-support.jetbrains.com/hc/en-us/community/posts/360007648019-Hot-to-change-error-messages-to-English-Intellij-\" rel=\"nofollow noreferrer\">Help | Edit custom VM options</a></li>\n<li><a href=\"https://stackoverflow.com/a/59288926/8370915\">Setting of Environments variables</a></li>\n<li><a href=\"https://stackoverflow.com/a/191958/8370915\">Using specific commands</a></li>\n</ol>\n" }, { "answer_id": 73687425, "author": "huangzhuohua", "author_id": 3977200, "author_profile": "https://Stackoverflow.com/users/3977200", "pm_score": 0, "selected": false, "text": "<p>only change postgresql.conf is not working on windows10,the following method is fine for me,is very simple but work:</p>\n<ol>\n<li>change lc_message = en_US.UTF-8, in postgresql.conf;</li>\n<li>delete all files in fold: \\share\\locale, expect es fold or the\nlanguage you want to keep;</li>\n<li>restart pg service and then you will find that is what you want!</li>\n</ol>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3565/" ]
Is it possible to change the language of system messages from PostgreSQL? In MSSQL for instance this is possible with the SQL statement [SET LANGUAGE](http://msdn.microsoft.com/en-us/library/ms174398.aspx).
``` SET lc_messages TO 'en_US.UTF-8'; ``` More info on requirements and limitations [here](http://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-LC-MESSAGES).
191,429
<p>I'm trying to use <a href="http://www.glish.com/css/9.asp" rel="nofollow noreferrer">this</a> layout with two 50% column width instead. But it seems that when the right columns reaches its 'min-width', it goes under the left column. Is there any way to use the 'shim' technique to set a min-width to the wrapper so both columns stop resizing. Thus, eliminating the problem of the right column finding itself under the left column.</p> <p>My page is as follows.</p> <pre><code>&lt;style type="text/css"&gt; #left { float: left; width: 50%; } .minwidth { width: 500px; height: 0; line-height: 0; } &lt;/style&gt; &lt;div id="wrapper"&gt; &lt;div id="left"&gt; left &lt;/div&gt; &lt;div id="right"&gt; right &lt;/div&gt; &lt;div class="minwidth"&gt;&amp;nbsp;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>The issue with that is the left column will stop resizing, but the right column will go below the left column and keep resizing. Basically, the effect that I want is once the wrappers width goes bellow, that both left, and right columns also stop resizing. Putting the shim in both left and right columns did not work either.</p> <p>Is there possibly another way of going abouts getting two 50% width columns and using a shim to properly set a min width?</p> <p>Thank you.</p> <p>Edit: The whitespace in the minwidth class is actually &amp;nbsp but it got converted. ;)</p>
[ { "answer_id": 191518, "author": "David Arno", "author_id": 7122, "author_profile": "https://Stackoverflow.com/users/7122", "pm_score": -1, "selected": false, "text": "<p>Use a 2 column table. It will do exactly what you want. Div's are supposed to be used to simply divide up logically distinct blocks, and tables are there to lay out columned data. If you want two columns, use a table, rather than trying to force Div's to behave like a table.</p>\n" }, { "answer_id": 191540, "author": "Robert K", "author_id": 24950, "author_profile": "https://Stackoverflow.com/users/24950", "pm_score": 1, "selected": false, "text": "<p>Try this for the style:</p>\n\n<pre><code>.left, .right { width:50%; float: left; }\n.right { float: right; }\n.minwidth { min-width: 500px; display: block; height: 0; clear: both; }\n</code></pre>\n" }, { "answer_id": 191546, "author": "Dr. Bob", "author_id": 12182, "author_profile": "https://Stackoverflow.com/users/12182", "pm_score": 1, "selected": false, "text": "<p>Just set a min width for the wrapper and just change the left and right columns to percentages. This will prevent your two columns from being pushed into/over/under each other.</p>\n" }, { "answer_id": 191553, "author": "slashnick", "author_id": 21030, "author_profile": "https://Stackoverflow.com/users/21030", "pm_score": 1, "selected": false, "text": "<p>This is a quick attempt but it works (only tested in Firefox):</p>\n\n<pre><code>&lt;head&gt;\n&lt;style type=\"text/css\"&gt;\n\n#left {\n float: left;\n width: 50%;\n}\n\n.minwidth {\n min-width: 500px;\n background:#eee;\n height: 0;\n overflow:visible;\n}\n.col{\n min-width:250px;\n background:#eaa;\n}\n\n&lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;div id=\"wrapper\" class=\"minwidth\"&gt;\n &lt;div id=\"left\" class=\"col\"&gt;\n left\n &lt;/div&gt;\n &lt;div id=\"right\" class=\"col\"&gt;\n right\n &lt;/div&gt;\n &lt;div&gt;&lt;!-- Not needed --&gt;&lt;/div&gt;\n&lt;/div&gt;\n&lt;/body&gt;\n</code></pre>\n" }, { "answer_id": 191577, "author": "willasaywhat", "author_id": 12234, "author_profile": "https://Stackoverflow.com/users/12234", "pm_score": 1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;Testing some CSS&lt;/title&gt;\n&lt;style type=\"text/css\"&gt;\n\n.floatme {\n float: left;\n width: 50%;\n}\n\n.minwidth {\n width: 500px;\n height: 0;\n line-height: 0;\n clear: both;\n}\n\n&lt;/style&gt;\n\n\n&lt;body&gt;\n&lt;div id=\"wrapper\"&gt;\n &lt;div class=\"floatme\"&gt;\n left\n &lt;/div&gt;\n &lt;div id=\"floatme\"&gt;\n right\n &lt;/div&gt;\n &lt;div class=\"minwidth\"&gt; &lt;/div&gt;\n&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 230152, "author": "adgoudz", "author_id": 30527, "author_profile": "https://Stackoverflow.com/users/30527", "pm_score": 4, "selected": true, "text": "<p>I was able to come up with a \"no HTML tables required\" solution based off of a technique by Stu Nicholls at CSS Play and I personally like it because not only does it work in IE6+ and FF2+, it is also valid CSS that does not require any hacks. For my argument on why a CSS-based layout is preferable over HTML tables, see below.</p>\n\n<p>First, I recommend that when designing new pages with CSS you do it with <strong>standards compliant</strong> browser mode. For an explanation of quirksmode and standards compliant mode, check out <a href=\"http://www.quirksmode.org/css/quirksmode.html\" rel=\"noreferrer\">this article</a> from one of my favorite CSS resource sites. All you have to do is add a specific DOCTYPE element at the top of your pages. The CSS will then be forced to render in standards compliant mode, resulting in fewer bugs and browser idiosyncrasies. In the case that you can't switch to standards compliant mode there is a min-width solution for browsers in quirksmode, also available at CSS Play.</p>\n\n<p>Second, you must add an additional wrapper around your existing markup. This wrapper is used to set the min-width for browsers that understand min-width (not IE). You can then use the * html trick to specifically target IE 6 and apply Stu Nicholl's technique to the inner wrappers. The technique is detailed here and the specific example used is \"#2 For standards compliant mode IE\":</p>\n\n<p><a href=\"http://www.cssplay.co.uk/boxes/minwidth.html\" rel=\"noreferrer\">http://www.cssplay.co.uk/boxes/minwidth.html</a></p>\n\n<p>The end result is rather simple. It creates 2 50% columns using the <a href=\"http://www.glish.com/css/9.asp\" rel=\"noreferrer\">2-column ALA style</a> technique mentioned in the original question, that have an overall minimum width (of 500px in this example) where the columns stop resizing and the right column does not fall below the left column. I hope this helps!</p>\n\n<p><strong>Edit:</strong> This same technique can be used to apply cross-browser compatible min-width to anything. For instance, the columns do not need to be 50% each and any number of columns can be used. <a href=\"http://www.glish.com/css/\" rel=\"noreferrer\">http://www.glish.com/css/</a> is a great resource for CSS-based page layouts and when combined with this min-width technique there are many nice layouts that can be created with minimal, valid CSS.</p>\n\n<pre><code>&lt;!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"&gt;\n&lt;html&gt;\n&lt;head&gt;\n &lt;style type=\"text/css\"&gt;\n\n /* For browsers that understand min-width */\n .width {\n width: 100%;\n min-width: 500px;\n }\n\n /* IE6 Only */\n * html .minwidth {\n border-left: 500px solid white;\n position: relative;\n float: left;\n }\n\n /* IE6 Only */\n * html .wrapper {\n margin-left: -500px;\n position: relative;\n float: left;\n }\n\n .left {\n float: left;\n width: 50%;\n }\n\n .right {\n float: left;\n }\n\n &lt;/style&gt;\n&lt;/head&gt;\n&lt;body&gt;\n\n&lt;div class=\"width\"&gt;\n &lt;div class=\"minwidth\"&gt;\n &lt;div class=\"wrapper\"&gt;\n &lt;div class=\"left\"&gt;\n Left\n &lt;/div&gt;\n &lt;div class=\"right\"&gt;\n Right\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>Now, my incentive for setting up a Stack Overflow account was being able to respond to the suggestion below that \"If you want two columns, use a table, rather than trying to force Div's to behave like a table\". Since I'm too new to either comment or vote down, I am augmenting this discussion. </p>\n\n<p>Really?</p>\n\n<p>Somebody asks a question about CSS-based layouts and you respond by telling them to use HTML tables?</p>\n\n<p>Let me start by saying that I don't believe that HTML tables are completely unnecessary. In fact, any time I need to display tabular data, <em>i.e. relational data</em>, I use an HTML table. CSS table display properties aren't fully supported yet (coming soon in IE8!) and using a <em>single-level</em> HTML table is an effective solution. Look at the markup for any of Google's web pages and you'll see that they would agree.</p>\n\n<p>As someone who has spent a great deal of time writing CSS-based layouts that are cross-browser compatible when they could have done it in 10 minutes using a table, I agree that there is an easier solution to this problem. However just because you can use dynamite to renovate your kitchen, doesn't mean you should. The following article provides a detailed explanation for why CSS-based layouts are more desirable.</p>\n\n<p><a href=\"http://www.chromaticsites.com/web-design-blog/2008-04-03/13-reasons-why-css-is-superior-to-tables-in-website-design/\" rel=\"noreferrer\">http://www.chromaticsites.com/web-design-blog/2008-04-03/13-reasons-why-css-is-superior-to-tables-in-website-design/</a></p>\n" }, { "answer_id": 1566495, "author": "Jay", "author_id": 103206, "author_profile": "https://Stackoverflow.com/users/103206", "pm_score": 0, "selected": false, "text": "<p>Well, I don't want to get into a political argument, but the reasoning in the cited article by Agoudzward about \"why CSS is better than tables\" has little to do with tables. What it demonstrates is that CSS is better than using individual font tags and color settings and the like over and over again when many page elements call for the same style. Yes, I absolutely agree that if you have a hundred elements on a page that all should be in green, 14pt, Arial text, then it makes excellent sense to create a CSS style for this rather than copying and pasting a font tag over and over, for all the reasons they give. That goes double if you want this same style across multiple pages.</p>\n\n<p>But what does that have to do with tables?</p>\n\n<p>The reasoning seems to be \"CSS is good because it allows you to specify font and color once rather than repeatedly, therefore anything that can be done with CSS is better than any possible alternative\". Well that doesn't follow at all! Just because a tool is good for one type of problem doesn't mean it's good for all possible problems. Hammers are great for putting in nails. That doesn't mean that I use them to put in screws. If I can do a layout more simply and logically with tables than with div's and CSS tags, then to insist that I should nevertheless use CSS because \"CSS is good\" leaves me saying, So what?</p>\n" }, { "answer_id": 1622334, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 1, "selected": false, "text": "<p>Here is a good example of what you desire I think.</p>\n\n<p><a href=\"http://matthewjamestaylor.com/blog/equal-height-columns-2-column.htm\" rel=\"nofollow noreferrer\">http://matthewjamestaylor.com/blog/equal-height-columns-2-column.htm</a></p>\n\n<p>In short here is the CSS:</p>\n\n<pre><code>/* Start of Column CSS */\n#container2 {\n clear:left;\n float:left;\n width:100%;\n overflow:hidden;\n background:#ffa7a7; /* column 2 background colour */\n}\n#container1 {\n float:left;\n width:100%;\n position:relative;\n right:50%;\n background:#fff689; /* column 1 background colour */\n}\n#col1 {\n float:left;\n width:46%;\n position:relative;\n left:52%;\n overflow:hidden;\n}\n#col2 {\n float:left;\n width:46%;\n position:relative;\n left:56%;\n overflow:hidden;\n}\n</code></pre>\n\n<p>Here is the html:</p>\n\n<pre><code>&lt;div id=\"container2\"&gt;\n &lt;div id=\"container1\"&gt;\n &lt;div id=\"col1\"&gt;\n &lt;!-- Column one start --&gt;\n &lt;h2&gt;Equal height columns&lt;/h2&gt;\n &lt;p&gt;It does not matter how much content is in each column, the background colours will always stretch down to the height of the tallest column.&lt;/p&gt;\n\n &lt;h2&gt;Valid XHTML strict markup&lt;/h2&gt;\n &lt;p&gt;The HTML in this layout validates as XHTML 1.0 strict.&lt;/p&gt;\n &lt;!-- Column one end --&gt;\n &lt;/div&gt;\n &lt;div id=\"col2\"&gt;\n &lt;!-- Column two start --&gt;\n &lt;h3&gt;Windows&lt;/h3&gt;\n &lt;ul&gt;\n &lt;li&gt;Firefox 1.5, 2 &amp;amp; 3&lt;/li&gt;\n &lt;li&gt;Safari&lt;/li&gt;\n &lt;li&gt;Opera 8 &amp;amp; 9&lt;/li&gt;\n\n &lt;li&gt;Explorer 5.5, 6 &amp;amp; 7&lt;/li&gt;\n &lt;li&gt;Google Chrome&lt;/li&gt;\n &lt;li&gt;Netscape 8&lt;/li&gt;\n &lt;/ul&gt;\n\n\n &lt;!-- Column two end --&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191429", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25371/" ]
I'm trying to use [this](http://www.glish.com/css/9.asp) layout with two 50% column width instead. But it seems that when the right columns reaches its 'min-width', it goes under the left column. Is there any way to use the 'shim' technique to set a min-width to the wrapper so both columns stop resizing. Thus, eliminating the problem of the right column finding itself under the left column. My page is as follows. ``` <style type="text/css"> #left { float: left; width: 50%; } .minwidth { width: 500px; height: 0; line-height: 0; } </style> <div id="wrapper"> <div id="left"> left </div> <div id="right"> right </div> <div class="minwidth">&nbsp;</div> </div> ``` The issue with that is the left column will stop resizing, but the right column will go below the left column and keep resizing. Basically, the effect that I want is once the wrappers width goes bellow, that both left, and right columns also stop resizing. Putting the shim in both left and right columns did not work either. Is there possibly another way of going abouts getting two 50% width columns and using a shim to properly set a min width? Thank you. Edit: The whitespace in the minwidth class is actually &nbsp but it got converted. ;)
I was able to come up with a "no HTML tables required" solution based off of a technique by Stu Nicholls at CSS Play and I personally like it because not only does it work in IE6+ and FF2+, it is also valid CSS that does not require any hacks. For my argument on why a CSS-based layout is preferable over HTML tables, see below. First, I recommend that when designing new pages with CSS you do it with **standards compliant** browser mode. For an explanation of quirksmode and standards compliant mode, check out [this article](http://www.quirksmode.org/css/quirksmode.html) from one of my favorite CSS resource sites. All you have to do is add a specific DOCTYPE element at the top of your pages. The CSS will then be forced to render in standards compliant mode, resulting in fewer bugs and browser idiosyncrasies. In the case that you can't switch to standards compliant mode there is a min-width solution for browsers in quirksmode, also available at CSS Play. Second, you must add an additional wrapper around your existing markup. This wrapper is used to set the min-width for browsers that understand min-width (not IE). You can then use the \* html trick to specifically target IE 6 and apply Stu Nicholl's technique to the inner wrappers. The technique is detailed here and the specific example used is "#2 For standards compliant mode IE": <http://www.cssplay.co.uk/boxes/minwidth.html> The end result is rather simple. It creates 2 50% columns using the [2-column ALA style](http://www.glish.com/css/9.asp) technique mentioned in the original question, that have an overall minimum width (of 500px in this example) where the columns stop resizing and the right column does not fall below the left column. I hope this helps! **Edit:** This same technique can be used to apply cross-browser compatible min-width to anything. For instance, the columns do not need to be 50% each and any number of columns can be used. <http://www.glish.com/css/> is a great resource for CSS-based page layouts and when combined with this min-width technique there are many nice layouts that can be created with minimal, valid CSS. ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <style type="text/css"> /* For browsers that understand min-width */ .width { width: 100%; min-width: 500px; } /* IE6 Only */ * html .minwidth { border-left: 500px solid white; position: relative; float: left; } /* IE6 Only */ * html .wrapper { margin-left: -500px; position: relative; float: left; } .left { float: left; width: 50%; } .right { float: left; } </style> </head> <body> <div class="width"> <div class="minwidth"> <div class="wrapper"> <div class="left"> Left </div> <div class="right"> Right </div> </div> </div> </div> </body> </html> ``` Now, my incentive for setting up a Stack Overflow account was being able to respond to the suggestion below that "If you want two columns, use a table, rather than trying to force Div's to behave like a table". Since I'm too new to either comment or vote down, I am augmenting this discussion. Really? Somebody asks a question about CSS-based layouts and you respond by telling them to use HTML tables? Let me start by saying that I don't believe that HTML tables are completely unnecessary. In fact, any time I need to display tabular data, *i.e. relational data*, I use an HTML table. CSS table display properties aren't fully supported yet (coming soon in IE8!) and using a *single-level* HTML table is an effective solution. Look at the markup for any of Google's web pages and you'll see that they would agree. As someone who has spent a great deal of time writing CSS-based layouts that are cross-browser compatible when they could have done it in 10 minutes using a table, I agree that there is an easier solution to this problem. However just because you can use dynamite to renovate your kitchen, doesn't mean you should. The following article provides a detailed explanation for why CSS-based layouts are more desirable. <http://www.chromaticsites.com/web-design-blog/2008-04-03/13-reasons-why-css-is-superior-to-tables-in-website-design/>
191,443
<p>I've run into this issue quite a few times and never liked the solution chosen. Let's say you have a list of States (just as a simple example) in the database. In your code-behind, you want to be able to reference a State by ID and have the list of them available via Intellisense. </p> <p>For example:</p> <pre><code>States.Arizona.Id //returns a GUID </code></pre> <p>But the problem is that I don't want to hard-code the GUIDS. Now in the past I've done all of the following:</p> <ul> <li><p>Create class constants (hard-coding of the worst kind.. ugh!)</p></li> <li><p>Create Lookup classes that have an ID property (among others) (still hard-coded and would require a rebuild of the project if ever updated)</p></li> <li><p>Put all the GUIDS into the .config file, create an enumeration, and within a static constructor load the GUIDS from the .config into a Hashtable with the enumeration item as the key. So then I can do: <code>StateHash[StatEnum.Arizona]</code>. Nice, because if a GUID changes, no rebuild required. However, doesn't help if a new record is added or an old one removed, because the enumeration will need to be updated.</p></li> </ul> <p>So what I'm asking is if someone has a better solution? Ideally, I'd want to be able to look up via Intellisense and not have to rebuild code when there's an update. Not even sure that's possible.</p> <p>EDIT: Using states was just an example (probably a bad one). It could be a list of widgets, car types, etc. if that helps.</p>
[ { "answer_id": 191489, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>Personally, I would store lookup data in a database, and simply try to avoid the type of hard coding that binds rules to things like individual states. Perhaps some key property <em>of</em> those states (like .ApplyDoubleTax or something). And non-logic code doesn't need to use intellisense - it typically just needs to list them or find by name, which can be done easily enough however you have stored it.</p>\n\n<p>Equally, I'd load the data once and cache it.</p>\n\n<p>Arguably, coding the logic against states <em>is</em> hard coding - especially if you want to go international anytime soon - I <em>hate</em> it when a site asks me what state I live in...</p>\n\n<p>Re the data changing... is the USA looking to annex anytime soon?</p>\n" }, { "answer_id": 191522, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 0, "selected": false, "text": "<p>This cries out for a custom MSBuild task. You really want an autogenerated enum or class in this case; if the IDs are sourced from a database and can/will change, and are not easily predicted. You could then put the task in your project and it would run before each build updating as necessary.</p>\n\n<p>Or start looking at ORMs :)</p>\n" }, { "answer_id": 191532, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 1, "selected": true, "text": "<p>I believe that if it shows up in Intellisense, then, by definition, it is hard-coded into your program.</p>\n\n<p>That said, if your goal is make the hard-coding as painless as possible, on thing you might try is auto-generating your enumeration based on what's in the database. That is, you can write a program that reads the database and creates a FOO.cs file containing your enumeration. Then just run that program every time the data changes.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22303/" ]
I've run into this issue quite a few times and never liked the solution chosen. Let's say you have a list of States (just as a simple example) in the database. In your code-behind, you want to be able to reference a State by ID and have the list of them available via Intellisense. For example: ``` States.Arizona.Id //returns a GUID ``` But the problem is that I don't want to hard-code the GUIDS. Now in the past I've done all of the following: * Create class constants (hard-coding of the worst kind.. ugh!) * Create Lookup classes that have an ID property (among others) (still hard-coded and would require a rebuild of the project if ever updated) * Put all the GUIDS into the .config file, create an enumeration, and within a static constructor load the GUIDS from the .config into a Hashtable with the enumeration item as the key. So then I can do: `StateHash[StatEnum.Arizona]`. Nice, because if a GUID changes, no rebuild required. However, doesn't help if a new record is added or an old one removed, because the enumeration will need to be updated. So what I'm asking is if someone has a better solution? Ideally, I'd want to be able to look up via Intellisense and not have to rebuild code when there's an update. Not even sure that's possible. EDIT: Using states was just an example (probably a bad one). It could be a list of widgets, car types, etc. if that helps.
I believe that if it shows up in Intellisense, then, by definition, it is hard-coded into your program. That said, if your goal is make the hard-coding as painless as possible, on thing you might try is auto-generating your enumeration based on what's in the database. That is, you can write a program that reads the database and creates a FOO.cs file containing your enumeration. Then just run that program every time the data changes.
191,463
<p>This seems like the most basic question in the world, but damned if I can find an answer.</p> <p>Is there a keyboard shortcut, either native to Visual Studio or through Code Rush or other third-party plug-in, to wrap the current selection with an HTML tag? I'm tired of typing the opening tag, cutting the misplaced closing tag to the clipboard, moving the cursor, and pasting it at the end where it belongs.</p> <p><strong>Update:</strong> <a href="http://screencast.com/t/pesxOgON" rel="noreferrer">This is how TextMate handles surrounding a selection with a tag</a>. Frankly, I'm stunned that Visual Studio doesn't seem to have a similar feature. Creating a macro or snippet for every conceivable tag I might want to use seems absurd.</p>
[ { "answer_id": 191606, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": false, "text": "<p>When faced with this situation, I often type the closing tag first, then the opening tag. This prevents the IDE from \"helping\" by inserting the closing tag where I don't want it. I'm also interested in a better solution, though.</p>\n" }, { "answer_id": 191631, "author": "Ian Jacobs", "author_id": 22818, "author_profile": "https://Stackoverflow.com/users/22818", "pm_score": 2, "selected": false, "text": "<p>Nothing I'm aware of, but writing a macro to wrap it in whatever tag you want shouldn't be hard. I have a similar one that will wrap my selection in a region block.</p>\n" }, { "answer_id": 2879206, "author": "Bradley Mountford", "author_id": 302103, "author_profile": "https://Stackoverflow.com/users/302103", "pm_score": 6, "selected": false, "text": "<p>I know this is old and you have probably found the answer by now but I would just like to add for the sake of those who might not know it that this is possible in VS 2010:</p>\n\n<ol>\n<li>Select the code you would like to surround.</li>\n<li>Do <code>ctrl-k</code> <code>ctrl-s</code> (or right-click and select <code>Surround with...</code>.</li>\n<li>There are a variety of HTML snippets to choose from.</li>\n</ol>\n\n<p>You can create your own SurroundsWith snippets if you do not find what you are looking for:</p>\n\n<ol>\n<li>Click <code>File</code> and then click <code>New</code>, and choose a file type of <code>XML</code>.</li>\n<li>On the <code>File</code> menu, click <code>Save</code> .</li>\n<li>In the <code>Save as</code> box, select <code>All Files (*.*)</code>.</li>\n<li>In the <code>File name</code> box, enter a file name with the <code>.snippet</code> file name extension.</li>\n<li>Click <code>Save</code>.</li>\n</ol>\n\n<p>Enter something like the following sample in the XML file:</p>\n\n<pre><code>&lt;CodeSnippet Format=\"1.1.0\" xmlns=\"http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet\"&gt;\n &lt;Header&gt;\n &lt;Title&gt;ul-div&lt;/Title&gt;\n &lt;Author&gt;Microsoft Corporation&lt;/Author&gt;\n &lt;Shortcut&gt;ul&gt;li&lt;/Shortcut&gt;\n &lt;Description&gt;Wrap in a ul and then an li&lt;/Description&gt;\n &lt;SnippetTypes&gt;\n &lt;SnippetType&gt;Expansion&lt;/SnippetType&gt;\n &lt;SnippetType&gt;SurroundsWith&lt;/SnippetType&gt;\n &lt;/SnippetTypes&gt;\n &lt;/Header&gt;\n &lt;Snippet&gt;\n &lt;Declarations&gt;\n &lt;Literal&gt;\n &lt;ID&gt;selected&lt;/ID&gt;\n &lt;ToolTip&gt;content&lt;/ToolTip&gt;\n &lt;Default&gt;content&lt;/Default&gt;\n &lt;/Literal&gt;\n &lt;/Declarations&gt;\n &lt;Code Language=\"html\"&gt;&lt;![CDATA[&lt;ul&gt;&lt;li&gt;$selected$&lt;/li&gt;&lt;/ul&gt;$end$]]&gt;&lt;/Code&gt;\n &lt;/Snippet&gt;\n&lt;/CodeSnippet&gt;\n</code></pre>\n\n<ol>\n<li>Open <code>Tools</code> > <code>Code Snippets Manager</code>.</li>\n<li>Click <code>Import</code> and browse to the snippet you just created.</li>\n<li>Check <code>My HTML Snippets</code> and click <code>Finish</code> and then <code>OK</code>.</li>\n</ol>\n\n<p>You will then have your shiny new HTML snippet available for wrapping stuff in!</p>\n" }, { "answer_id": 5512631, "author": "Chao", "author_id": 300996, "author_profile": "https://Stackoverflow.com/users/300996", "pm_score": 3, "selected": false, "text": "<p>I know this is an ancient thread but having come up against the issue I finally got round to making my own and as this is one of the first results in Google I figured people might find this useful.</p>\n\n<p>Actually it was pretty easy, I just copied from an existing HTML snippet and moved around the literals. The following snippet will surround with a generic HTML tag, it prompts for the tag and will put it in both the opening and closing tags.</p>\n\n<pre><code>&lt;CodeSnippet Format=\"1.1.0\" xmlns=\"http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet\"&gt;\n &lt;!-- Generic HTML Snippet --&gt;\n &lt;Header&gt;\n &lt;Title&gt;Html&lt;/Title&gt;\n &lt;Author&gt;Liam Slater&lt;/Author&gt;\n &lt;Shortcut&gt;h&lt;/Shortcut&gt;\n &lt;Description&gt;Markup snippet for HTML&lt;/Description&gt;\n &lt;SnippetTypes&gt;\n &lt;SnippetType&gt;SurroundsWith&lt;/SnippetType&gt;\n &lt;/SnippetTypes&gt;\n &lt;/Header&gt;\n &lt;Snippet&gt;\n &lt;Declarations&gt;\n &lt;Literal&gt;\n &lt;ID&gt;tag&lt;/ID&gt;\n &lt;ToolTip&gt;tag&lt;/ToolTip&gt;\n &lt;Default&gt;&lt;/Default&gt;\n &lt;/Literal&gt;\n &lt;Literal&gt;\n &lt;ID&gt;selected&lt;/ID&gt;\n &lt;ToolTip&gt;content&lt;/ToolTip&gt;\n &lt;Default&gt;content&lt;/Default&gt;\n &lt;/Literal&gt;\n &lt;/Declarations&gt;\n &lt;Code Language=\"html\"&gt;&lt;![CDATA[&lt;$tag$&gt;$selected$&lt;/$tag$&gt;$end$]]&gt;&lt;/Code&gt;\n &lt;/Snippet&gt;\n&lt;/CodeSnippet&gt;\n</code></pre>\n" }, { "answer_id": 25382145, "author": "Janspeed", "author_id": 486325, "author_profile": "https://Stackoverflow.com/users/486325", "pm_score": 6, "selected": false, "text": "<p>Ctrl-X -> Type tags -> Ctrl-V is still the fastest solution I've seen as mentioned in this answer: <a href=\"https://stackoverflow.com/a/5109994/486325\">https://stackoverflow.com/a/5109994/486325</a>.</p>\n" }, { "answer_id": 25796282, "author": "zhech", "author_id": 191905, "author_profile": "https://Stackoverflow.com/users/191905", "pm_score": 5, "selected": false, "text": "<p>If you have <a href=\"http://vswebessentials.com\">Web Essentials</a> installed, you can <a href=\"http://vswebessentials.com/features/html#surround-with\">use Shift+Alt+W</a> to surround a selection with a tag.</p>\n" }, { "answer_id": 36803516, "author": "djones", "author_id": 1647159, "author_profile": "https://Stackoverflow.com/users/1647159", "pm_score": 8, "selected": true, "text": "<p>Visual Studio 2015 comes with a new shortcut, Shift+Alt+W, that wraps the current selection with a div. This shortcut leaves the text &quot;div&quot; selected, making it seamlessly changeable to any desired tag. This coupled with the automatic end tag replacement makes for a quick solution.</p>\n<h3>UPDATE</h3>\n<p>This shortcut is available in Visual Studio 2017 as well, but you must have the &quot;ASP.NET and Web Development&quot; workload installed.</p>\n<h1>Example</h1>\n<pre><code>Shift+Alt+W &gt; p &gt; Enter\n</code></pre>\n" }, { "answer_id": 43863928, "author": "Burak Karakuş", "author_id": 1817929, "author_profile": "https://Stackoverflow.com/users/1817929", "pm_score": 3, "selected": false, "text": "<p>For those who use Visual Studio 2017: Right click on an <code>html</code>/<code>cshtml</code> area, or select some elements to wrap, there is a <code>Wrap With &lt;div&gt;</code> button on the list.\n<a href=\"https://i.stack.imgur.com/CSFSa.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/CSFSa.png\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 65353511, "author": "Nate", "author_id": 11437774, "author_profile": "https://Stackoverflow.com/users/11437774", "pm_score": 0, "selected": false, "text": "<p>I know this is an old question but I was just struggling with the same thing. You can install the Emmet Keybindings extension by Andrés Gutiérrez. Once installed you can highlight text then use control + MW to wrap with any tag you'd like. To give each line an opening and closing tag include an * after the tag.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1923/" ]
This seems like the most basic question in the world, but damned if I can find an answer. Is there a keyboard shortcut, either native to Visual Studio or through Code Rush or other third-party plug-in, to wrap the current selection with an HTML tag? I'm tired of typing the opening tag, cutting the misplaced closing tag to the clipboard, moving the cursor, and pasting it at the end where it belongs. **Update:** [This is how TextMate handles surrounding a selection with a tag](http://screencast.com/t/pesxOgON). Frankly, I'm stunned that Visual Studio doesn't seem to have a similar feature. Creating a macro or snippet for every conceivable tag I might want to use seems absurd.
Visual Studio 2015 comes with a new shortcut, Shift+Alt+W, that wraps the current selection with a div. This shortcut leaves the text "div" selected, making it seamlessly changeable to any desired tag. This coupled with the automatic end tag replacement makes for a quick solution. ### UPDATE This shortcut is available in Visual Studio 2017 as well, but you must have the "ASP.NET and Web Development" workload installed. Example ======= ``` Shift+Alt+W > p > Enter ```
191,482
<p>I'm trying to build a similar 'slider' as demoed here <a href="http://ui.jquery.com/repository/real-world/product-slider/" rel="nofollow noreferrer">http://ui.jquery.com/repository/real-world/product-slider/</a> but I'm trying to use interior divs inside of the list items (<code>&lt;li&gt;</code>). it seems as if this demo breaks if you're not using an image or block element (<code>&lt;p&gt;</code>,<code>&lt;div&gt;</code>,etc.)</p> <p>Anyone have any quick solutions to this? I basically want to use text and possibly images inside of a <code>&lt;div&gt;</code> instead of using images.</p> <p>I did find jCarousel which seems as if it works, but I was looking for something a little more lightweight? Any ideas?</p>
[ { "answer_id": 196871, "author": "Rudi", "author_id": 22830, "author_profile": "https://Stackoverflow.com/users/22830", "pm_score": 2, "selected": false, "text": "<p>I think I <em>sort of</em> have a working example of what you're trying to do, but there are a couple issues.</p>\n\n<p>Using the example you posted as a base, you can replace the HTML markup of the LI's in a UL to be DIV's in a container DIV. For example:</p>\n\n<pre><code> &lt;div class=\"sliderGallery\"&gt;\n &lt;div class=\"div-that-gets-cropped\"&gt;\n &lt;div class=\"text-and-images-chunk\"&gt;Some text!&lt;br /&gt;&lt;img class=\"pb-airportexpress\" src=\"slider-gallery_files/pb_airport_express.jpg\" /&gt;&lt;/div&gt;\n &lt;div class=\"text-and-images-chunk\"&gt;Some text!&lt;br /&gt;&lt;img src=\"slider-gallery_files/pb_airport_extreme.jpg\" /&gt;&lt;/div&gt;\n &lt;div class=\"text-and-images-chunk\"&gt;Some text!&lt;br /&gt;&lt;img src=\"slider-gallery_files/pb_timecapsule_20080115.jpg\" /&gt;&lt;/div&gt;\n ...\n &lt;/div&gt;\n</code></pre>\n\n<p>Then you modify the jQuery code in the page to target that container DIV instead of the UL:</p>\n\n<pre><code> window.onload = function () {\n var container = $('div.sliderGallery');\n var divThatGetsCropped = $('div.div-that-gets-cropped', container);\n var itemsWidth = divThatGetsCropped.innerWidth() - container.outerWidth();\n $('.slider', container).slider({\n minValue: 0,\n maxValue: itemsWidth,\n handle: '.handle',\n stop: function (event, ui) {\n divThatGetsCropped.animate({'left' : ui.value * -1}, 500);\n },\n slide: function (event, ui) {\n divThatGetsCropped.css('left', ui.value * -1);\n }\n });\n };\n</code></pre>\n\n<p>Then you have some non-trivial CSS changes to make... The original example relied on the LI's being styled to display: inline, inside of a container with overflow hidden. It's going to be a headache to try to get everything to show up correctly if you just style these \"text-and-images-chunk\" DIV's to be displayed inline. You probably want to float them all.</p>\n\n<p><strong>BUT</strong>, floated elements won't play very nicely with the container \"div-that-gets-cropped\" DIV because of the way it's being \"revealed\" by the \"sliderGallery\" DIV (at least that's what I'm experiencing in Firefox 3.03). I got around this by setting a really big width for the \"div-that-gets-cropped\" DIV (10000 px):</p>\n\n<pre><code> .sliderGallery div.div-that-gets-cropped {\n position: absolute;\n list-style: none;\n overflow: none;\n white-space: nowrap;\n padding: 0;\n margin: 0;\n width: 10000px;\n }\n\n .sliderGallery div.div-that-gets-cropped div.text-and-images-chunk {\n float: left;\n margin-right: 24px;\n }\n</code></pre>\n\n<p>And you'll have to tweak the \"left\" values for .slider-lbl1, .slider-lbl2 to match up whatever the widths end up being (this might be tricky if the size of your text ends up changing the width of the \"text-and-images-chunk\" elements).</p>\n\n<p>The one issue I noticed is that when you have the images in a block-level element, there isn't a good way to get them to \"hug\" the bottom, as they do in the example using inline. You might be able to get this working by playing around with the positioning of the elements (I couldn't), but hopefully this won't be a big deal in your specific usage.</p>\n\n<p>All of that said, jCarousel seems like it's <em>intended for exactly what you're doing</em>, even if it does add a little code bulk.</p>\n" }, { "answer_id": 1021635, "author": "Brian Vallelunga", "author_id": 2656, "author_profile": "https://Stackoverflow.com/users/2656", "pm_score": 0, "selected": false, "text": "<p>Check out the jCarousel Lite plugin. I've found it to be very useful and easy to configure.</p>\n\n<p><a href=\"http://www.gmarwaha.com/jquery/jcarousellite/index.php?#demo\" rel=\"nofollow noreferrer\">http://www.gmarwaha.com/jquery/jcarousellite/index.php?#demo</a></p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8534/" ]
I'm trying to build a similar 'slider' as demoed here <http://ui.jquery.com/repository/real-world/product-slider/> but I'm trying to use interior divs inside of the list items (`<li>`). it seems as if this demo breaks if you're not using an image or block element (`<p>`,`<div>`,etc.) Anyone have any quick solutions to this? I basically want to use text and possibly images inside of a `<div>` instead of using images. I did find jCarousel which seems as if it works, but I was looking for something a little more lightweight? Any ideas?
I think I *sort of* have a working example of what you're trying to do, but there are a couple issues. Using the example you posted as a base, you can replace the HTML markup of the LI's in a UL to be DIV's in a container DIV. For example: ``` <div class="sliderGallery"> <div class="div-that-gets-cropped"> <div class="text-and-images-chunk">Some text!<br /><img class="pb-airportexpress" src="slider-gallery_files/pb_airport_express.jpg" /></div> <div class="text-and-images-chunk">Some text!<br /><img src="slider-gallery_files/pb_airport_extreme.jpg" /></div> <div class="text-and-images-chunk">Some text!<br /><img src="slider-gallery_files/pb_timecapsule_20080115.jpg" /></div> ... </div> ``` Then you modify the jQuery code in the page to target that container DIV instead of the UL: ``` window.onload = function () { var container = $('div.sliderGallery'); var divThatGetsCropped = $('div.div-that-gets-cropped', container); var itemsWidth = divThatGetsCropped.innerWidth() - container.outerWidth(); $('.slider', container).slider({ minValue: 0, maxValue: itemsWidth, handle: '.handle', stop: function (event, ui) { divThatGetsCropped.animate({'left' : ui.value * -1}, 500); }, slide: function (event, ui) { divThatGetsCropped.css('left', ui.value * -1); } }); }; ``` Then you have some non-trivial CSS changes to make... The original example relied on the LI's being styled to display: inline, inside of a container with overflow hidden. It's going to be a headache to try to get everything to show up correctly if you just style these "text-and-images-chunk" DIV's to be displayed inline. You probably want to float them all. **BUT**, floated elements won't play very nicely with the container "div-that-gets-cropped" DIV because of the way it's being "revealed" by the "sliderGallery" DIV (at least that's what I'm experiencing in Firefox 3.03). I got around this by setting a really big width for the "div-that-gets-cropped" DIV (10000 px): ``` .sliderGallery div.div-that-gets-cropped { position: absolute; list-style: none; overflow: none; white-space: nowrap; padding: 0; margin: 0; width: 10000px; } .sliderGallery div.div-that-gets-cropped div.text-and-images-chunk { float: left; margin-right: 24px; } ``` And you'll have to tweak the "left" values for .slider-lbl1, .slider-lbl2 to match up whatever the widths end up being (this might be tricky if the size of your text ends up changing the width of the "text-and-images-chunk" elements). The one issue I noticed is that when you have the images in a block-level element, there isn't a good way to get them to "hug" the bottom, as they do in the example using inline. You might be able to get this working by playing around with the positioning of the elements (I couldn't), but hopefully this won't be a big deal in your specific usage. All of that said, jCarousel seems like it's *intended for exactly what you're doing*, even if it does add a little code bulk.
191,483
<p>I want to check the login status of a user through an ajax request. Depending wether the user is logged in I want to display either the username/password input or the username. Currently the request is sent on body.onload and a prgoress indicator is shown until the response arrives. Is there a better way?</p> <hr> <p>Let's assume that the requirements state that there should be no direct server side processing.</p>
[ { "answer_id": 191499, "author": "Steve g", "author_id": 12092, "author_profile": "https://Stackoverflow.com/users/12092", "pm_score": 1, "selected": false, "text": "<p>Why not check before the user is even given the html?</p>\n\n<p>If you're just running static HTML w/ Javascript, I would suggest using <a href=\"http://www.jquery.com\" rel=\"nofollow noreferrer\">JQuery</a> and using the $(document).ready():</p>\n" }, { "answer_id": 191502, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 3, "selected": false, "text": "<p>This sounds like an operation that should be done on the server first, before the page is rendered. If someone has javascript disabled, what would happen?</p>\n" }, { "answer_id": 191516, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 0, "selected": false, "text": "<p>I think this should be possible, but it is not recommended. The correct thing to do is have the server fully determine the content of the page before it is even sent.</p>\n\n<p>If you're being held up by slow image downloads or other non-HTML content, check out one of the various JavaScript libraries. I always recommend <a href=\"http://jquery.com/\" rel=\"nofollow noreferrer\">jQuery</a>, which has the following syntax:</p>\n\n<pre><code>$(document).ready(function() {\n // The DOM is fully loaded now, but images might still be loading.\n});\n</code></pre>\n" }, { "answer_id": 191605, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>I believe that if you use inline javascript, it should be executed as soon as it's encountered:</p>\n\n<pre><code>&lt;HTML&gt;&lt;HEAD&gt;...&lt;/HEAD&gt;\n&lt;BODY&gt;\n&lt;script&gt;\ndocument.write(\"This is written before anything else\");\n&lt;/script&gt;\nThis come later.\n&lt;/BODY&gt;\n&lt;/HTML&gt;\n</code></pre>\n" }, { "answer_id": 192378, "author": "Eric Wendelin", "author_id": 25066, "author_profile": "https://Stackoverflow.com/users/25066", "pm_score": 3, "selected": true, "text": "<p>If you don't want to depend on a toolkit, you can create your own DOMReady function that looks kinda like this:</p>\n\n<pre>\n/* Usage: DOMReady(ajaxFunc); */\nfunction DOMReady(f) {\n if (!document.all) {\n document.addEventListener(\"DOMContentLoaded\", f, false);\n } else {\n if (document.readystate == 'complete') { \n window.setTimeout(f, 0);\n }\n else {\n //Add event to onload just if all else fails\n attachEvent(window, \"load\", f);\n }\n }\n}\n</pre>\n\n<p>Or for a more complex solution: <a href=\"http://snipplr.com/view/6029/domreadyjs/\" rel=\"nofollow noreferrer\">http://snipplr.com/view/6029/domreadyjs/</a></p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133/" ]
I want to check the login status of a user through an ajax request. Depending wether the user is logged in I want to display either the username/password input or the username. Currently the request is sent on body.onload and a prgoress indicator is shown until the response arrives. Is there a better way? --- Let's assume that the requirements state that there should be no direct server side processing.
If you don't want to depend on a toolkit, you can create your own DOMReady function that looks kinda like this: ``` /* Usage: DOMReady(ajaxFunc); */ function DOMReady(f) { if (!document.all) { document.addEventListener("DOMContentLoaded", f, false); } else { if (document.readystate == 'complete') { window.setTimeout(f, 0); } else { //Add event to onload just if all else fails attachEvent(window, "load", f); } } } ``` Or for a more complex solution: <http://snipplr.com/view/6029/domreadyjs/>
191,493
<p>I often need to design a dialog in Delphi/C++Builder that allows various properties of an object to be modified, and the code to use it typically looks like this.</p> <pre><code>Dialog.Edit1.Text := MyObject.Username; Dialog.Edit2.Text := MyObject.Password; // ... many more of the same if (Dialog.ShowModal = mrOk) begin MyObject.Username := Dialog.Edit1.Text; MyObject.Password := Dialog.Edit2.Text; // ... again, many more of the same end; </code></pre> <p>I also often need similar code for marshalling objects to/from xml/ini-files/whatever.</p> <p>Are there any common idioms or techniques for avoiding this kind of simple but repetitive code?</p>
[ { "answer_id": 191610, "author": "akalenuk", "author_id": 25459, "author_profile": "https://Stackoverflow.com/users/25459", "pm_score": 0, "selected": false, "text": "<p>Delphi at least have 'With', though it doesn't solve the problem completely.</p>\n\n<pre><code>if (Dialog.ShowModal = mrOk) \nbegin\n with MyObject do\n begin\n Username := Dialog.Edit1.Text;\n Password := Dialog.Edit2.Text;\n // ... again, many more of the same\n end;\nend;\n</code></pre>\n\n<p>And builder AFAIK has nothing alike.</p>\n" }, { "answer_id": 191809, "author": "mj2008", "author_id": 5544, "author_profile": "https://Stackoverflow.com/users/5544", "pm_score": 2, "selected": false, "text": "<p>Here's my variation on this. What I did, having got fed up with the same repetitive code, was to name all the edit boxes according to the XML node names I wanted, then iterate around the components and output their values. The XML code should be obvious, and I only have an edit and checkbox, but you should be able to see the idea.</p>\n\n<pre><code>procedure TfrmFTPSetup.LoadFromXML(szFileName : string);\nvar\nxComponent : TComponent;\nnLoop : Integer;\nxMainNode : TXmlNode;\nxDocument : TNativeXml;\nbegin\ninherited;\n\nxDocument := TNativeXml.Create;\ntry\n xDocument.LoadFromFile(szFileName);\n xMainNode := xml_ChildNodeByName(xDocument.Root, 'options');\n for nLoop := 0 to ComponentCount - 1 do\n begin\n xComponent := Components[nLoop];\n if xComponent is TRzCustomEdit then\n begin\n (xComponent as TRzCustomEdit).Text := xMainNode.AttributeByName[xComponent.Name];\n end;\n if xComponent is TRzCheckBox then\n begin\n (xComponent as TRzCheckBox).Checked := xml_X2Boolean(xMainNode.AttributeByName[xComponent.Name], false);\n end;\n end;\nfinally\n FreeAndNil(xDocument);\nend;\n end;\n\n procedure TfrmFTPSetup.SaveToXML(szFileName : string);\nvar\nxComponent : TComponent;\nnLoop : Integer;\nxMainNode : TXmlNode;\nxDocument : TNativeXml;\nbegin\ninherited;\n\nxDocument := TNativeXml.CreateName('ftpcontrol');\ntry\n xMainNode := xml_ChildNodeByNameCreate(xDocument.Root, 'options');\n for nLoop := 0 to ComponentCount - 1 do\n begin\n xComponent := Components[nLoop];\n if xComponent is TRzCustomEdit then\n begin\n xMainNode.AttributeByName[xComponent.Name] := (xComponent as TRzCustomEdit).Text;\n end;\n if xComponent is TRzCheckBox then\n begin\n xMainNode.AttributeByName[xComponent.Name] := xml_Boolean2X((xComponent as TRzCheckBox).Checked);\n end;\n end;\n\n xDocument.XmlFormat := xfReadable;\n xDocument.SaveToFile(szFileName);\nfinally\n FreeAndNil(xDocument);\nend;\n end;\n</code></pre>\n" }, { "answer_id": 192008, "author": "skamradt", "author_id": 9217, "author_profile": "https://Stackoverflow.com/users/9217", "pm_score": 3, "selected": true, "text": "<p>well, something that I feel completely invaluable is the <a href=\"http://www.gexperts.org\" rel=\"nofollow noreferrer\">GExperts</a> plugin wizard \"Reverse Statement\" which is invoked after installing GExperts by pressing Shift + ALT + R</p>\n\n<p>What it does is automatically switch the assignments around for the highlighted block. For example:</p>\n\n<pre><code>edit1.text := dbfield.asString;\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>dbField.asString := edit1.text;\n</code></pre>\n\n<p>Not exactly what your looking for, but a huge time saver when you have a large number of assignments.</p>\n" }, { "answer_id": 192265, "author": "Jozz", "author_id": 12351, "author_profile": "https://Stackoverflow.com/users/12351", "pm_score": 0, "selected": false, "text": "<p>Binding controls to data works well in Delphi, but unfortunately only when that data resides in a TDataSet descendant. You could write a TDataSet descendant that uses an object for data storage, and it turns out that one such thing already exists. See link below... This implementation appears to only work with collections of objects (TCollection or TObjectList), not single objects.</p>\n\n<p><a href=\"http://www.torry.net/pages.php?id=563\" rel=\"nofollow noreferrer\">http://www.torry.net/pages.php?id=563</a> - search the page for for \"Snap Object DataSet\"</p>\n\n<p>I have no personal experience with this, but it would be very useful if it works and especially if it would also work with single object instances, such as a property on a data module...</p>\n" }, { "answer_id": 194226, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 0, "selected": false, "text": "<p>Look up \"<a href=\"http://en.wikipedia.org/wiki/Mediator_pattern\" rel=\"nofollow noreferrer\">mediator pattern</a>\". It's a GoF design pattern, and in their book the GoF in fact motivate this design pattern with a somewhat similar situation to what you're describing here. It aims at solving a different problem -- coupling -- but I think you have this problem too anyhow.</p>\n\n<p>In short, the idea is to create a dialog mediator, an extra object that sits in between all the dialog widgets. No widget knows about any other widget, but each widget does know the mediator. The mediator knows all widgets. When one widget changes it informs the mediator; the mediator then informs the relevant widgets about this. For example, when you click OK the mediator may inform other widgets about this event.</p>\n\n<p>This way each widgets takes care of events and actions related to itself only. The mediator takes care of the interaction between all widgets, so all this \"boilerplate\" code is split over all widgets, and the \"residue\" which is global to all widgets is the interaction, and it is the responsibility of the mediator.</p>\n" }, { "answer_id": 197176, "author": "dcraggs", "author_id": 4382, "author_profile": "https://Stackoverflow.com/users/4382", "pm_score": 1, "selected": false, "text": "<p>It's not considered good practice to access properties of visual components on a form. It is considered better to have seperate properties. In the example above you would have username and password properties with get and set methods. </p>\n\n<p>For example:</p>\n\n<pre><code>unit Unit1;\n\ninterface\n\nuses\n Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,\n Dialogs, StdCtrls;\n\ntype\n TForm1 = class(TForm)\n Edit1: TEdit;\n Edit2: TEdit;\n private\n function GetPassword: string;\n function GetUsername: string;\n procedure SetPassword(const Value: string);\n procedure SetUsername(const Value: string);\n public\n property Password: string read GetPassword write SetPassword;\n property Username: string read GetUsername write SetUsername;\n end;\n\nvar\n Form1: TForm1;\n\nimplementation\n\n{$R *.dfm}\n\nfunction TForm1.GetPassword: string;\nbegin\n Result := Edit2.Text;\nend;\n\nfunction TForm1.GetUsername: string;\nbegin\n Result := Edit1.Text;\nend;\n\nprocedure TForm1.SetPassword(const Value: string);\nbegin\n Edit2.Text := Value;\nend;\n\nprocedure TForm1.SetUsername(const Value: string);\nbegin\n Edit1.Text := Value;\nend;\n\nend.\n</code></pre>\n\n<p>This means you can change the visual components on the form without having it affecting the calling code.</p>\n\n<p>Another option would be to pass the object as a property to the dialog;</p>\n\n<pre><code>unit Unit1;\n\ninterface\n\nuses\n Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,\n Dialogs, StdCtrls;\n\ntype\n TUserObject = class(TObject)\n private\n FPassword: string;\n FUsername: string;\n public\n property Password: string read FPassword write FPassword;\n property Username: string read FUsername write FUsername;\n end;\n\n TForm1 = class(TForm)\n Edit1: TEdit;\n Edit2: TEdit;\n btnOK: TButton;\n procedure btnOKClick(Sender: TObject);\n private\n FUserObject: TUserObject;\n procedure SetUserObject(const Value: Integer);\n public\n property UserObject: Integer read FUserObject write SetUserObject;\n end;\n\nvar\n Form1: TForm1;\n\nimplementation\n\n{$R *.dfm}\n\nprocedure TForm1.btnOKClick(Sender: TObject);\nbegin\n FUserObject.Username := Edit1.Text;\n FUserObject.Password := Edit2.Text;\n ModalResult := mrOK;\nend;\n\nprocedure TForm1.SetUserObject(const Value: Integer);\nbegin\n FUserObject := Value;\n Edit1.Text := FUserObject.Username;\n Edit2.Text := FUserObject.Password;\nend;\n\nend.\n</code></pre>\n\n<p>Hope that helps.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1737/" ]
I often need to design a dialog in Delphi/C++Builder that allows various properties of an object to be modified, and the code to use it typically looks like this. ``` Dialog.Edit1.Text := MyObject.Username; Dialog.Edit2.Text := MyObject.Password; // ... many more of the same if (Dialog.ShowModal = mrOk) begin MyObject.Username := Dialog.Edit1.Text; MyObject.Password := Dialog.Edit2.Text; // ... again, many more of the same end; ``` I also often need similar code for marshalling objects to/from xml/ini-files/whatever. Are there any common idioms or techniques for avoiding this kind of simple but repetitive code?
well, something that I feel completely invaluable is the [GExperts](http://www.gexperts.org) plugin wizard "Reverse Statement" which is invoked after installing GExperts by pressing Shift + ALT + R What it does is automatically switch the assignments around for the highlighted block. For example: ``` edit1.text := dbfield.asString; ``` becomes ``` dbField.asString := edit1.text; ``` Not exactly what your looking for, but a huge time saver when you have a large number of assignments.
191,503
<p>I'm using the following code to loop through a directory to print out the names of the files. However, not all of the files are displayed. I have tried using <strong>clearstatcache</strong> with no effect.</p> <pre><code> $str = ''; $ignore = array('.', '..'); $dh = @opendir( $path ); if ($dh === FALSE) { // error } $file = readdir( $dh ); while( $file !== FALSE ) { if (in_array($file, $ignore, TRUE)) { break; } $str .= $file."\n"; $file = readdir( $dh ); } </code></pre> <p>Here's the contents of the directory right now:</p> <pre><code>root.auth test1.auth test2.auth test3.auth test5.auth </code></pre> <p>However, test5.auth does not appear. If I rename it to test4.auth it does not appear. If I rename it to test6.auth it <strong>does</strong> appear. This is reliable behaviour - I can rename it several times and it still won't show up unless I rename it to test6.auth.</p> <p>What on earth could be happening?</p> <p>I'm running Arch Linux (kernel 2.6.26-ARCH) with PHP Version 5.2.6 and Apache/2.2.9 with Suhosin-Patch. My filesystem is ext3 and I'm running fam 2.6.10.</p>
[ { "answer_id": 191535, "author": "Jacco", "author_id": 22674, "author_profile": "https://Stackoverflow.com/users/22674", "pm_score": 2, "selected": true, "text": "<p>Your <code>break</code> keywords messes up your code:<br>\nYour loop very likely first encounters the '.' directory and than breaks out of your while loop.</p>\n\n<p>try replacing it with a <code>continue</code> and you should be fine.</p>\n" }, { "answer_id": 191545, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 1, "selected": false, "text": "<pre><code>if (in_array($file, $ignore, TRUE)) { break; }\n</code></pre>\n\n<p>Surely that should be <code>continue</code> not <code>break</code>?</p>\n" }, { "answer_id": 192005, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 2, "selected": false, "text": "<p>Continue won't work either, because you will skip the line that reads the next file.</p>\n\n<p>You could get rid of the first <code>$file = readdir( $dh );</code> and then do</p>\n\n<pre><code>while (false !== ($file = readdir($dh))) {\n if (in_array($file, $ignore, TRUE)) { continue; }\n $str .= $file.\"\\n\";\n}\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/840/" ]
I'm using the following code to loop through a directory to print out the names of the files. However, not all of the files are displayed. I have tried using **clearstatcache** with no effect. ``` $str = ''; $ignore = array('.', '..'); $dh = @opendir( $path ); if ($dh === FALSE) { // error } $file = readdir( $dh ); while( $file !== FALSE ) { if (in_array($file, $ignore, TRUE)) { break; } $str .= $file."\n"; $file = readdir( $dh ); } ``` Here's the contents of the directory right now: ``` root.auth test1.auth test2.auth test3.auth test5.auth ``` However, test5.auth does not appear. If I rename it to test4.auth it does not appear. If I rename it to test6.auth it **does** appear. This is reliable behaviour - I can rename it several times and it still won't show up unless I rename it to test6.auth. What on earth could be happening? I'm running Arch Linux (kernel 2.6.26-ARCH) with PHP Version 5.2.6 and Apache/2.2.9 with Suhosin-Patch. My filesystem is ext3 and I'm running fam 2.6.10.
Your `break` keywords messes up your code: Your loop very likely first encounters the '.' directory and than breaks out of your while loop. try replacing it with a `continue` and you should be fine.
191,592
<p>I'm working on a simple 2D game engine in Java, and having no trouble with FSEM, buffer strategies, and so on; my issue is with the mouse cursor. In windowed mode, I can hide the mouse cursor, no problem, by using setCursor() from my JFrame to set a wholly-transparent cursor. However, after a call to device.setFullScreenWindow(this) to go into FSEM, the mouse cursor comes back, and subsequent calls to setCursor() to set it back to my blank cursor have no effect. Calling device.setFullScreenWindow(null) allows me to get rid of the cursor again - it's only while I'm in FSEM that I can't get rid of it.</p> <p>I'm working under JDK 6, target platform is JDK 5+.</p> <p><strong>UPDATE:</strong> I've done some more testing, and it looks like this issue occurs under MacOS X 10.5 w/Java 6u7, but not under Windows XP SP3 with Java 6u7. So, it could possibly be a bug in the Mac version of the JVM.</p>
[ { "answer_id": 191634, "author": "Antonio Louro", "author_id": 15528, "author_profile": "https://Stackoverflow.com/users/15528", "pm_score": 0, "selected": false, "text": "<p>I don't know if this knowledge applies but in a old VB6 app I had the same problem and I got rid of it moving the cursor out of the screen giving it some very large values.<br>\nHope it helps.</p>\n" }, { "answer_id": 192075, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 3, "selected": false, "text": "<p>One developer found a way around it by creating a one pixel cursor out of a transparent GIF.</p>\n\n<p><a href=\"http://sevensoft.livejournal.com/23460.html\" rel=\"noreferrer\">http://sevensoft.livejournal.com/23460.html</a></p>\n\n<p>I know you tried that, but his is specifically addressing the issue of full-screen mode, exactly as you say, so perhaps there's something he's done that you haven't.</p>\n" }, { "answer_id": 192829, "author": "seisyll", "author_id": 21815, "author_profile": "https://Stackoverflow.com/users/21815", "pm_score": 0, "selected": false, "text": "<p>If you're running only on Windows, it looks like you'll need to call ShowCursor(FALSE) through JNI. At least, to make the cursor hide complete.</p>\n\n<p>Here's some code which creates the 1x1 cursor. It works for me, though I still get a 1x1 cursor.</p>\n\n<pre><code> Toolkit toolkit = Toolkit.getDefaultToolkit();\n Dimension dim = toolkit.getBestCursorSize(1,1);\n transCursor = toolkit.createCustomCursor(gc.createCompatibleImage(dim.width, dim.height),\n new Point(0, 0), \"transCursor\");\n ((Component)mainFrame).setCursor(transCursor);\n</code></pre>\n" }, { "answer_id": 192959, "author": "slf", "author_id": 13263, "author_profile": "https://Stackoverflow.com/users/13263", "pm_score": 0, "selected": false, "text": "<p>Specifically for your Mac problem, through JNI you could use the following:</p>\n\n<p><a href=\"http://developer.apple.com/documentation/GraphicsImaging/Reference/Quartz_Services_Ref/Reference/reference.html#//apple_ref/c/func/CGDisplayHideCursor\" rel=\"nofollow noreferrer\">Quartz Display Services Reference - CGDisplayHideCursor</a></p>\n" }, { "answer_id": 205690, "author": "Adrian", "author_id": 7426, "author_profile": "https://Stackoverflow.com/users/7426", "pm_score": 3, "selected": true, "text": "<p>I think I've finally found the solution:</p>\n\n<pre><code>System.setProperty(\"apple.awt.fullscreenhidecursor\",\"true\");\n</code></pre>\n\n<p>This is an Apple-proprietary system property that hides the mouse cursor when an application is in full-screen mode. It's the only way I've found to fix it.</p>\n" }, { "answer_id": 1028113, "author": "Ricket", "author_id": 47493, "author_profile": "https://Stackoverflow.com/users/47493", "pm_score": 1, "selected": false, "text": "<p>Here's what has been working for me:</p>\n\n<pre><code>Toolkit toolkit = Toolkit.getDefaultToolkit();\n\n// get the smallest valid cursor size\nDimension dim = toolkit.getBestCursorSize(1, 1);\n\n// create a new image of that size with an alpha channel\nBufferedImage cursorImg = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_ARGB);\n\n// get a Graphics2D object to draw to the image\nGraphics2D g2d = cursorImg.createGraphics();\n\n// set the background 'color' with 0 alpha and clear the image\ng2d.setBackground(new Color(0.0f, 0.0f, 0.0f, 0.0f));\ng2d.clearRect(0, 0, dim.width, dim.height);\n\n// dispose the Graphics2D object\ng2d.dispose();\n\n// now create your cursor using that transparent image\nhiddenCursor = toolkit.createCustomCursor(cursorImg, new Point(0,0), \"hiddenCursor\");\n</code></pre>\n\n<p>Granted, I haven't tested it on Mac (yet), only Windows. But when I used the common methods I was getting the cursor as black box, so I use the code above the create a transparent box and set it as the cursor instead. Of course you have to use the setCursor method on an AWT object (such as your app's Frame) to set this hiddenCursor. Here is my hideMouse method ('fr' is my Frame):</p>\n\n<pre><code>public void hideMouse(boolean hide) {\n if(hide) {\n fr.setCursor(hiddenCursor);\n } else {\n fr.setCursor(Cursor.getDefaultCursor());\n }\n}\n</code></pre>\n" }, { "answer_id": 4141187, "author": "Janthoe", "author_id": 502739, "author_profile": "https://Stackoverflow.com/users/502739", "pm_score": 4, "selected": false, "text": "<p>Try Creating a custom invisible cursor:</p>\n\n<pre><code> Toolkit toolkit = Toolkit.getDefaultToolkit();\n Point hotSpot = new Point(0,0);\n BufferedImage cursorImage = new BufferedImage(1, 1, BufferedImage.TRANSLUCENT); \n Cursor invisibleCursor = toolkit.createCustomCursor(cursorImage, hotSpot, \"InvisibleCursor\"); \n setCursor(invisibleCursor);\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7426/" ]
I'm working on a simple 2D game engine in Java, and having no trouble with FSEM, buffer strategies, and so on; my issue is with the mouse cursor. In windowed mode, I can hide the mouse cursor, no problem, by using setCursor() from my JFrame to set a wholly-transparent cursor. However, after a call to device.setFullScreenWindow(this) to go into FSEM, the mouse cursor comes back, and subsequent calls to setCursor() to set it back to my blank cursor have no effect. Calling device.setFullScreenWindow(null) allows me to get rid of the cursor again - it's only while I'm in FSEM that I can't get rid of it. I'm working under JDK 6, target platform is JDK 5+. **UPDATE:** I've done some more testing, and it looks like this issue occurs under MacOS X 10.5 w/Java 6u7, but not under Windows XP SP3 with Java 6u7. So, it could possibly be a bug in the Mac version of the JVM.
I think I've finally found the solution: ``` System.setProperty("apple.awt.fullscreenhidecursor","true"); ``` This is an Apple-proprietary system property that hides the mouse cursor when an application is in full-screen mode. It's the only way I've found to fix it.
191,609
<p>Where would you write an error log file, say <code>ErrorLog.txt</code>, in Windows? Keep in mind the path would need to be open to basic users for file write permissions.</p> <p>I know the eventlog is a possible location for writing errors, but does it work for "user" level permissions?</p> <p>EDIT: I am targeting Windows 2003, but I was posing the question in such a way as to have a "General Guideline" for where to write error logs.<br> As for the EventLog, I have had issues before in an ASP.NET application where I wanted to log to the Windows event log, but I had security issues causing me heartache. (I do not recall the issues I had, but remember having them.)</p>
[ { "answer_id": 191618, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 0, "selected": false, "text": "<p>%TEMP% is always a good location for logs I find.</p>\n" }, { "answer_id": 191624, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": -1, "selected": false, "text": "<p>Put it in the directory of the application. The users will need access to the folder to run and execute the application, and you can check write access on application startup.</p>\n\n<p>The event log is a pain to use for troubleshooting, but you should still post significant errors there.</p>\n\n<p>EDIT - You should look into the MS Application Blocks for logging if you are using .NET. They really make life easy.</p>\n\n<p>Jeez Karma-killers. Next time I won't even offer a suggestion when the poster puts up an incomplete post.</p>\n" }, { "answer_id": 191625, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 5, "selected": true, "text": "<p>Have you considered logging the event viewer instead? If you want to write your own log, I suggest the users local app setting directory. Make a product directory under there. It's different on different version of Windows.</p>\n\n<p>On Vista, you cannot put files like this under c:\\program files. You will run into a lot of problems with it. </p>\n\n<p>In .NET, you can find out this folder with this:</p>\n\n<pre><code>Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)\n</code></pre>\n\n<p>And the Event Log is fairly simple to use too:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx</a></p>\n" }, { "answer_id": 191628, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": false, "text": "<p>Personally, I would suggest using the Windows event log, it's great. If you can't, then write the file to the ApplicationData directory or the ProgramData (Application Data for all users on Windows XP) directory.</p>\n" }, { "answer_id": 191667, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 2, "selected": false, "text": "<p>The standard location(s) are:</p>\n\n<pre><code>C:\\Documents and Settings\\All Users\\Application Data\\MyApp\n</code></pre>\n\n<p>or</p>\n\n<pre><code>C:\\Documents and Settings\\%Username%\\Application Data\\MyApp\n</code></pre>\n\n<p>(aka <code>%UserProfile%\\Application Data\\MyApp</code>) which would match your <em>user level</em> permission requirement. It also separates logs created by different users.</p>\n\n<p>Using <em>.NET</em> runtime, these can be built as:</p>\n\n<pre><code>AppDir=\n System.Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)\n</code></pre>\n\n<p>or</p>\n\n<pre><code>AppDir=\n System.Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)\n</code></pre>\n\n<p>followed by:</p>\n\n<pre><code>MyAppDir = IO.Path.Combine(AppDir,'MyApp')\n</code></pre>\n\n<p>(Which, hopefully, maps <em>Vista</em> profiles too).</p>\n" }, { "answer_id": 191671, "author": "Rob", "author_id": 7872, "author_profile": "https://Stackoverflow.com/users/7872", "pm_score": 2, "selected": false, "text": "<p>The Windows event log is definitely the way to go for logging of errors. You're not limited to the \"Application\" log as it's possible to create a new log target (e.g. \"My Application\"). That may need to be done as part of setup as I'm not sure if it requires administrative privileges or not. There's a Microsoft example in C# at <a href=\"http://support.microsoft.com/kb/307024\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/307024</a>.</p>\n\n<p>Windows 2008 also has <a href=\"http://technet.microsoft.com/en-us/library/cc771823.aspx\" rel=\"nofollow noreferrer\">Event Log Forwarding</a> which can be quite handy with server applications.</p>\n" }, { "answer_id": 193977, "author": "David Robbins", "author_id": 19799, "author_profile": "https://Stackoverflow.com/users/19799", "pm_score": 0, "selected": false, "text": "<p>Going against the grain here - it depends on what you need to do. Sometimes you need to manipulate the results, so log.txt is the way to go. It's simple, mutable, and easy to search. </p>\n\n<p>Take an example from Joel. Fogbugz will send a log / dump of error messages via http to their server. You could do the same and not have to worry about the user's access rights on their drive.</p>\n" }, { "answer_id": 194001, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": false, "text": "<p>Text files are great for a server application (you did say Windows 2003). You should have a separate log file for each server application, the location is really a matter of convention to agree with administrators. E.g. for ASP.NET apps I've often seen them placed on a separate disk from the application under a folder structure that mimics the virtual directory structure.</p>\n\n<p>For client apps, one disadvantage of text files is that a user may start multiple copies of your application (unless you've taken specific steps to prevent this). So you have the problem of contention if multiple instances attempt to write to the same log file. For this reason I would always prefer the Windows Event Log for client apps. One caveat is that you need to be an administrator to create an event log - this can be done e.g. by the setup package.</p>\n\n<p>If you do use a file, I'd suggest using the folder Environment.SpecialFolder.<strong>Local</strong>ApplicationData rather than SpecialFolder.ApplicationData as suggested by others. LocalApplicationData is on the local disk: you don't want network problems to stop you from logging when the user has a roaming profile. For a WinForms application, use Application.LocalUserAppDataPath.</p>\n\n<p>In either case, I would use a configuration file to decide where to log, so that you can easily change it. E.g. if you use Log4Net or a similar framework, you can easily configure whether to log to a text file, event log, both or elsewhere (e.g. a database) without changing your app. </p>\n" }, { "answer_id": 215761, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I agree with Lou on this, but I prefer to set this up in a configuration file like Joe said. You can use </p>\n\n<p>file value=\"${APPDATA}/Test/log-file.txt\"</p>\n\n<p>(\"Test\" could be whatever you want, or removed entirely) in the configuration file, which causes the log file to be written to \"/Documents and Settings/LoginUser/Application\nData/Test\" on Windows XP and to \"/Users/LoginUser/AppData/Roaming/Test on Windows Vista.</p>\n\n<p>I am just adding this as I just spent way too much time figuring how to make this work on Windows Vista...</p>\n\n<p>This works as-is with Windows applications. To use logging in web applications, I found Phil Haack's blog entry on this to be a great resource: \n<a href=\"http://haacked.com/archive/2005/03/07/ConfiguringLog4NetForWebApplications.aspx\" rel=\"nofollow noreferrer\">http://haacked.com/archive/2005/03/07/ConfiguringLog4NetForWebApplications.aspx</a></p>\n" }, { "answer_id": 4510890, "author": "ExplodingBoy", "author_id": 551397, "author_profile": "https://Stackoverflow.com/users/551397", "pm_score": 0, "selected": false, "text": "<p>I personally don't like to use the Windows Event Log where I am right now because we do not have access to the production servers, so that would mean that we would need to request access every time we wanted to look at the errors. It is not a speedy process unfortunately, so your troubleshooting is completely haulted by waiting for someone else. I also don't like that they kind of get lost within the ones from other applications. Sure you can sort, but it's just a bit of a nucance scrolling down. What you use will end up being a combination of personal preference coupled along with limitations of the enviroment you are working in. (log file, event log, or database)</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1048/" ]
Where would you write an error log file, say `ErrorLog.txt`, in Windows? Keep in mind the path would need to be open to basic users for file write permissions. I know the eventlog is a possible location for writing errors, but does it work for "user" level permissions? EDIT: I am targeting Windows 2003, but I was posing the question in such a way as to have a "General Guideline" for where to write error logs. As for the EventLog, I have had issues before in an ASP.NET application where I wanted to log to the Windows event log, but I had security issues causing me heartache. (I do not recall the issues I had, but remember having them.)
Have you considered logging the event viewer instead? If you want to write your own log, I suggest the users local app setting directory. Make a product directory under there. It's different on different version of Windows. On Vista, you cannot put files like this under c:\program files. You will run into a lot of problems with it. In .NET, you can find out this folder with this: ``` Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) ``` And the Event Log is fairly simple to use too: <http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx>
191,640
<p>I wish to search a database table on a nullable column. Sometimes the value I'm search for is itself NULL. Since Null is equal to nothing, even NULL, saying</p> <pre><code>where MYCOLUMN=SEARCHVALUE </code></pre> <p>will fail. Right now I have to resort to</p> <pre><code>where ((MYCOLUMN=SEARCHVALUE) OR (MYCOLUMN is NULL and SEARCHVALUE is NULL)) </code></pre> <p>Is there a simpler way of saying that?</p> <p>(I'm using Oracle if that matters)</p>
[ { "answer_id": 191646, "author": "DCookie", "author_id": 8670, "author_profile": "https://Stackoverflow.com/users/8670", "pm_score": 2, "selected": false, "text": "<p>Try </p>\n\n<pre><code>WHERE NVL(mycolumn,'NULL') = NVL(searchvalue,'NULL')\n</code></pre>\n" }, { "answer_id": 191648, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 3, "selected": false, "text": "<p>Use NVL to replace null with some dummy value on both sides, as in:</p>\n\n<pre><code>WHERE NVL(MYCOLUMN,0) = NVL(SEARCHVALUE,0)\n</code></pre>\n" }, { "answer_id": 191649, "author": "Chris Shaffer", "author_id": 6744, "author_profile": "https://Stackoverflow.com/users/6744", "pm_score": 4, "selected": false, "text": "<p>I don't know if it's simpler, but I've occasionally used</p>\n\n<pre><code>WHERE ISNULL(MyColumn, -1) = ISNULL(SearchValue, -1)\n</code></pre>\n\n<p>Replacing \"-1\" with some value that is valid for the column type but also not likely to be actually found in the data.</p>\n\n<p>NOTE: I use MS SQL, not Oracle, so not sure if \"ISNULL\" is valid.</p>\n" }, { "answer_id": 191656, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 7, "selected": true, "text": "<p>You can do the IsNull or NVL stuff, but it's just going to make the engine do more work. You'll be calling functions to do column conversions which then have to have the results compared.</p>\n\n<p>Use what you have</p>\n\n<pre><code>where ((MYCOLUMN=SEARCHVALUE) OR (MYCOLUMN is NULL and SEARCHVALUE is NULL))\n</code></pre>\n" }, { "answer_id": 191658, "author": "Carl", "author_id": 951280, "author_profile": "https://Stackoverflow.com/users/951280", "pm_score": 0, "selected": false, "text": "<p>I would think that what you have is OK. You could maybe use:</p>\n\n<pre><code>where NVL(MYCOLUMN, '') = NVL(SEARCHVALUE, '')\n</code></pre>\n" }, { "answer_id": 191680, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": false, "text": "<p>Another alternative, which is probably optimal from the executed query point of view, and <em>will be useful only if you are doing some kind of query generation</em> is to generate the exact query you need based on the search value.</p>\n\n<p>Pseudocode follows.</p>\n\n<pre><code>if (SEARCHVALUE IS NULL) {\n condition = 'MYCOLUMN IS NULL'\n} else {\n condition = 'MYCOLUMN=SEARCHVALUE'\n}\nrunQuery(query,condition)\n</code></pre>\n" }, { "answer_id": 192072, "author": "DCookie", "author_id": 8670, "author_profile": "https://Stackoverflow.com/users/8670", "pm_score": 5, "selected": false, "text": "<p>@Andy Lester asserts that the original form of the query is more efficient than using NVL. I decided to test that assertion:</p>\n\n<pre><code> SQL&gt; DECLARE\n 2 CURSOR B IS\n 3 SELECT batch_id, equipment_id\n 4 FROM batch;\n 5 v_t1 NUMBER;\n 6 v_t2 NUMBER;\n 7 v_c1 NUMBER;\n 8 v_c2 NUMBER;\n 9 v_b INTEGER;\n 10 BEGIN\n 11 -- Form 1 of the where clause\n 12 v_t1 := dbms_utility.get_time;\n 13 v_c1 := dbms_utility.get_cpu_time;\n 14 FOR R IN B LOOP\n 15 SELECT COUNT(*)\n 16 INTO v_b\n 17 FROM batch\n 18 WHERE equipment_id = R.equipment_id OR (equipment_id IS NULL AND R.equipment_id IS NULL);\n 19 END LOOP;\n 20 v_t2 := dbms_utility.get_time;\n 21 v_c2 := dbms_utility.get_cpu_time;\n 22 dbms_output.put_line('For clause: WHERE equipment_id = R.equipment_id OR (equipment_id IS NULL AND R.equipment_id IS NULL)');\n 23 dbms_output.put_line('CPU seconds used: '||(v_c2 - v_c1)/100);\n 24 dbms_output.put_line('Elapsed time: '||(v_t2 - v_t1)/100);\n 25 \n 26 -- Form 2 of the where clause\n 27 v_t1 := dbms_utility.get_time;\n 28 v_c1 := dbms_utility.get_cpu_time;\n 29 FOR R IN B LOOP\n 30 SELECT COUNT(*)\n 31 INTO v_b\n 32 FROM batch\n 33 WHERE NVL(equipment_id,'xxxx') = NVL(R.equipment_id,'xxxx');\n 34 END LOOP;\n 35 v_t2 := dbms_utility.get_time;\n 36 v_c2 := dbms_utility.get_cpu_time;\n 37 dbms_output.put_line('For clause: WHERE NVL(equipment_id,''xxxx'') = NVL(R.equipment_id,''xxxx'')');\n 38 dbms_output.put_line('CPU seconds used: '||(v_c2 - v_c1)/100);\n 39 dbms_output.put_line('Elapsed time: '||(v_t2 - v_t1)/100);\n 40 END;\n 41 /\n\n\n For clause: WHERE equipment_id = R.equipment_id OR (equipment_id IS NULL AND R.equipment_id IS NULL)\n CPU seconds used: 84.69\n Elapsed time: 84.8\n For clause: WHERE NVL(equipment_id,'xxxx') = NVL(R.equipment_id,'xxxx')\n CPU seconds used: 124\n Elapsed time: 124.01\n\n PL/SQL procedure successfully completed\n\n SQL&gt; select count(*) from batch;\n\n COUNT(*)\n----------\n 20903\n\nSQL&gt; \n</code></pre>\n\n<p>I was kind of surprised to find out just how correct Andy is. It costs nearly 50% more to do the NVL solution. So, even though one piece of code might not look as tidy or elegant as another, it could be significantly more efficient. I ran this procedure multiple times, and the results were nearly the same each time. Kudos to Andy...</p>\n" }, { "answer_id": 275796, "author": "Ted", "author_id": 7972, "author_profile": "https://Stackoverflow.com/users/7972", "pm_score": 2, "selected": false, "text": "<p>If an out-of-band value is possible:</p>\n\n<pre><code>where coalesce(mycolumn, 'out-of-band') \n = coalesce(searchvalue, 'out-of-band')\n</code></pre>\n" }, { "answer_id": 351611, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 1, "selected": false, "text": "<p>This can also do the job in Oracle.</p>\n\n<pre><code>WHERE MYCOLUMN || 'X' = SEARCHVALUE || 'X'\n</code></pre>\n\n<p>There are some situations where it beats the IS NULL test with the OR.</p>\n\n<p>I was also surprised that DECODE lets you check NULL against NULL.</p>\n\n<pre><code>WITH \nTEST AS\n(\n SELECT NULL A FROM DUAL\n)\nSELECT DECODE (A, NULL, 'NULL IS EQUAL', 'NULL IS NOT EQUAL')\nFROM TEST\n</code></pre>\n" }, { "answer_id": 5303981, "author": "Peter Meinl", "author_id": 158475, "author_profile": "https://Stackoverflow.com/users/158475", "pm_score": 4, "selected": false, "text": "<p>In <a href=\"https://rads.stackoverflow.com/amzn/click/com/1590595300\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Expert Oracle Database Architecture</a> I saw:</p>\n\n<pre><code>WHERE DECODE(MYCOLUMN, SEARCHVALUE, 1) = 1\n</code></pre>\n" }, { "answer_id": 16961703, "author": "Jason Winger", "author_id": 2459552, "author_profile": "https://Stackoverflow.com/users/2459552", "pm_score": 0, "selected": false, "text": "<p>This is a situation we find ourselves in a lot with our Oracle functions that drive reports. We want to allow users to enter a value to restrict results or leave it blank to return all records. This is what I have used and it has worked well for us.</p>\n\n<pre><code>WHERE rte_pending.ltr_rte_id = prte_id\n OR ((rte_pending.ltr_rte_id IS NULL OR rte_pending.ltr_rte_id IS NOT NULL)\n AND prte_id IS NULL)\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191640", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12725/" ]
I wish to search a database table on a nullable column. Sometimes the value I'm search for is itself NULL. Since Null is equal to nothing, even NULL, saying ``` where MYCOLUMN=SEARCHVALUE ``` will fail. Right now I have to resort to ``` where ((MYCOLUMN=SEARCHVALUE) OR (MYCOLUMN is NULL and SEARCHVALUE is NULL)) ``` Is there a simpler way of saying that? (I'm using Oracle if that matters)
You can do the IsNull or NVL stuff, but it's just going to make the engine do more work. You'll be calling functions to do column conversions which then have to have the results compared. Use what you have ``` where ((MYCOLUMN=SEARCHVALUE) OR (MYCOLUMN is NULL and SEARCHVALUE is NULL)) ```
191,644
<p>I've googled around a bit, but maybe I didn't put the correct magik incantation into the search box. </p> <p>Does anyone know how to get output parameters from a stored procedure in Python? I'm using pymssql to call a stored procedure, and I'm not sure of the correct syntax to get the output parameter back. I don't think I can use any other db modules since I'm running this from a Linux box to connect to a mssql database on a MS Server.</p> <pre><code>import pymssql con = pymssql.connect(host='xxxxx',user='xxxx',password='xxxxx',database='xxxxx') cur = con.cursor() query = "EXECUTE blah blah blah" cur.execute(query) con.commit() con.close() </code></pre>
[ { "answer_id": 192032, "author": "Milen A. Radev", "author_id": 15785, "author_profile": "https://Stackoverflow.com/users/15785", "pm_score": 2, "selected": false, "text": "<p>I'm not a python expert but after a brief perusing of the <a href=\"http://www.python.org/dev/peps/pep-0249/\" rel=\"nofollow noreferrer\">DB-API 2.0</a> I believe you should use the \"callproc\" method of the cursor like this:</p>\n\n<pre><code>cur.callproc('my_stored_proc', (first_param, second_param, an_out_param))\n</code></pre>\n\n<p>Then you'll have the result in the returned value (of the out param) in the \"an_out_param\" variable.</p>\n" }, { "answer_id": 198338, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 0, "selected": false, "text": "<p>You might also look at using SELECT rather than EXECUTE. EXECUTE is (iirc) basically a SELECT that doesn't actually fetch anything (, just makes side-effects happen).</p>\n" }, { "answer_id": 198358, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "<p>If you make your procedure produce a table, you can use that result as a substitute for out params.</p>\n\n<p>So instead of:</p>\n\n<pre><code>CREATE PROCEDURE Foo (@Bar INT OUT, @Baz INT OUT) AS\nBEGIN\n /* Stuff happens here */\n RETURN 0\nEND\n</code></pre>\n\n<p>do</p>\n\n<pre><code>CREATE PROCEDURE Foo (@Bar INT, @Baz INT) AS\nBEGIN\n /* Stuff happens here */\n SELECT @Bar Bar, @Baz Baz\n RETURN 0\nEND\n</code></pre>\n" }, { "answer_id": 220033, "author": "Paul D. Eden", "author_id": 3045, "author_profile": "https://Stackoverflow.com/users/3045", "pm_score": 1, "selected": false, "text": "<p>It looks like every python dbapi library implemented on top of freetds (pymssql, pyodbc, etc) will not be able to access output parameters when connecting to Microsoft SQL Server 7 SP3 and higher.</p>\n\n<p><a href=\"http://www.freetds.org/faq.html#ms.output.parameters\" rel=\"nofollow noreferrer\">http://www.freetds.org/faq.html#ms.output.parameters</a></p>\n" }, { "answer_id": 220150, "author": "Paul D. Eden", "author_id": 3045, "author_profile": "https://Stackoverflow.com/users/3045", "pm_score": 2, "selected": false, "text": "<p>If you cannot or don't want to modify the original procedure and have access to the database you can write a simple wrapper procedure that is callable from python.</p>\n\n<p>For example, if you have a stored procedure like:</p>\n\n<pre><code>CREATE PROC GetNextNumber\n @NextNumber int OUTPUT\nAS\n...\n</code></pre>\n\n<p>You could write a wrapper like so which is easily callable from python:</p>\n\n<pre><code>CREATE PROC GetNextNumberWrap\nAS\n DECLARE @RNextNumber int\n EXEC GetNextNumber @RNextNumber\n SELECT @RNextNumber\nGO\n</code></pre>\n\n<p>Then you could call it from python like so:</p>\n\n<pre><code>import pymssql\ncon = pymssql.connect(...)\ncur = con.cursor()\ncur.execute(\"EXEC GetNextNumberWrap\")\nnext_num = cur.fetchone()[0]\n</code></pre>\n" }, { "answer_id": 1596296, "author": "M Deitemeyer", "author_id": 193285, "author_profile": "https://Stackoverflow.com/users/193285", "pm_score": 1, "selected": false, "text": "<p>I was able to get an output value from a SQL stored procedure using Python. I could not find good help getting the output values in Python. I figured out the Python syntax myself, so I suspect this is worth posting here:</p>\n\n<pre><code>import sys, string, os, shutil, arcgisscripting\nfrom win32com.client import Dispatch\nfrom adoconstants import *\n\n#skip ahead to the important stuff\n\nconn = Dispatch('ADODB.Connection')\nconn.ConnectionString = \"Provider=sqloledb.1; Data Source=NT38; Integrated Security = SSPI;database=UtilityTicket\"\nconn.Open()\n\n#Target Procedure Example: EXEC TicketNumExists @ticketNum = 8386998, @exists output\n\nCmd = Dispatch('ADODB.Command')\nCmd.ActiveConnection = conn\n\nCmd.CommandType = adCmdStoredProc\nCmd.CommandText = \"TicketNumExists\"\n\nParam1 = Cmd.CreateParameter('@ticketNum', adInteger, adParamInput)\nParam1.Value = str(TicketNumber)\nParam2 = Cmd.CreateParameter('@exists', adInteger, adParamOutput)\n\nCmd.Parameters.Append(Param1)\nCmd.Parameters.Append(Param2)\n\nCmd.Execute()\n\nAnswer = Cmd.Parameters('@exists').Value\n</code></pre>\n" }, { "answer_id": 39968406, "author": "Gord Thompson", "author_id": 2144390, "author_profile": "https://Stackoverflow.com/users/2144390", "pm_score": 1, "selected": false, "text": "<h2>2016 update (callproc support in pymssql 2.x)</h2>\n\n<p>pymssql v2.x offers limited support for <code>callproc</code>. It supports OUTPUT parameters using the <code>pymssql.output()</code> parameter syntax. Note, however, that OUTPUT parameters can only be retrieved with <code>callproc</code> if the stored procedure does <strong>not</strong> also return a result set. That issue is discussed on GitHub <a href=\"https://github.com/pymssql/pymssql/issues/466\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<h3>For stored procedures that do not return a result set</h3>\n\n<p>Given the T-SQL stored procedure</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE PROCEDURE [dbo].[myDoubler] \n @in int = 0, \n @out int OUTPUT\nAS\nBEGIN\n SET NOCOUNT ON;\n SELECT @out = @in * 2;\nEND\n</code></pre>\n\n<p>the Python code</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>import pymssql\nconn = pymssql.connect(\n host=r'localhost:49242',\n database='myDb',\n autocommit=True\n )\ncrsr = conn.cursor()\n\nsql = \"dbo.myDoubler\"\nparams = (3, pymssql.output(int, 0))\nfoo = crsr.callproc(sql, params)\nprint(foo)\nconn.close()\n</code></pre>\n\n<p>produces the following output</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>(3, 6)\n</code></pre>\n\n<p>Notice that <code>callproc</code> returns the parameter tuple with the OUTPUT parameter value assigned by the stored procedure (<code>foo[1]</code> in this case).</p>\n\n<h3>For stored procedures that return a result set</h3>\n\n<p>If the stored procedure returns one or more result sets <em>and</em> also returns output parameters, we need to use an anonymous code block to retrieve the output parameter value(s):</p>\n\n<p>Stored Procedure:</p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>ALTER PROCEDURE [dbo].[myDoubler] \n @in int = 0, \n @out int OUTPUT\nAS\nBEGIN\n SET NOCOUNT ON;\n SELECT @out = @in * 2;\n -- now let's return a result set, too\n SELECT 'foo' AS thing UNION ALL SELECT 'bar' AS thing;\nEND\n</code></pre>\n\n<p>Python code:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>sql = \"\"\"\\\nDECLARE @out_value INT;\nEXEC dbo.myDoubler @in = %s, @out = @out_value OUTPUT;\nSELECT @out_value AS out_value;\n\"\"\"\nparams = (3,)\ncrsr.execute(sql, params)\nrows = crsr.fetchall()\nwhile rows:\n print(rows)\n if crsr.nextset():\n rows = crsr.fetchall()\n else:\n rows = None\n</code></pre>\n\n<p>Result:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>[('foo',), ('bar',)]\n[(6,)]\n</code></pre>\n" }, { "answer_id": 40631433, "author": "Jaroslaw Matlak", "author_id": 7161851, "author_profile": "https://Stackoverflow.com/users/7161851", "pm_score": 0, "selected": false, "text": "<p>You can try to reformat <code>query</code>:</p>\n\n<pre><code>import pypyodc\n\nconnstring = \"DRIVER=SQL Server;\"\\\n \"SERVER=servername;\"\\\n \"PORT=1043;\"\\\n \"DATABASE=dbname;\"\\\n \"UID=user;\"\\\n \"PWD=pwd\"\n\nconn = pypyodbc.connect(connString)\ncursor = conn.cursor()\n\nquery=\"DECLARE @ivar INT \\r\\n\" \\\n \"DECLARE @svar VARCHAR(MAX) \\r\\n\" \\\n \"EXEC [procedure]\" \\\n \"@par1=?,\" \\\n \"@par2=?,\" \\\n \"@param1=@ivar OUTPUT,\" \\\n \"@param2=@svar OUTPUT \\r\\n\" \\\n \"SELECT @ivar, @svar \\r\\n\"\npar1=0\npar2=0\nparams=[par1, par2]\nresult = cursor.execute(query, params)\nprint result.fetchall()\n</code></pre>\n\n<p>[1]<a href=\"https://amybughunter.wordpress.com/tag/pypyodbc/\" rel=\"nofollow noreferrer\">https://amybughunter.wordpress.com/tag/pypyodbc/</a></p>\n" }, { "answer_id": 40879178, "author": "neolei", "author_id": 423905, "author_profile": "https://Stackoverflow.com/users/423905", "pm_score": 0, "selected": false, "text": "<p>Here's how I did it, the key is to declare output parameter first:</p>\n\n<pre><code>import cx_Oracle as Oracle\n\nconn = Oracle.connect('xxxxxxxx')\ncur = conn.cursor()\n\nidd = cur.var(Oracle.NUMBER)\ncur.execute('begin :idd := seq_inv_turnover_id.nextval; end;', (idd,))\nprint(idd.getvalue())\n</code></pre>\n" }, { "answer_id": 71298476, "author": "Randy Stegner Sr.", "author_id": 12492220, "author_profile": "https://Stackoverflow.com/users/12492220", "pm_score": 0, "selected": false, "text": "<p>I use pyodbc and then convert the pyodbc rows object to a list. Most of the answers show a query declaring variables as part of the query. But I would think you declare your variables as part of the sp, thus eliminating an unnecessary step in python. Then, in python, all you have to do is pass the parameters to fill in those variables.</p>\n<p>Here is the function I use to convert the pyodbc rows object to a usable list (of lists) (note that I have noticed pyodbc sometimes adds trailing spaces, so I account for that which works well for me):</p>\n<pre><code>def convert_pyodbc(pyodbc_lst):\n'''Converts pyodbc rows into usable list of lists (each sql row is a list),\n then examines each list for list elements that are strings,\n removes trailing spaces, and returns a usable list.'''\nusable_lst = []\nfor row in pyodbc_lst:\n e = [elem for elem in row]\n usable_lst.append(e)\nfor i in range(0,len(usable_lst[0])):\n for lst_elem in usable_lst:\n if isinstance(lst_elem[i],str):\n lst_elem[i] = lst_elem[i].rstrip()\nreturn usable_lst\n</code></pre>\n<p>Now if I need to run a stored procedure from python that returns a results set, I simply use:</p>\n<pre><code>strtdate = '2022-02-21'\nstpdate = '2022-02-22'\n\nconn = mssql_conn('MYDB')\ncursor = conn.cursor()\n\nqry = cursor.execute(f&quot;EXEC mystoredprocedure_using_dates \n'{strtdate}','{stpdate}' &quot;)\nresults = convert_pyodbc(qry.fetchall())\n\ncursor.close()\nconn.close()\n</code></pre>\n<p>And sample results which I then take and write to a spreadsheet or w/e:</p>\n<pre><code>[[datetime.date(2022, 2, 21), '723521', 'A Team Line 1', 40, 9], \n[datetime.date(2022, 2, 21), '723522', 'A Team Line 2', 15, 10], \n[datetime.date(2022, 2, 21), '723523', 'A Team Line 3', 1, 5], \n[datetime.date(2022, 2, 21), '723686', 'B Team Line 1', 39, 27], \n[datetime.date(2022, 2, 21), '723687', 'B Team Line 2', 12, 14]]\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13380/" ]
I've googled around a bit, but maybe I didn't put the correct magik incantation into the search box. Does anyone know how to get output parameters from a stored procedure in Python? I'm using pymssql to call a stored procedure, and I'm not sure of the correct syntax to get the output parameter back. I don't think I can use any other db modules since I'm running this from a Linux box to connect to a mssql database on a MS Server. ``` import pymssql con = pymssql.connect(host='xxxxx',user='xxxx',password='xxxxx',database='xxxxx') cur = con.cursor() query = "EXECUTE blah blah blah" cur.execute(query) con.commit() con.close() ```
I'm not a python expert but after a brief perusing of the [DB-API 2.0](http://www.python.org/dev/peps/pep-0249/) I believe you should use the "callproc" method of the cursor like this: ``` cur.callproc('my_stored_proc', (first_param, second_param, an_out_param)) ``` Then you'll have the result in the returned value (of the out param) in the "an\_out\_param" variable.
191,652
<p>I work a lot with serial communications with a variety of devices, and so I often have to analyze hex dumps in log files. Currently, I do this manually by looking at the dumps, looking at the protocol spec, and writing down the results. However, this is tedious and error-prone, especially whem messages contain hundreds of bytes and contain mixtures of big-endian and little-endian data, ASCII, Unicode, compression, CRCs, . . . .</p> <p>I have written a few Python scripts to assist with the more common cases. But there are lots of protocols to deal with, and it doesn't make sense to spend the time writing a custom script unless I know I'll have a lot of dumps to analyze.</p> <p>What I'd like is some sort of utility that can automate this activity. So, for example, if I have a textual hex dump like this:</p> <pre><code>7e ff 00 7b 00 13 86 04 00 41 42 43 44 56 ef 7e </code></pre> <p>and some sort of description of the message format, like this:</p> <pre><code># Field Size Byte Order Output Format Flag 1 hex Address 1 hex Control 1 hex DataType 1 decimal LineIndex 1 decimal PollAddress 2 msb hex DataSize 2 lsb decimal Data (DataSize) ascii CRC 2 lsb hex Flag 1 hex </code></pre> <p>I'd get output like this:</p> <pre><code>Flag 0x7e Address 0xff Control 0x00 DataType 123 LineIndex 0 PollAddress 0x1386 DataSize 4 Data "ABCD" CRC 0xef56 Flag 0x7e </code></pre> <p>Hardware-based protocol analyzers often have fancy features for doing this kind of thing, but I need to work with textual log files.</p> <p>Does any such utility or library exist?</p> <hr> <p>Some good answers have come up since I set up the bounty. I guess bounties work!</p> <p>Wireshark and HexEdit both look promising; I'll take a look at those, and will proabably award the bounty to whichever one suits my needs. But I'm still open to other ideas.</p>
[ { "answer_id": 191659, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 0, "selected": false, "text": "<p>I'm pretty sure I saw something like that on CPAN. I could be more vague if you like. :-)</p>\n\n<p><strong>Update:</strong> It's not exactly what you want, but have a look at <a href=\"http://cpan.uwinnipeg.ca/htdocs/Parse-Binary/Parse/Binary/FixedFormat.html\" rel=\"nofollow noreferrer\">Parse::Binary::FixedFormat</a></p>\n" }, { "answer_id": 517032, "author": "iny", "author_id": 27067, "author_profile": "https://Stackoverflow.com/users/27067", "pm_score": 3, "selected": true, "text": "<p><a href=\"http://www.wireshark.org/\" rel=\"nofollow noreferrer\">Wireshark</a> is quite good at opening network protocols.</p>\n" }, { "answer_id": 517047, "author": "Bill Perkins", "author_id": 59515, "author_profile": "https://Stackoverflow.com/users/59515", "pm_score": 1, "selected": false, "text": "<p>Typically, I use emacs hexl-mode to view binary files as a \"text-dump\". When I need more specific output, I just do as you and write a parser in C++.</p>\n" }, { "answer_id": 517245, "author": "James Caccese", "author_id": 23581, "author_profile": "https://Stackoverflow.com/users/23581", "pm_score": 1, "selected": false, "text": "<p>In my job we were designing network and serial protocols to control embedded hardware. I also got tired of reading dumps wrong, and writing scripts for each protocol, so I wrote a library to do exactly what you describe. You could give it a text file description of the protocol, and it had a gui supporting check boxes for setting single bits, radio buttons for choosing between the valid combinations of bits, and drop-down lists when there were a lot of choices. You could edit the hex view of the data, the binary view of each field, or even point and click at the fields, and all the other views would update. It saved us a ton of time. It's a little quick and dirty, but I'd post it if it wasn't owned by my employer. The point is, it wasn't very hard to write, and once I went away from scripts for each protocol and to one program that could understand a description of the protocol, things were great. We stopped screw ups relating to misreading a dump, and adding new protocols became trivial. Plus the textual description of the protocol went straight into the development specs so the software guys would know what to do with the hardware. I encourage you to take a crack at it.</p>\n" }, { "answer_id": 517875, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 2, "selected": false, "text": "<p>I suppose you need a good hex editor. Have a look at <a href=\"http://expertcomsoft.com/\" rel=\"nofollow noreferrer\">hexedit</a>. I have used the free version in the past and it is good, but I don't know if it offers what you are looking for. Basically you want to be able to define a struct and then be able to decode hex data against it. I suppose a good hex editor would support this. Check the paid version of HexEdit or google for another editor; there are many available.</p>\n" }, { "answer_id": 519444, "author": "Vatine", "author_id": 34771, "author_profile": "https://Stackoverflow.com/users/34771", "pm_score": 1, "selected": false, "text": "<p>One possible starting point would be <a href=\"http://nmedit.sourceforge.net/subprojects/libpdl.html\" rel=\"nofollow noreferrer\">libPDL</a>, a C++ library.</p>\n\n<p>Another option may be <a href=\"http://www.nbee.org/doku.php?id=netpdl:index\" rel=\"nofollow noreferrer\">NetPDL</a>.</p>\n" }, { "answer_id": 519616, "author": "Zac Thompson", "author_id": 58549, "author_profile": "https://Stackoverflow.com/users/58549", "pm_score": 1, "selected": false, "text": "<p>You should use the <a href=\"http://www.tcl.tk/man/tcl8.5/TclCmd/binary.htm\" rel=\"nofollow noreferrer\">Tcl binary</a> commands for stuff like this. What follows is the starting point for your example above. Tcl is really easy to learn and write scripts in. If you're doing serial comm stuff you owe it to yourself to learn at least the basics.</p>\n\n<pre><code>bash$ tclsh\n% binary scan [binary format H* 7eff007b00138604004142434456ef7e] \\\n H2H2H2ccH4sa4h4H2 \\\n flag1 addr ctl datatype lineidx polladdr datasize data crc flag2\n10\n% puts \"$flag1 $addr $ctl $datatype $lineidx \\\n $polladdr $datasize $data $crc $flag2\"\n7e ff 00 123 0 1386 4 ABCD 65fe 7e\n</code></pre>\n\n<p>When you did your byte-order stuff you switched around the bytes but not the bits, so I'm not really sure what you were looking for there. Anyway, this will get you started.</p>\n" }, { "answer_id": 523244, "author": "Charles Faiga", "author_id": 17560, "author_profile": "https://Stackoverflow.com/users/17560", "pm_score": 1, "selected": false, "text": "<p>Have a look at <a href=\"http://www.hexworkshop.com\" rel=\"nofollow noreferrer\">hexworkshop</a> </p>\n\n<p>I have been using it for years to analyze hex dumps. It has a structure Viewer that lets you define data structure a in C/C++ style and then displays the data in that format.</p>\n" }, { "answer_id": 523265, "author": "nobody", "author_id": 19405, "author_profile": "https://Stackoverflow.com/users/19405", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.x-ways.net/winhex/\" rel=\"nofollow noreferrer\">WinHex</a> supports displaying/editing user-defined record formats. There are some examples at <a href=\"http://www.x-ways.net/winhex/templates/index.html\" rel=\"nofollow noreferrer\"><a href=\"http://www.x-ways.net/winhex/templates/index.html\" rel=\"nofollow noreferrer\">http://www.x-ways.net/winhex/templates/index.html</a></a></p>\n" }, { "answer_id": 43699453, "author": "Pedro Gimeno", "author_id": 2428487, "author_profile": "https://Stackoverflow.com/users/2428487", "pm_score": 0, "selected": false, "text": "<p>There is a BSD command-line utility called <code>hexdump</code> that does this through the use of format strings (which can be in an external file). See <a href=\"https://www.suse.com/communities/blog/making-sense-hexdump/\" rel=\"nofollow noreferrer\">https://www.suse.com/communities/blog/making-sense-hexdump/</a> for an intro, and e.g. <a href=\"https://www.freebsd.org/cgi/man.cgi?query=hexdump&amp;sektion=1\" rel=\"nofollow noreferrer\">https://www.freebsd.org/cgi/man.cgi?query=hexdump&amp;sektion=1</a> for the manual page (with special attention to the <code>-e</code> and <code>-f</code> options and the section titled <strong>Formats</strong>).</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175/" ]
I work a lot with serial communications with a variety of devices, and so I often have to analyze hex dumps in log files. Currently, I do this manually by looking at the dumps, looking at the protocol spec, and writing down the results. However, this is tedious and error-prone, especially whem messages contain hundreds of bytes and contain mixtures of big-endian and little-endian data, ASCII, Unicode, compression, CRCs, . . . . I have written a few Python scripts to assist with the more common cases. But there are lots of protocols to deal with, and it doesn't make sense to spend the time writing a custom script unless I know I'll have a lot of dumps to analyze. What I'd like is some sort of utility that can automate this activity. So, for example, if I have a textual hex dump like this: ``` 7e ff 00 7b 00 13 86 04 00 41 42 43 44 56 ef 7e ``` and some sort of description of the message format, like this: ``` # Field Size Byte Order Output Format Flag 1 hex Address 1 hex Control 1 hex DataType 1 decimal LineIndex 1 decimal PollAddress 2 msb hex DataSize 2 lsb decimal Data (DataSize) ascii CRC 2 lsb hex Flag 1 hex ``` I'd get output like this: ``` Flag 0x7e Address 0xff Control 0x00 DataType 123 LineIndex 0 PollAddress 0x1386 DataSize 4 Data "ABCD" CRC 0xef56 Flag 0x7e ``` Hardware-based protocol analyzers often have fancy features for doing this kind of thing, but I need to work with textual log files. Does any such utility or library exist? --- Some good answers have come up since I set up the bounty. I guess bounties work! Wireshark and HexEdit both look promising; I'll take a look at those, and will proabably award the bounty to whichever one suits my needs. But I'm still open to other ideas.
[Wireshark](http://www.wireshark.org/) is quite good at opening network protocols.
191,690
<p>I have a table, we'll call <code>Users</code>. This table has a single primary key defined in SQL Server - an autoincrement <code>int ID</code>.</p> <p>Sometimes, my LINQ queries against this table fail with an <code>"Index was outside the range"</code> error - even the most simplest of queries. The query itself doesn't use any indexers.</p> <p>For example: </p> <pre><code>User = Users.Take(1); </code></pre> <p>or</p> <pre><code>IEnumerable&lt;Users&gt; = Users.ToList(); </code></pre> <p>Both of the queries threw the same error. Using the debugger Visualizer to look at the generated query - I copy and paste the query in SQL and it works fine. I also click "execute" on the visualizer and it works fine. But executing the code by itself throws this error. I don't implement any of the partial methods on the class, so nothing is happening there. If I restart my debugger, the problem goes away, only to rear it's head again randomly a few hours later. More critically, I see this bug in my error logs from the app running in production. </p> <p>I do a ton of LINQ in my app, against a dozen or so different entities in my database, but I only see this problem on queries related to a specific entity in my table. Some googling has suggested that this problem might be related to an incorrect relationship specified between my model and another entity, but I don't have <em>any</em> relationships with this object. It seems to be working 95% of the time, it's just the other 5% that fail.</p> <p>I have completely deleted the object from the designer, and re-added it from a "refreshed" server browser, and that did not fix the problem.</p> <p>Any ideas what's going on here?</p> <p>Here's the full error message and stack trace:</p> <blockquote> <p>Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) at System.Data.Linq.Table<code>1.System.Linq.IQueryProvider.Execute[TResult](Expression expression) at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable</code>1 source, Expression`1 predicate) at MyProject.FindUserByType(String typeId)</p> </blockquote> <p>EDIT: As requested, below is a copy of the table schema.</p> <pre><code>CREATE TABLE [dbo].[Container]( [ID] [int] IDENTITY(1,1) NOT NULL, [MarketCode] [varchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [Description] [varchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [Capacity] [int] NOT NULL, [Volume] [float] NOT NULL CONSTRAINT [PK_Container] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] </code></pre> <p>EDIT: The stack trace shows <code>FirstOrDefault</code>, but I duplicated the error using both <code>Take()</code> and <code>ToList()</code>. The stack trace is identical between all of these, simply interchangnig <code>FirstOrDefault/Take/ToList</code>. The move down the stack to <code>SqlProvider.Execute</code> is in fact identical. </p>
[ { "answer_id": 192720, "author": "Dan Goldstein", "author_id": 23427, "author_profile": "https://Stackoverflow.com/users/23427", "pm_score": 0, "selected": false, "text": "<p>The exception occurs in a System library and your story makes me think the problem isn't in your code. Has the schema changed recently? Is your mapping correct?</p>\n" }, { "answer_id": 193327, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 1, "selected": false, "text": "<p>I would say that you've got a model -> database mismatch somewhere. When I get as desperate as you on situations like this, I usually fire up VS.NET, create a new console app, and rebuild the section of the DBML which references the entity of interest in this query, and re-run. You may find that in this sort of isolation, the query works. Did you customize any of your entity definitions by filling out partial methods, especially the ones that fire on creation? </p>\n" }, { "answer_id": 1229023, "author": "Mark", "author_id": 64084, "author_profile": "https://Stackoverflow.com/users/64084", "pm_score": 3, "selected": false, "text": "<p>This almost certainly won't be everyone's root cause, but I encountered this exact same exception in my project - and found that the root cause was that an exception was being thrown during construction of an entity class. Oddly, the true exception is \"lost\" and instead manifests as an ArgumentOutOfRange exception originating at the iterator of the Linq statement that retrieves the object/s. </p>\n\n<p>If you are receiving this error and you have introduced OnCreated or OnLoaded methods on your POCOs, try stepping through those methods. </p>\n" }, { "answer_id": 17271014, "author": "hassan", "author_id": 2515487, "author_profile": "https://Stackoverflow.com/users/2515487", "pm_score": 0, "selected": false, "text": "<p>This Problem Occurs due to linq object and Database fields of that Table are not identical.</p>\n" }, { "answer_id": 35437037, "author": "Nick Niebling", "author_id": 1095493, "author_profile": "https://Stackoverflow.com/users/1095493", "pm_score": 0, "selected": false, "text": "<p>I had this Issue as well and solved it.</p>\n\n<p>Now I understand the error was wrong usage of Linq Data Context, but maybe my experience can still help others understand why they get this error.</p>\n\n<p>Linq Data Context is not meant for running simultaneously. Therefore creating multiple tasks running async is not ideal. Inspect following sample code to understand the issue:</p>\n\n<pre><code>using(var ctx = new LinqDataContext())\n{\n List&lt;Task&gt; tasks = new List&lt;Task&gt;();\n for(int i=0;i&lt;1000;i++)\n {\n var task = Task.Run(() =&gt; {\n var customer = ctx.Customers.SingleOrDefault(o =&gt; o.Id == i);\n customer.DoSomething();\n }\n tasks.Add(task);\n }\n Task.WaitAll(tasks);\n}\n</code></pre>\n\n<p>In my scenario, I was passing the data context as a parameter in a longer call stack, and calling async methods along the way. So it wasn't as obvious as above example. But maybe this can help someone else anyhow :-)</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17803/" ]
I have a table, we'll call `Users`. This table has a single primary key defined in SQL Server - an autoincrement `int ID`. Sometimes, my LINQ queries against this table fail with an `"Index was outside the range"` error - even the most simplest of queries. The query itself doesn't use any indexers. For example: ``` User = Users.Take(1); ``` or ``` IEnumerable<Users> = Users.ToList(); ``` Both of the queries threw the same error. Using the debugger Visualizer to look at the generated query - I copy and paste the query in SQL and it works fine. I also click "execute" on the visualizer and it works fine. But executing the code by itself throws this error. I don't implement any of the partial methods on the class, so nothing is happening there. If I restart my debugger, the problem goes away, only to rear it's head again randomly a few hours later. More critically, I see this bug in my error logs from the app running in production. I do a ton of LINQ in my app, against a dozen or so different entities in my database, but I only see this problem on queries related to a specific entity in my table. Some googling has suggested that this problem might be related to an incorrect relationship specified between my model and another entity, but I don't have *any* relationships with this object. It seems to be working 95% of the time, it's just the other 5% that fail. I have completely deleted the object from the designer, and re-added it from a "refreshed" server browser, and that did not fix the problem. Any ideas what's going on here? Here's the full error message and stack trace: > > Index was out of range. Must be non-negative and less than the size of > the collection. Parameter name: index at > System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, > QueryInfo queryInfo, IObjectReaderFactory factory, Object[] > parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object > lastResult) at > System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, > QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] > userArguments, ICompiledSubQuery[] subQueries) at > System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression > query) at > System.Data.Linq.Table`1.System.Linq.IQueryProvider.Execute[TResult](Expression > expression) at > System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source, > Expression`1 predicate) at MyProject.FindUserByType(String typeId) > > > EDIT: As requested, below is a copy of the table schema. ``` CREATE TABLE [dbo].[Container]( [ID] [int] IDENTITY(1,1) NOT NULL, [MarketCode] [varchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [Description] [varchar](max) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL, [Capacity] [int] NOT NULL, [Volume] [float] NOT NULL CONSTRAINT [PK_Container] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] ``` EDIT: The stack trace shows `FirstOrDefault`, but I duplicated the error using both `Take()` and `ToList()`. The stack trace is identical between all of these, simply interchangnig `FirstOrDefault/Take/ToList`. The move down the stack to `SqlProvider.Execute` is in fact identical.
This almost certainly won't be everyone's root cause, but I encountered this exact same exception in my project - and found that the root cause was that an exception was being thrown during construction of an entity class. Oddly, the true exception is "lost" and instead manifests as an ArgumentOutOfRange exception originating at the iterator of the Linq statement that retrieves the object/s. If you are receiving this error and you have introduced OnCreated or OnLoaded methods on your POCOs, try stepping through those methods.
191,692
<p>Is there a method to get all of the .aspx files in my website? Maybe iterate through the site's file structure and add to an array?</p>
[ { "answer_id": 191696, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 1, "selected": false, "text": "<p>using Directory.GetFiles(\"*.aspx\"), you can get all the files in the directory. And you can make it recursive to grab any sub directories and their files.</p>\n" }, { "answer_id": 191702, "author": "Shawn Miller", "author_id": 247, "author_profile": "https://Stackoverflow.com/users/247", "pm_score": 4, "selected": true, "text": "<pre><code>Directory.GetFiles(HttpContext.Current.Server.MapPath(@\"/\"), \"*.aspx\", SearchOption.AllDirectories);\n</code></pre>\n" }, { "answer_id": 191719, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 1, "selected": false, "text": "<p>Keep in mind that you can define an .aspx page without having an actual file be there in the web.config.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
Is there a method to get all of the .aspx files in my website? Maybe iterate through the site's file structure and add to an array?
``` Directory.GetFiles(HttpContext.Current.Server.MapPath(@"/"), "*.aspx", SearchOption.AllDirectories); ```
191,697
<p>In our industrial automation application, we need to capture and display the data in the milliseconds.</p> <p>We have data binding between data grid control and a DataTable object. We have around three hundred records which needs to be display in the grid. So we update the 300 records every time we get the records. </p> <p>Example </p> <pre><code> TabularViewTable tvt = _presenter.WorkItem.Items.Get&lt;TabularViewTable&gt; ("TabularViewTable"); foreach (DataRow row in tvt.Rows) { row["Value"] = GetDataFast(row["Name"]); } </code></pre> <p>After connecting 10 devices, the CPU usage goes 15%. How to improve the performance using DataTable or using some custom data source</p> <p>Regards,</p> <p>Krishgy</p>
[ { "answer_id": 191758, "author": "zendar", "author_id": 25732, "author_profile": "https://Stackoverflow.com/users/25732", "pm_score": 2, "selected": false, "text": "<p>You should seriously reconsider your user interface:</p>\n\n<ul>\n<li>Is it really necessary to display 300 values? Ordinary human cannot concentrate on more than 7 things simultaneously,</li>\n<li>Even if you lower number of parameters, there is frequency of refresh that seems to high to be practical.</li>\n</ul>\n\n<p>You probably should do following:</p>\n\n<ul>\n<li>create a dashboard with graphical representation of most important data (graphs, gauges, ...) </li>\n<li>create drill down forms and reports, so that user can see what happened with system in any given period</li>\n</ul>\n" }, { "answer_id": 859288, "author": "runxc1 Bret Ferrier", "author_id": 30850, "author_profile": "https://Stackoverflow.com/users/30850", "pm_score": 0, "selected": false, "text": "<p>For starters you need to switch from a DataTable to a DataReader as it is much faster. Secondly I would look at a Lazy Loading architecture. Bind 50 entries and when they scroll to the bottom Bind/Load another 50.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
In our industrial automation application, we need to capture and display the data in the milliseconds. We have data binding between data grid control and a DataTable object. We have around three hundred records which needs to be display in the grid. So we update the 300 records every time we get the records. Example ``` TabularViewTable tvt = _presenter.WorkItem.Items.Get<TabularViewTable> ("TabularViewTable"); foreach (DataRow row in tvt.Rows) { row["Value"] = GetDataFast(row["Name"]); } ``` After connecting 10 devices, the CPU usage goes 15%. How to improve the performance using DataTable or using some custom data source Regards, Krishgy
You should seriously reconsider your user interface: * Is it really necessary to display 300 values? Ordinary human cannot concentrate on more than 7 things simultaneously, * Even if you lower number of parameters, there is frequency of refresh that seems to high to be practical. You probably should do following: * create a dashboard with graphical representation of most important data (graphs, gauges, ...) * create drill down forms and reports, so that user can see what happened with system in any given period
191,704
<p>I want to use regular expressions (Perl compatible) to be able to find a pattern surrounded by two other patterns, but not include the strings matching the surrounding patterns in the match.</p> <p>For example, I want to be able to find occurrences of strings like:</p> <blockquote> <p>Foo Bar Baz</p> </blockquote> <p>But only have the match include the middle part:</p> <blockquote> <p>Bar</p> </blockquote> <p>I know this is possible, but I can't remember how to do it.</p>
[ { "answer_id": 191724, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": false, "text": "<p>Parentheses define the groupings.</p>\n\n<pre><code>\"Foo (Bar) Baz\"\n</code></pre>\n\n<p>Example</p>\n\n<pre><code>~&gt; cat test.pl\n$a = \"The Foo Bar Baz was lass\";\n\n$a =~ m/Foo (Bar) Baz/;\n\nprint $1,\"\\n\";\n~&gt; perl test.pl\nBar\n</code></pre>\n" }, { "answer_id": 191727, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "<p>Use <a href=\"http://www.regular-expressions.info/lookaround.html\" rel=\"nofollow noreferrer\">lookaround</a>:</p>\n\n<pre><code>(?&lt;=Foo\\s)Bar(?=\\sBaz)\n</code></pre>\n\n<p>This would match any \"Bar\" that is preceded by \"Foo\" and followed by \"Baz\", separated through a single white space. \"Foo\" and \"Baz\" would not be part of the final match.</p>\n" }, { "answer_id": 191731, "author": "Cervo", "author_id": 16219, "author_profile": "https://Stackoverflow.com/users/16219", "pm_score": 2, "selected": false, "text": "<p>$string =~ m/Foo (Bar) Baz/</p>\n\n<p>$1</p>\n\n<p>This may not be exactly what you want as the match is still \"Foo Bar Baz\". But it shows you how to just get the part that you are interested in. Otherwise you can use lookahead and lookbehind to get the match without consuming characters...</p>\n" }, { "answer_id": 192894, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 3, "selected": true, "text": "<p>In the general case, you probably can't. The simplest approach is to match everything and use backreferences to capture the portion of interest:</p>\n\n<pre><code>Foo\\s+(Bar)\\s+Baz\n</code></pre>\n\n<p>This isn't the same as not including the surrounding text in the match though. That probably doesn't matter if all you want to do is extract \"Bar\" but would matter if you're matching against the same string multiple times and need to continue from where the previous match left off.</p>\n\n<p>Look-around will work in some cases. Tomalak's suggestion:</p>\n\n<pre><code>(?&lt;=Foo\\s)Bar(?=\\sBaz)\n</code></pre>\n\n<p>only works for fixed width look-behind (at least in Perl). As of Perl 5.10, the <code>\\K</code> assertion can be used to effectively provide variable width look-behind:</p>\n\n<pre><code>Foo\\s+\\KBar(?=\\s+Baz)\n</code></pre>\n\n<p>which should be capable of doing what you asked for in all cases, but would require that you're implementing this in Perl 5.10.</p>\n\n<p>While it would be convenient, there's no equivalent of <code>\\K</code> for ending the matched text, so you have to use a look-ahead.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4849/" ]
I want to use regular expressions (Perl compatible) to be able to find a pattern surrounded by two other patterns, but not include the strings matching the surrounding patterns in the match. For example, I want to be able to find occurrences of strings like: > > Foo Bar Baz > > > But only have the match include the middle part: > > Bar > > > I know this is possible, but I can't remember how to do it.
In the general case, you probably can't. The simplest approach is to match everything and use backreferences to capture the portion of interest: ``` Foo\s+(Bar)\s+Baz ``` This isn't the same as not including the surrounding text in the match though. That probably doesn't matter if all you want to do is extract "Bar" but would matter if you're matching against the same string multiple times and need to continue from where the previous match left off. Look-around will work in some cases. Tomalak's suggestion: ``` (?<=Foo\s)Bar(?=\sBaz) ``` only works for fixed width look-behind (at least in Perl). As of Perl 5.10, the `\K` assertion can be used to effectively provide variable width look-behind: ``` Foo\s+\KBar(?=\s+Baz) ``` which should be capable of doing what you asked for in all cases, but would require that you're implementing this in Perl 5.10. While it would be convenient, there's no equivalent of `\K` for ending the matched text, so you have to use a look-ahead.
191,732
<p>I'm passing /file:c:\myfile.doc and I'm getting back "/file:c:\myfile.doc" instead of "C:\myfile.doc", could someone please advise where I am going wrong?</p> <pre><code> if (entry.ToUpper().IndexOf("FILE") != -1) { //override default log location MyFileLocation = entry.Split(new char[] {'='})[1]; } </code></pre>
[ { "answer_id": 191743, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": false, "text": "<p>You are splitting on \"=\" instead of \":\"</p>\n\n<p>Try </p>\n\n<pre><code> if (entry.ToUpper().IndexOf(\"FILE:\") == 0)\n {\n //override default log location\n MyFileLocation location = entry.Split(new char[] {':'},2)[1];\n }\n</code></pre>\n" }, { "answer_id": 191752, "author": "Craig", "author_id": 2894, "author_profile": "https://Stackoverflow.com/users/2894", "pm_score": 0, "selected": false, "text": "<p>You could also just lop off the 'file:' part. It is clearly defined and will be constant so it isn't THAT bad. Not great, but not horrible.</p>\n" }, { "answer_id": 191764, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 0, "selected": false, "text": "<p>Here is a good example of a <a href=\"http://www.codeproject.com/KB/recipes/yaclap.aspx\" rel=\"nofollow noreferrer\">command line argument parser</a>.</p>\n" }, { "answer_id": 191768, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 2, "selected": false, "text": "<p>The easiest way to do this is to just take a substring. Since you are reading this from the command line, the \"/file:\" portion will always be consistent.</p>\n\n<pre><code>entry.Substring(6);\n</code></pre>\n\n<p>This will return everything after the \"/file:\".</p>\n" }, { "answer_id": 191772, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "<p>The code you've posted would require the argument <code>/file=c:\\myfile.doc</code>.</p>\n\n<p>Either use that as the parameter or split on the colon (<strong>:</strong>) instead of equals (<strong>=</strong>).</p>\n" }, { "answer_id": 191839, "author": "Carl", "author_id": 951280, "author_profile": "https://Stackoverflow.com/users/951280", "pm_score": 1, "selected": false, "text": "<p>Not an answer as I think it's been answered well enough already, but as you stated that you're a beginner I thought that I would point out that:</p>\n\n<pre><code>entry.split(new char[]{':'});\n</code></pre>\n\n<p>can be:</p>\n\n<pre><code>entry.split(':');\n</code></pre>\n\n<p>This uses:</p>\n\n<pre><code>split(params char[] separator);\n</code></pre>\n\n<p>This can be deceiving for new C# programmers as the params keyword means that you can actually pass in 1 to many chars, as in:</p>\n\n<pre><code>entry.split(':','.',' ');\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm passing /file:c:\myfile.doc and I'm getting back "/file:c:\myfile.doc" instead of "C:\myfile.doc", could someone please advise where I am going wrong? ``` if (entry.ToUpper().IndexOf("FILE") != -1) { //override default log location MyFileLocation = entry.Split(new char[] {'='})[1]; } ```
You are splitting on "=" instead of ":" Try ``` if (entry.ToUpper().IndexOf("FILE:") == 0) { //override default log location MyFileLocation location = entry.Split(new char[] {':'},2)[1]; } ```
191,740
<p>I'm using SqlServer for the first time, and in every single one of our create procedure scripts there is a block of code like below to remove the procedure if it already exists:</p> <pre><code>IF EXISTS (SELECT * FROM information_schema.routines WHERE routine_name = 'SomeProcedureName' AND routine_type = 'PROCEDURE' BEGIN DROP PROCEDURE SomeProcedureName END //then the procedure definition </code></pre> <p>To stop cutting and pasting this boilerplate code in every file I would like to put this code in its own stored procedure so that instead the scripts would look like this:</p> <pre><code>DropIfRequired('SomeProcedureName') //then the procedure definition </code></pre> <p>My attempt at a solution is:</p> <pre><code>CREATE PROCEDURE DropIfRequired ( @procedureName varchar ) AS IF EXISTS (SELECT * FROM information_schema.routines WHERE routine_name = @procedureName AND routine_type = 'PROCEDURE') BEGIN DROP PROCEDURE @procedureName END </code></pre> <p>But I then get the following error:</p> <p>Msg 102, Level 15, State 1, Procedure DeleteProcedure, Line 10 Incorrect syntax near '@procedureName'.</p> <p>Any ideas how to do what I want?</p>
[ { "answer_id": 191753, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 2, "selected": false, "text": "<p>its missing quotes, try adding them in with an exec statement.</p>\n\n<pre><code>EXEC( 'DROP PROCEDURE ''' + @procName + '''') ( all single quotes)\n</code></pre>\n" }, { "answer_id": 191773, "author": "Cervo", "author_id": 16219, "author_profile": "https://Stackoverflow.com/users/16219", "pm_score": 4, "selected": true, "text": "<p>The full answer is:\n<PRE>\nDECLARE @SQL VARCHAR(8000)\nSELECT @SQL = 'USE ' + DB_NAME() + CHAR(10)\nSET @SQL = @SQL + 'DROP PROCEDURE ' + @procName\n--PRINT @SQL\nEXEC(@SQL)\n</PRE></p>\n\n<p>The one given by Andrew will only work if the default database for your login is set to the database you want. When using dynamic sql you get a new database context. So if you do not have a default database set you will execute the command from master.</p>\n" }, { "answer_id": 191793, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 2, "selected": false, "text": "<p>One thing to note is that in the DropIfRequired procedure, you have defined the procedure name as follows:</p>\n\n<pre><code>CREATE PROCEDURE DropIfRequired\n( \n @procedureName varchar\n)\n</code></pre>\n\n<p>You need to define a length of the varchar parameter, otherwise SQL will assume a length of one character. Instead, do something like as follows (1000 should be more than enough for most procedure names)</p>\n\n<pre><code>CREATE PROCEDURE DropIfRequired\n( \n @procedureName varchar(1000)\n)\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24063/" ]
I'm using SqlServer for the first time, and in every single one of our create procedure scripts there is a block of code like below to remove the procedure if it already exists: ``` IF EXISTS (SELECT * FROM information_schema.routines WHERE routine_name = 'SomeProcedureName' AND routine_type = 'PROCEDURE' BEGIN DROP PROCEDURE SomeProcedureName END //then the procedure definition ``` To stop cutting and pasting this boilerplate code in every file I would like to put this code in its own stored procedure so that instead the scripts would look like this: ``` DropIfRequired('SomeProcedureName') //then the procedure definition ``` My attempt at a solution is: ``` CREATE PROCEDURE DropIfRequired ( @procedureName varchar ) AS IF EXISTS (SELECT * FROM information_schema.routines WHERE routine_name = @procedureName AND routine_type = 'PROCEDURE') BEGIN DROP PROCEDURE @procedureName END ``` But I then get the following error: Msg 102, Level 15, State 1, Procedure DeleteProcedure, Line 10 Incorrect syntax near '@procedureName'. Any ideas how to do what I want?
The full answer is: ``` DECLARE @SQL VARCHAR(8000) SELECT @SQL = 'USE ' + DB_NAME() + CHAR(10) SET @SQL = @SQL + 'DROP PROCEDURE ' + @procName --PRINT @SQL EXEC(@SQL) ``` The one given by Andrew will only work if the default database for your login is set to the database you want. When using dynamic sql you get a new database context. So if you do not have a default database set you will execute the command from master.
191,746
<p>Given the following HTML:</p> <pre><code>&lt;select name="my_dropdown" id="my_dropdown"&gt; &lt;option value="1"&gt;displayed text 1&lt;/option&gt; &lt;/select&gt; </code></pre> <p>How do I grab the string "displayed text 1" using Javascript/the DOM?</p>
[ { "answer_id": 191755, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 1, "selected": false, "text": "<p>The displayed text is a child node of the option node. You can use:</p>\n\n<pre><code>myOptionNode.childNodes[0];\n</code></pre>\n\n<p>to access it, assuming the text node is the only thing inside the option (and not other tags).</p>\n\n<p><strong>EDIT:</strong> Oh yeah, as others mentioned, I completely forgot about:</p>\n\n<pre><code>myOptionNode.text;\n</code></pre>\n" }, { "answer_id": 191767, "author": "Liam", "author_id": 18333, "author_profile": "https://Stackoverflow.com/users/18333", "pm_score": 4, "selected": true, "text": "<pre><code>var sel = document.getElementById(\"my_dropdown\");\n\n//get the selected option\nvar selectedText = sel.options[sel.selectedIndex].text;\n\n//or get the first option\nvar optionText = sel.options[0].text;\n\n//or get the option with value=\"1\"\nfor(var i=0; i&lt;sel.options.length; i++){\n if(sel.options[i].value == \"1\"){\n var valueIsOneText = sel.options[i].text;\n }\n}\n</code></pre>\n" }, { "answer_id": 191778, "author": "Joe Scylla", "author_id": 25771, "author_profile": "https://Stackoverflow.com/users/25771", "pm_score": 2, "selected": false, "text": "<pre><code>var mySelect = document.forms[\"my_form\"].my_dropdown;\n// or if you select has a id\nvar mySelect = document.getElementById(\"my_dropdown\");\nvar text = mySelect.options[mySelect.selectedIndex].text;\n</code></pre>\n" }, { "answer_id": 191804, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 0, "selected": false, "text": "<p>If you were using <a href=\"http://www.prototypejs.org\" rel=\"nofollow noreferrer\">Prototype</a>, you could get at it like this:</p>\n\n<pre><code>$$('#my_dropdown option[value=1]').each( function(elem){\n alert(elem.text);\n });\n</code></pre>\n\n<p>The above is using a CSS selector that says find all <strong>option</strong> tags with <strong>value=\"1\"</strong> that are inside the element that has <strong>id=\"my_dropdown\"</strong>.</p>\n" }, { "answer_id": 191820, "author": "Leanan", "author_id": 22390, "author_profile": "https://Stackoverflow.com/users/22390", "pm_score": 1, "selected": false, "text": "<p>Assuming you modified your code a bit to have an id / class on the and were using jQuery you could have something like the following. It will pop up an alert for each option with the text of the option. You probably won't want to alert for all the text, but it illustrates how to get at the text in the first place:</p>\n\n<pre>\n$('select#id option').each(function() {\n alert($(this).text());\n});\n</pre>\n\n<p>If you use a class instead of an id, then you'd just have to change the 'select#id' to 'select.class'. If you didn't want to add a class/id there are other ways to get at the select.</p>\n\n<p>I leave figuring those ways out if you want to go that route as an activity for the reader.</p>\n" }, { "answer_id": 192176, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "<p>Assuming you want the <strong>selected</strong> option's text:</p>\n\n<pre><code>var select = document.getElementById('my_dropdown');\nfor(var i = 0; i &lt; select.options.length; i++) {\n if(select.options[i].selected) {\n break;\n }\n}\nvar selectText = select.options[i].text;\n</code></pre>\n\n<p>In Prototype:</p>\n\n<pre><code>var selectText = $$('#my_dropdown option[selected]')[0].text;\n</code></pre>\n\n<p>Edit: And jQuery for completeness' sake (assuming jQuery's CSS selector support is roughly equivalent to that of Prototype's):</p>\n\n<pre><code>var selectText = $('#my_dropdown option[selected]').get(0).text;\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26848/" ]
Given the following HTML: ``` <select name="my_dropdown" id="my_dropdown"> <option value="1">displayed text 1</option> </select> ``` How do I grab the string "displayed text 1" using Javascript/the DOM?
``` var sel = document.getElementById("my_dropdown"); //get the selected option var selectedText = sel.options[sel.selectedIndex].text; //or get the first option var optionText = sel.options[0].text; //or get the option with value="1" for(var i=0; i<sel.options.length; i++){ if(sel.options[i].value == "1"){ var valueIsOneText = sel.options[i].text; } } ```
191,757
<p>I thought this would be really simple, but it's presenting some difficulties. If I have</p> <pre><code>std::string name = &quot;John&quot;; int age = 21; </code></pre> <p>How do I combine them to get a single string <code>&quot;John21&quot;</code>?</p>
[ { "answer_id": 191775, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 2, "selected": false, "text": "<p>Common Answer: <a href=\"http://www.cplusplus.com/reference/clibrary/cstdlib/itoa.html\" rel=\"nofollow noreferrer\">itoa()</a></p>\n\n<p>This is bad. <code>itoa</code> is non-standard, as pointed out <a href=\"https://stackoverflow.com/questions/190229/where-is-the-itoa-function-in-linux\">here</a>. </p>\n" }, { "answer_id": 191776, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 6, "selected": false, "text": "<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;sstream&gt;\nusing namespace std;\nstring itos(int i) // convert int to string\n{\n stringstream s;\n s &lt;&lt; i;\n return s.str();\n}\n</code></pre>\n\n<p>Shamelessly stolen from <a href=\"http://www.research.att.com/~bs/bs_faq2.html\" rel=\"noreferrer\">http://www.research.att.com/~bs/bs_faq2.html</a>.</p>\n" }, { "answer_id": 191780, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 6, "selected": false, "text": "<pre><code>#include &lt;iostream&gt;\n#include &lt;sstream&gt;\n\nstd::ostringstream o;\no &lt;&lt; name &lt;&lt; age;\nstd::cout &lt;&lt; o.str();\n</code></pre>\n" }, { "answer_id": 191785, "author": "Jay Conrod", "author_id": 1891, "author_profile": "https://Stackoverflow.com/users/1891", "pm_score": 7, "selected": false, "text": "<p>If you have Boost, you can convert the integer to a string using <code>boost::lexical_cast&lt;std::string&gt;(age)</code>.</p>\n\n<p>Another way is to use stringstreams:</p>\n\n<pre><code>std::stringstream ss;\nss &lt;&lt; age;\nstd::cout &lt;&lt; name &lt;&lt; ss.str() &lt;&lt; std::endl;\n</code></pre>\n\n<p>A third approach would be to use <code>sprintf</code> or <code>snprintf</code> from the C library.</p>\n\n<pre><code>char buffer[128];\nsnprintf(buffer, sizeof(buffer), \"%s%d\", name.c_str(), age);\nstd::cout &lt;&lt; buffer &lt;&lt; std::endl;\n</code></pre>\n\n<p>Other posters suggested using <code>itoa</code>. This is NOT a standard function, so your code will not be portable if you use it. There are compilers that don't support it.</p>\n" }, { "answer_id": 191794, "author": "Seb Rose", "author_id": 12405, "author_profile": "https://Stackoverflow.com/users/12405", "pm_score": 4, "selected": false, "text": "<pre><code>#include &lt;string&gt;\n#include &lt;sstream&gt;\nusing namespace std;\nstring concatenate(std::string const&amp; name, int i)\n{\n stringstream s;\n s &lt;&lt; name &lt;&lt; i;\n return s.str();\n}\n</code></pre>\n" }, { "answer_id": 192017, "author": "user12576", "author_id": 12576, "author_profile": "https://Stackoverflow.com/users/12576", "pm_score": 4, "selected": false, "text": "<p>It seems to me that the simplest answer is to use the <code>sprintf</code> function:</p>\n\n<pre><code>sprintf(outString,\"%s%d\",name,age);\n</code></pre>\n" }, { "answer_id": 192290, "author": "bsruth", "author_id": 23504, "author_profile": "https://Stackoverflow.com/users/23504", "pm_score": 3, "selected": false, "text": "<p>If you are using MFC, you can use a CString</p>\n\n<pre><code>CString nameAge = \"\";\nnameAge.Format(\"%s%d\", \"John\", 21);\n</code></pre>\n\n<p>Managed C++ also has a \n<a href=\"http://msdn.microsoft.com/en-us/library/fht0f5be.aspx\" rel=\"nofollow noreferrer\"> string formatter</a>.</p>\n" }, { "answer_id": 192821, "author": "Zing-", "author_id": 8883, "author_profile": "https://Stackoverflow.com/users/8883", "pm_score": 4, "selected": false, "text": "<pre><code>#include &lt;sstream&gt;\n\ntemplate &lt;class T&gt;\ninline std::string to_string (const T&amp; t)\n{\n std::stringstream ss;\n ss &lt;&lt; t;\n return ss.str();\n}\n</code></pre>\n\n<p>Then your usage would look something like this</p>\n\n<pre><code> std::string szName = \"John\";\n int numAge = 23;\n szName += to_string&lt;int&gt;(numAge);\n cout &lt;&lt; szName &lt;&lt; endl;\n</code></pre>\n\n<p><a href=\"http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/\" rel=\"noreferrer\">Googled</a> [and tested :p ]</p>\n" }, { "answer_id": 193198, "author": "Pyry Jahkola", "author_id": 26981, "author_profile": "https://Stackoverflow.com/users/26981", "pm_score": 2, "selected": false, "text": "<p>The std::ostringstream is a good method, but sometimes this additional trick might get handy transforming the formatting to a one-liner:</p>\n\n<pre><code>#include &lt;sstream&gt;\n#define MAKE_STRING(tokens) /****************/ \\\n static_cast&lt;std::ostringstream&amp;&gt;( \\\n std::ostringstream().flush() &lt;&lt; tokens \\\n ).str() \\\n /**/\n</code></pre>\n\n<p>Now you can format strings like this:</p>\n\n<pre><code>int main() {\n int i = 123;\n std::string message = MAKE_STRING(\"i = \" &lt;&lt; i);\n std::cout &lt;&lt; message &lt;&lt; std::endl; // prints: \"i = 123\"\n}\n</code></pre>\n" }, { "answer_id": 900035, "author": "DannyT", "author_id": 106673, "author_profile": "https://Stackoverflow.com/users/106673", "pm_score": 10, "selected": false, "text": "<p>In alphabetical order:</p>\n<pre><code>std::string name = &quot;John&quot;;\nint age = 21;\nstd::string result;\n\n// 1. with Boost\nresult = name + boost::lexical_cast&lt;std::string&gt;(age);\n\n// 2. with C++11\nresult = name + std::to_string(age);\n\n// 3. with FastFormat.Format\nfastformat::fmt(result, &quot;{0}{1}&quot;, name, age);\n\n// 4. with FastFormat.Write\nfastformat::write(result, name, age);\n\n// 5. with the {fmt} library\nresult = fmt::format(&quot;{}{}&quot;, name, age);\n\n// 6. with IOStreams\nstd::stringstream sstm;\nsstm &lt;&lt; name &lt;&lt; age;\nresult = sstm.str();\n\n// 7. with itoa\nchar numstr[21]; // enough to hold all numbers up to 64-bits\nresult = name + itoa(age, numstr, 10);\n\n// 8. with sprintf\nchar numstr[21]; // enough to hold all numbers up to 64-bits\nsprintf(numstr, &quot;%d&quot;, age);\nresult = name + numstr;\n\n// 9. with STLSoft's integer_to_string\nchar numstr[21]; // enough to hold all numbers up to 64-bits\nresult = name + stlsoft::integer_to_string(numstr, 21, age);\n\n// 10. with STLSoft's winstl::int_to_string()\nresult = name + winstl::int_to_string(age);\n\n// 11. With Poco NumberFormatter\nresult = name + Poco::NumberFormatter().format(age);\n</code></pre>\n<ol>\n<li>is safe, but slow; requires <a href=\"http://www.boost.org/\" rel=\"noreferrer\">Boost</a> (header-only); most/all platforms</li>\n<li>is safe, requires C++11 (<a href=\"http://www.cplusplus.com/reference/string/to_string/\" rel=\"noreferrer\">to_string()</a> is already included in <code>#include &lt;string&gt;</code>)</li>\n<li>is safe, and fast; requires <a href=\"http://fastformat.sourceforge.net/\" rel=\"noreferrer\">FastFormat</a>, which must be compiled; most/all platforms</li>\n<li>(<em>ditto</em>)</li>\n<li>is safe, and fast; requires <a href=\"https://github.com/fmtlib/fmt\" rel=\"noreferrer\">the {fmt} library</a>, which can either be compiled or used in a header-only mode; most/all platforms</li>\n<li>safe, slow, and verbose; requires <code>#include &lt;sstream&gt;</code> (from standard C++)</li>\n<li>is brittle (you must supply a large enough buffer), fast, and verbose; itoa() is a non-standard extension, and not guaranteed to be available for all platforms</li>\n<li>is brittle (you must supply a large enough buffer), fast, and verbose; requires nothing (is standard C++); all platforms</li>\n<li>is brittle (you must supply a large enough buffer), <a href=\"http://www.ddj.com/cpp/184401596\" rel=\"noreferrer\">probably the fastest-possible conversion</a>, verbose; requires <a href=\"http://www.stlsoft.org/\" rel=\"noreferrer\">STLSoft</a> (header-only); most/all platforms</li>\n<li>safe-ish (you don't use more than one <a href=\"http://www.stlsoft.org/doc-1.9/int%5F%5Fto%5F%5Fstring%5F8hpp.html\" rel=\"noreferrer\">int_to_string()</a> call in a single statement), fast; requires <a href=\"http://www.stlsoft.org/\" rel=\"noreferrer\">STLSoft</a> (header-only); Windows-only</li>\n<li>is safe, but slow; requires <a href=\"https://pocoproject.org/\" rel=\"noreferrer\">Poco C++</a> ; most/all platforms</li>\n</ol>\n" }, { "answer_id": 3854165, "author": "mloskot", "author_id": 151641, "author_profile": "https://Stackoverflow.com/users/151641", "pm_score": 2, "selected": false, "text": "<p>There are more options possible to use to concatenate integer (or other numerric object) with string. It is <a href=\"http://www.boost.org/doc/libs/release/libs/format/index.html\" rel=\"nofollow\">Boost.Format</a></p>\n\n<pre><code>#include &lt;boost/format.hpp&gt;\n#include &lt;string&gt;\nint main()\n{\n using boost::format;\n\n int age = 22;\n std::string str_age = str(format(\"age is %1%\") % age);\n}\n</code></pre>\n\n<p>and Karma from <a href=\"http://boost-spirit.com\" rel=\"nofollow\">Boost.Spirit</a> (v2)</p>\n\n<pre><code>#include &lt;boost/spirit/include/karma.hpp&gt;\n#include &lt;iterator&gt;\n#include &lt;string&gt;\nint main()\n{\n using namespace boost::spirit;\n\n int age = 22;\n std::string str_age(\"age is \");\n std::back_insert_iterator&lt;std::string&gt; sink(str_age);\n karma::generate(sink, int_, age);\n\n return 0;\n}\n</code></pre>\n\n<p>Boost.Spirit Karma claims to be one of the <a href=\"http://boost-spirit.com/home/2010/03/09/integer-to-string-conversion-karma-fastest-again/\" rel=\"nofollow\">fastest option for integer to string</a> conversion.</p>\n" }, { "answer_id": 7011581, "author": "leinir", "author_id": 232739, "author_profile": "https://Stackoverflow.com/users/232739", "pm_score": 2, "selected": false, "text": "<p>As a Qt-related question was closed in favour of this one, here's how to do it using Qt:</p>\n\n<pre><code>QString string = QString(\"Some string %1 with an int somewhere\").arg(someIntVariable);\nstring.append(someOtherIntVariable);\n</code></pre>\n\n<p>The string variable now has someIntVariable's value in place of %1 and someOtherIntVariable's value at the end.</p>\n" }, { "answer_id": 7995673, "author": "uckelman", "author_id": 181106, "author_profile": "https://Stackoverflow.com/users/181106", "pm_score": 3, "selected": false, "text": "<p>If you'd like to use <code>+</code> for concatenation of anything which has an output operator, you can provide a template version of <code>operator+</code>:</p>\n\n<pre><code>template &lt;typename L, typename R&gt; std::string operator+(L left, R right) {\n std::ostringstream os;\n os &lt;&lt; left &lt;&lt; right;\n return os.str();\n}\n</code></pre>\n\n<p>Then you can write your concatenations in a straightforward way:</p>\n\n<pre><code>std::string foo(\"the answer is \");\nint i = 42;\nstd::string bar(foo + i); \nstd::cout &lt;&lt; bar &lt;&lt; std::endl;\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>the answer is 42\n</code></pre>\n\n<p>This isn't the most efficient way, but you don't need the most efficient way unless you're doing a lot of concatenation inside a loop.</p>\n" }, { "answer_id": 11860411, "author": "Jeremy", "author_id": 849506, "author_profile": "https://Stackoverflow.com/users/849506", "pm_score": 8, "selected": false, "text": "<p>In C++11, you can use <code>std::to_string</code>, e.g.:</p>\n\n<pre><code>auto result = name + std::to_string( age );\n</code></pre>\n" }, { "answer_id": 16781028, "author": "David G", "author_id": 701092, "author_profile": "https://Stackoverflow.com/users/701092", "pm_score": 5, "selected": false, "text": "<p>If you have C++11, you can use <code>std::to_string</code>.</p>\n\n<p>Example:</p>\n\n<pre><code>std::string name = \"John\";\nint age = 21;\n\nname += std::to_string(age);\n\nstd::cout &lt;&lt; name;\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>John21\n</code></pre>\n" }, { "answer_id": 18489238, "author": "Reda Lahdili", "author_id": 2724738, "author_profile": "https://Stackoverflow.com/users/2724738", "pm_score": 1, "selected": false, "text": "<p>There is a function I wrote, which takes the int number as the parameter, and convert it to a string literal. This function is dependent on another function that converts a single digit to its char equivalent:</p>\n\n<pre><code>char intToChar(int num)\n{\n if (num &lt; 10 &amp;&amp; num &gt;= 0)\n {\n return num + 48;\n //48 is the number that we add to an integer number to have its character equivalent (see the unsigned ASCII table)\n }\n else\n {\n return '*';\n }\n}\n\nstring intToString(int num)\n{\n int digits = 0, process, single;\n string numString;\n process = num;\n\n // The following process the number of digits in num\n while (process != 0)\n {\n single = process % 10; // 'single' now holds the rightmost portion of the int\n process = (process - single)/10;\n // Take out the rightmost number of the int (it's a zero in this portion of the int), then divide it by 10\n // The above combination eliminates the rightmost portion of the int\n digits ++;\n }\n\n process = num;\n\n // Fill the numString with '*' times digits\n for (int i = 0; i &lt; digits; i++)\n {\n numString += '*';\n }\n\n\n for (int i = digits-1; i &gt;= 0; i--)\n {\n single = process % 10;\n numString[i] = intToChar ( single);\n process = (process - single) / 10;\n }\n\n return numString;\n}\n</code></pre>\n" }, { "answer_id": 20194939, "author": "David G", "author_id": 701092, "author_profile": "https://Stackoverflow.com/users/701092", "pm_score": 2, "selected": false, "text": "<p>Here is an implementation of how to append an int to a string using the parsing and formatting facets from the IOStreams library.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;locale&gt;\n#include &lt;string&gt;\n\ntemplate &lt;class Facet&gt;\nstruct erasable_facet : Facet\n{\n erasable_facet() : Facet(1) { }\n ~erasable_facet() { }\n};\n\nvoid append_int(std::string&amp; s, int n)\n{\n erasable_facet&lt;std::num_put&lt;char,\n std::back_insert_iterator&lt;std::string&gt;&gt;&gt; facet;\n std::ios str(nullptr);\n\n facet.put(std::back_inserter(s), str,\n str.fill(), static_cast&lt;unsigned long&gt;(n));\n}\n\nint main()\n{\n std::string str = \"ID: \";\n int id = 123;\n\n append_int(str, id);\n\n std::cout &lt;&lt; str; // ID: 123\n}\n</code></pre>\n" }, { "answer_id": 27594181, "author": "Kevin", "author_id": 4383443, "author_profile": "https://Stackoverflow.com/users/4383443", "pm_score": 5, "selected": false, "text": "<p>This is the easiest way:</p>\n\n<pre><code>string s = name + std::to_string(age);\n</code></pre>\n" }, { "answer_id": 39754848, "author": "Sukhbir", "author_id": 5036543, "author_profile": "https://Stackoverflow.com/users/5036543", "pm_score": 2, "selected": false, "text": "<p>You can concatenate int to string by using the given below simple trick, but note that this only works when integer is of single digit. Otherwise, add integer digit by digit to that string.</p>\n\n<pre><code>string name = \"John\";\nint age = 5;\nchar temp = 5 + '0';\nname = name + temp;\ncout &lt;&lt; name &lt;&lt; endl;\n\nOutput: John5\n</code></pre>\n" }, { "answer_id": 50089264, "author": "vitaut", "author_id": 471164, "author_profile": "https://Stackoverflow.com/users/471164", "pm_score": 3, "selected": false, "text": "<p>In C++20 you'll be able to do:</p>\n<pre><code>auto result = std::format(&quot;{}{}&quot;, name, age);\n</code></pre>\n<p>In the meantime you can use <a href=\"https://github.com/fmtlib/fmt\" rel=\"noreferrer\">the {fmt} library</a>, <code>std::format</code> is based on:</p>\n<pre><code>auto result = fmt::format(&quot;{}{}&quot;, name, age);\n</code></pre>\n<p><strong>Disclaimer</strong>: I'm the author of the {fmt} library and C++20 <code>std::format</code>.</p>\n" }, { "answer_id": 51093935, "author": "lohith99", "author_id": 8638353, "author_profile": "https://Stackoverflow.com/users/8638353", "pm_score": 3, "selected": false, "text": "<p>This problem can be done in many ways. I will show it in two ways:</p>\n\n<ol>\n<li><p>Convert the number to string using <code>to_string(i)</code>.</p></li>\n<li><p>Using string streams.</p>\n\n<p>Code:</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;sstream&gt;\n#include &lt;bits/stdc++.h&gt;\n#include &lt;iostream&gt;\nusing namespace std;\n\nint main() {\n string name = \"John\";\n int age = 21;\n\n string answer1 = \"\";\n // Method 1). string s1 = to_string(age).\n\n string s1=to_string(age); // Know the integer get converted into string\n // where as we know that concatenation can easily be done using '+' in C++\n\n answer1 = name + s1;\n\n cout &lt;&lt; answer1 &lt;&lt; endl;\n\n // Method 2). Using string streams\n\n ostringstream s2;\n\n s2 &lt;&lt; age;\n\n string s3 = s2.str(); // The str() function will convert a number into a string\n\n string answer2 = \"\"; // For concatenation of strings.\n\n answer2 = name + s3;\n\n cout &lt;&lt; answer2 &lt;&lt; endl;\n\n return 0;\n}\n</code></pre></li>\n</ol>\n" }, { "answer_id": 51667112, "author": "Isma Rekathakusuma", "author_id": 8198089, "author_profile": "https://Stackoverflow.com/users/8198089", "pm_score": 2, "selected": false, "text": "<ul>\n<li>std::ostringstream</li>\n</ul>\n\n<blockquote>\n<pre><code>#include &lt;sstream&gt;\n\nstd::ostringstream s;\ns &lt;&lt; \"John \" &lt;&lt; age;\nstd::string query(s.str());\n</code></pre>\n</blockquote>\n\n<ul>\n<li>std::to_string (C++11)</li>\n</ul>\n\n<blockquote>\n<pre><code>std::string query(\"John \" + std::to_string(age));\n</code></pre>\n</blockquote>\n\n<ul>\n<li>boost::lexical_cast</li>\n</ul>\n\n<blockquote>\n<pre><code>#include &lt;boost/lexical_cast.hpp&gt;\n\nstd::string query(\"John \" + boost::lexical_cast&lt;std::string&gt;(age));\n</code></pre>\n</blockquote>\n" }, { "answer_id": 60929988, "author": "ant_dev", "author_id": 10728087, "author_profile": "https://Stackoverflow.com/users/10728087", "pm_score": 3, "selected": false, "text": "<p>As a one liner: <code>name += std::to_string(age);</code></p>\n" }, { "answer_id": 67506608, "author": "PeterSom", "author_id": 779373, "author_profile": "https://Stackoverflow.com/users/779373", "pm_score": 1, "selected": false, "text": "<p>In C++ 20 you can have a variadic lambda that does concatenate arbitrary streamable types to a string in a few lines:</p>\n<pre><code>auto make_string=[os=std::ostringstream{}](auto&amp;&amp; ...p) mutable \n{ \n (os &lt;&lt; ... &lt;&lt; std::forward&lt;decltype(p)&gt;(p) ); \n return std::move(os).str();\n};\n\nint main() {\nstd::cout &lt;&lt; make_string(&quot;Hello world: &quot;,4,2, &quot; is &quot;, 42.0);\n}\n</code></pre>\n<p>see <a href=\"https://godbolt.org/z/dEe9h75eb\" rel=\"nofollow noreferrer\">https://godbolt.org/z/dEe9h75eb</a></p>\n<p>using move(os).str() guarantees that the ostringstream object's stringbuffer is empty next time the lambda is called.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23120/" ]
I thought this would be really simple, but it's presenting some difficulties. If I have ``` std::string name = "John"; int age = 21; ``` How do I combine them to get a single string `"John21"`?
In alphabetical order: ``` std::string name = "John"; int age = 21; std::string result; // 1. with Boost result = name + boost::lexical_cast<std::string>(age); // 2. with C++11 result = name + std::to_string(age); // 3. with FastFormat.Format fastformat::fmt(result, "{0}{1}", name, age); // 4. with FastFormat.Write fastformat::write(result, name, age); // 5. with the {fmt} library result = fmt::format("{}{}", name, age); // 6. with IOStreams std::stringstream sstm; sstm << name << age; result = sstm.str(); // 7. with itoa char numstr[21]; // enough to hold all numbers up to 64-bits result = name + itoa(age, numstr, 10); // 8. with sprintf char numstr[21]; // enough to hold all numbers up to 64-bits sprintf(numstr, "%d", age); result = name + numstr; // 9. with STLSoft's integer_to_string char numstr[21]; // enough to hold all numbers up to 64-bits result = name + stlsoft::integer_to_string(numstr, 21, age); // 10. with STLSoft's winstl::int_to_string() result = name + winstl::int_to_string(age); // 11. With Poco NumberFormatter result = name + Poco::NumberFormatter().format(age); ``` 1. is safe, but slow; requires [Boost](http://www.boost.org/) (header-only); most/all platforms 2. is safe, requires C++11 ([to\_string()](http://www.cplusplus.com/reference/string/to_string/) is already included in `#include <string>`) 3. is safe, and fast; requires [FastFormat](http://fastformat.sourceforge.net/), which must be compiled; most/all platforms 4. (*ditto*) 5. is safe, and fast; requires [the {fmt} library](https://github.com/fmtlib/fmt), which can either be compiled or used in a header-only mode; most/all platforms 6. safe, slow, and verbose; requires `#include <sstream>` (from standard C++) 7. is brittle (you must supply a large enough buffer), fast, and verbose; itoa() is a non-standard extension, and not guaranteed to be available for all platforms 8. is brittle (you must supply a large enough buffer), fast, and verbose; requires nothing (is standard C++); all platforms 9. is brittle (you must supply a large enough buffer), [probably the fastest-possible conversion](http://www.ddj.com/cpp/184401596), verbose; requires [STLSoft](http://www.stlsoft.org/) (header-only); most/all platforms 10. safe-ish (you don't use more than one [int\_to\_string()](http://www.stlsoft.org/doc-1.9/int%5F%5Fto%5F%5Fstring%5F8hpp.html) call in a single statement), fast; requires [STLSoft](http://www.stlsoft.org/) (header-only); Windows-only 11. is safe, but slow; requires [Poco C++](https://pocoproject.org/) ; most/all platforms
191,787
<p>I want to find a sql command or something that can do this where I have a table named tblFoo and I want to name it tblFooBar. However, I want the primary key to also be change, for example, currently it is:</p> <pre><code>CONSTRAINT [PK_tblFoo] PRIMARY KEY CLUSTERED </code></pre> <p>And I want a name change to change it to:</p> <pre><code>CONSTRAINT [PK_tblFooBar] PRIMARY KEY CLUSTERED </code></pre> <p>Then, recursively go through and cascade this change on all tables that have a foreigh key relationship, eg. from this:</p> <pre><code>CHECK ADD CONSTRAINT [FK_tblContent_tblFoo] FOREIGN KEY([fooID]) </code></pre> <p>To this:</p> <pre><code> CHECK ADD CONSTRAINT [FK_tblContent_tblFooBar] FOREIGN KEY([fooID]) </code></pre> <p>Naturally, I am trying not to go through and do this all manually because a) it is an error prone process, and b)it doesn't scale.</p>
[ { "answer_id": 191815, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 1, "selected": false, "text": "<p>SQL Server won't do this directly as far as I am aware. You would have to manually build the script to do the change. This can be achieved by generating the SQL for the table definition (SSMS will do this) and doing a search and replace on the names.</p>\n" }, { "answer_id": 191888, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 4, "selected": true, "text": "<p>This is just off the top of my head and isn't complete (you'd need to add similar code for indexes). Also, you would need to either add code to avoid renaming objects from a table with the same base name, but additional characters - for example, this code would also list tblFoo2 and all of its associated objects. Hopefully it's a start for you though.</p>\n\n<pre><code>DECLARE\n @old_name VARCHAR(100),\n @new_name VARCHAR(100)\n\nSET @old_name = 'tblFoo'\nSET @new_name = 'tblFooBar'\n\nSELECT\n 'EXEC sp_rename ''' + name + ''', ''' + REPLACE(name, @old_name, @new_name) + ''''\nFROM dbo.sysobjects\nWHERE name LIKE '%' + @old_name + '%'\n</code></pre>\n" }, { "answer_id": 192235, "author": "evilhomer", "author_id": 2806, "author_profile": "https://Stackoverflow.com/users/2806", "pm_score": 2, "selected": false, "text": "<p>A great tool that takes the pain out of renaming tables is <a href=\"http://www.red-gate.com/products/SQL_Refactor/index.htm\" rel=\"nofollow noreferrer\">Red Gate SQL Refactor</a>\nIt will automatically find your dependency's and work all that stuff out for you too.</p>\n\n<p>Big fan :-)</p>\n" }, { "answer_id": 8551632, "author": "Srinidhi", "author_id": 1068914, "author_profile": "https://Stackoverflow.com/users/1068914", "pm_score": 3, "selected": false, "text": "<p>Good answer by Tom<br/>\nI've just extended his query here to include indexes</p>\n\n<pre><code>declare\n @old nvarchar(100),\n @new nvarchar(100)\n\nset @old = 'OldName'\nset @new = 'NewName'\n\nselect 'EXEC sp_rename ''' + name + ''', ''' + \n REPLACE(name, @old, @new) + ''''\n from sys.objects \n where name like '%' + @old + '%'\nunion -- index renames\nselect 'EXEC sp_rename ''' + (sys.objects.name + '.' + sys.indexes.name) + ''', ''' +\n REPLACE(sys.indexes.name, @old, @new) + ''', ''INDEX'''\n from sys.objects \n left join sys.indexes on sys.objects.object_id = sys.indexes.object_id\n where sys.indexes.name like '%' + @old + '%'\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191787", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7952/" ]
I want to find a sql command or something that can do this where I have a table named tblFoo and I want to name it tblFooBar. However, I want the primary key to also be change, for example, currently it is: ``` CONSTRAINT [PK_tblFoo] PRIMARY KEY CLUSTERED ``` And I want a name change to change it to: ``` CONSTRAINT [PK_tblFooBar] PRIMARY KEY CLUSTERED ``` Then, recursively go through and cascade this change on all tables that have a foreigh key relationship, eg. from this: ``` CHECK ADD CONSTRAINT [FK_tblContent_tblFoo] FOREIGN KEY([fooID]) ``` To this: ``` CHECK ADD CONSTRAINT [FK_tblContent_tblFooBar] FOREIGN KEY([fooID]) ``` Naturally, I am trying not to go through and do this all manually because a) it is an error prone process, and b)it doesn't scale.
This is just off the top of my head and isn't complete (you'd need to add similar code for indexes). Also, you would need to either add code to avoid renaming objects from a table with the same base name, but additional characters - for example, this code would also list tblFoo2 and all of its associated objects. Hopefully it's a start for you though. ``` DECLARE @old_name VARCHAR(100), @new_name VARCHAR(100) SET @old_name = 'tblFoo' SET @new_name = 'tblFooBar' SELECT 'EXEC sp_rename ''' + name + ''', ''' + REPLACE(name, @old_name, @new_name) + '''' FROM dbo.sysobjects WHERE name LIKE '%' + @old_name + '%' ```
191,791
<p>I am hoping to find a way to do this in vb.net: </p> <p>Say you have function call getPaint(Color). You want the call to be limited to the parameter values of (red,green,yellow). When they enter that parameter, the user is provided the available options, like how a boolean parameter functions.</p> <p>Any ideas? </p>
[ { "answer_id": 191811, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 2, "selected": false, "text": "<p>Hope I am not missing something from your question. Use an enumeration like this:</p>\n\n<pre><code>Enum Color\n Red = 1\n Green = 2\n Yellow = 3\nEnd Enum\n</code></pre>\n\n<p>When you write <code>getPaint(Color</code> followed by a . (period) the Intellisense system will automatically suggest the three options declared in the enumeration (Red, Green, Yellow).</p>\n" }, { "answer_id": 191832, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 3, "selected": true, "text": "<p>to limit a enum with a large number of values, to just a few you could do the following</p>\n\n<h2>C#</h2>\n\n<pre><code>List&lt;Color&gt; allow = new List&lt;Color&gt; { Color.Red, Color.Green, Color.Yellow };\nif (!allow.Contains(color))\n{\n throw new ArguementException(\"Invalid Color\");\n}\n</code></pre>\n\n<h2>VB</h2>\n\n<pre><code>Dim allow As New List(Of Color)()\nallow.Add(Color.Red)\nallow.Add(Color.Green)\nallow.Add(Color.Yellow)\nIf Not allow.Contains(color) Then\nThrow New ArguementException(\"Invalid Color\")\nEnd If\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/44449/" ]
I am hoping to find a way to do this in vb.net: Say you have function call getPaint(Color). You want the call to be limited to the parameter values of (red,green,yellow). When they enter that parameter, the user is provided the available options, like how a boolean parameter functions. Any ideas?
to limit a enum with a large number of values, to just a few you could do the following C# -- ``` List<Color> allow = new List<Color> { Color.Red, Color.Green, Color.Yellow }; if (!allow.Contains(color)) { throw new ArguementException("Invalid Color"); } ``` VB -- ``` Dim allow As New List(Of Color)() allow.Add(Color.Red) allow.Add(Color.Green) allow.Add(Color.Yellow) If Not allow.Contains(color) Then Throw New ArguementException("Invalid Color") End If ```
191,817
<p>I'm roughing a layout together and doing some browser testing. Never came across this issue before, check out the contact form in the footer of this page</p> <p><a href="http://staging.terrilynn.com/fundraising/" rel="nofollow noreferrer"><a href="http://staging.terrilynn.com/fundraising/" rel="nofollow noreferrer">http://staging.terrilynn.com/fundraising/</a></a></p> <p>There is a div with a width of 298px floated to the right that comes first in the source order. It is followed by several other divs, each with their child form elements floated left.</p> <p>The div's that should appear to the left of right-floated message div are disappearing.</p> <p>Page displays correctly in firefox. Any help would be appreciated.</p> <pre><code>&lt;div id='footer-contact-form'&gt; &lt;h1&gt;Request Information &lt;span class='note'&gt;(all fields required)&lt;/span&gt;&lt;/h1&gt; &lt;form class="monkForm" method="post" action="http://my.ekklesia360.com/FormBuilder/handleSubmit.php" id="footer-info-request"&gt; &lt;fieldset&gt; &lt;legend&gt;Footer Info Request&lt;/legend&gt; &lt;div class="textarea required" id="w2376"&gt; &lt;p class="data"&gt; &lt;label for="area_2376"&gt;Message&lt;/label&gt; &lt;textarea id="area_2376" name="e_2376" rows="5" cols="20"&gt;&lt;/textarea&gt; &lt;/p&gt; &lt;/div&gt; &lt;div class="text required" id="w2377"&gt; &lt;p class="data"&gt; &lt;label for="text_2377"&gt;Name&lt;/label&gt; &lt;input id="text_2377" type="text" name="e_2377" value="" /&gt; &lt;/p&gt; &lt;/div&gt; &lt;div class="text required" id="w2378"&gt; &lt;p class="data"&gt; &lt;label for="text_2378"&gt;Phone&lt;/label&gt; &lt;input id="text_2378" type="text" name="e_2378" value="" /&gt; &lt;/p&gt;&lt;/div&gt; &lt;div class="text" id="w2379"&gt; &lt;p class="data"&gt; &lt;label for="text_2379"&gt;Email&lt;/label&gt; &lt;input id="text_2379" type="text" name="e_2379" value="" /&gt; &lt;/p&gt; &lt;/div&gt; &lt;p id="formsubmit"&gt;&lt;input type="submit" name="submit" value="Send" /&gt;&lt;/p&gt; &lt;input type="hidden" name="token" value="8143f99c1d01b4d1207dbe7860e5586d" /&gt; &lt;input type="hidden" name="SITEID" value="2185" /&gt; &lt;input type="hidden" name="cpBID" value="367780" /&gt; &lt;input type="hidden" name="formslug" value="footer-info-request" /&gt; &lt;input type="hidden" name="CMSCODE" value="EKK" /&gt; &lt;input type="hidden" name="fkey" value="" /&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;/div&gt;&lt;!-- #footer-contact-form --&gt; </code></pre>
[ { "answer_id": 191878, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<p>Have you tried not floating the <code>&lt;p&gt;</code> elements to the left? Why are you actually doing this? It isn't required in the current layout.</p>\n" }, { "answer_id": 192076, "author": "matte", "author_id": 25768, "author_profile": "https://Stackoverflow.com/users/25768", "pm_score": 2, "selected": true, "text": "<p>I guess I found the problem:</p>\n\n<p>screen.css (line 382)</p>\n\n<pre><code>#footer-contact-form div {\nmargin:0 300px 10px 0;\noverflow:hidden;\n}\n</code></pre>\n\n<p>\"overflow:hidden\" causes the problem.</p>\n" }, { "answer_id": 192132, "author": "mjr", "author_id": 26858, "author_profile": "https://Stackoverflow.com/users/26858", "pm_score": 0, "selected": false, "text": "<p>Wow that worked!</p>\n\n<p>I was using overflow:hidden to force the div to contain the floated label and input elements.</p>\n\n<p>But really the float on the input elements wasn't necessary.</p>\n\n<p>Thanks you all very much.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26858/" ]
I'm roughing a layout together and doing some browser testing. Never came across this issue before, check out the contact form in the footer of this page [<http://staging.terrilynn.com/fundraising/>](http://staging.terrilynn.com/fundraising/) There is a div with a width of 298px floated to the right that comes first in the source order. It is followed by several other divs, each with their child form elements floated left. The div's that should appear to the left of right-floated message div are disappearing. Page displays correctly in firefox. Any help would be appreciated. ``` <div id='footer-contact-form'> <h1>Request Information <span class='note'>(all fields required)</span></h1> <form class="monkForm" method="post" action="http://my.ekklesia360.com/FormBuilder/handleSubmit.php" id="footer-info-request"> <fieldset> <legend>Footer Info Request</legend> <div class="textarea required" id="w2376"> <p class="data"> <label for="area_2376">Message</label> <textarea id="area_2376" name="e_2376" rows="5" cols="20"></textarea> </p> </div> <div class="text required" id="w2377"> <p class="data"> <label for="text_2377">Name</label> <input id="text_2377" type="text" name="e_2377" value="" /> </p> </div> <div class="text required" id="w2378"> <p class="data"> <label for="text_2378">Phone</label> <input id="text_2378" type="text" name="e_2378" value="" /> </p></div> <div class="text" id="w2379"> <p class="data"> <label for="text_2379">Email</label> <input id="text_2379" type="text" name="e_2379" value="" /> </p> </div> <p id="formsubmit"><input type="submit" name="submit" value="Send" /></p> <input type="hidden" name="token" value="8143f99c1d01b4d1207dbe7860e5586d" /> <input type="hidden" name="SITEID" value="2185" /> <input type="hidden" name="cpBID" value="367780" /> <input type="hidden" name="formslug" value="footer-info-request" /> <input type="hidden" name="CMSCODE" value="EKK" /> <input type="hidden" name="fkey" value="" /> </fieldset> </form> </div><!-- #footer-contact-form --> ```
I guess I found the problem: screen.css (line 382) ``` #footer-contact-form div { margin:0 300px 10px 0; overflow:hidden; } ``` "overflow:hidden" causes the problem.
191,826
<p>I'm actually developing a Web Service in Java using Axis 2. I designed my service as a POJO (Plain Old Java Object) with public method throwing exceptions :</p> <pre><code>public class MyService { public Object myMethod() throws MyException { [...] } } </code></pre> <p>I then generated the WSDL using Axis2 ant task. With the WSDL I generate a client stub to test my service. The generated code contains a "MyExceptionException" and the "myMethod" in the stub declare to throw this :</p> <pre><code>public class MyServiceStub extends org.apache.axis2.client.Stub { [...] public MyServiceStub.MyMethodResponse myMethod(MyServiceStub.MyMethod myMethod) throws java.rmi.RemoteException, MyExceptionException0 { [...] } [...] } </code></pre> <p>But when calling the method surrounded by a catch, the "MyExceptionException" is never transmitted by the server which transmit an AxisFault instead (subclass of RemoteException).</p> <p>I assume the problem is server-side but don't find where. The service is deployed as an aar file in the axis2 webapp on a tomcat 5.5 server. The services.xml looks like this :</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;service name="MyService" scope="application"&gt; &lt;description&gt;&lt;/description&gt; &lt;messageReceivers&gt; &lt;messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/&gt; &lt;messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/&gt; &lt;/messageReceivers&gt; &lt;parameter name="ServiceClass"&gt;MyService&lt;/parameter&gt; &lt;parameter name="ServiceTCCL"&gt;composite&lt;/parameter&gt; &lt;/service&gt; </code></pre> <p>If the behavior is normal then I'll drop the use of Exceptions (which is not vital to my project) but I'm circumspect why Java2WSDL generate custom &lt;wsdl:fault&gt; in operation input &amp; output declaration and WSDL2Java generate an Exception class (and declare to throw it in the stub method) if this is not usable...</p>
[ { "answer_id": 192363, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 3, "selected": true, "text": "<p>I don't really think there is a problem. Your Client calls a method on the server. That method results in an exception. Axis transforms this exception to something which can be send to the client to indicate the error.</p>\n\n<p>All exceptions, as far as I know, are wrapped into an AxisFault which is then transmitted to the client as, I believe, a SoapFault message with as description the exception message.</p>\n\n<p>In other words, the client should only see AxisFaults as the exception (exception class) is not serialized and send. Server exceptions should become AxisFaults at the client side. </p>\n" }, { "answer_id": 1762087, "author": "Axel", "author_id": 214457, "author_profile": "https://Stackoverflow.com/users/214457", "pm_score": 1, "selected": false, "text": "<p>Have you tried using Axis2 with Lady4j, it solved this issue for us.</p>\n" }, { "answer_id": 2919955, "author": "Russell", "author_id": 351795, "author_profile": "https://Stackoverflow.com/users/351795", "pm_score": 1, "selected": false, "text": "<p>If your WSDL specifies that your service throws a custom error your client should expect to handle these errors as well as the generic remote exceptions thrown by the operation of Axis2. </p>\n\n<p>When your stub recieves an AxisFault from the server, it attempts to consturct a custom exception if this is specified in your WSDL. If this fails it will simply pass out the AxisFault instead.</p>\n\n<p>The stub will attempt to call f.getDetail(). If this is null it will not try to construct a custom exception and will pass out the AxisFault. With Axis2 1.5, the autogenerated MessageInOutReciver on the serverside does not set this value by default.</p>\n\n<p>You can set it manually on the serverside like this (assuming you have autogenerated MyFaultException and MyFault classes):</p>\n\n<pre><code> MyFaultException ex = new MyFaultException(\"My Exception Message\");\n MyFault fault = new MyFault();\n fault.setMyFault(\"My Fault Message\");\n ex.setFaultMessage(fault);\n throw ex; \n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191826", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26859/" ]
I'm actually developing a Web Service in Java using Axis 2. I designed my service as a POJO (Plain Old Java Object) with public method throwing exceptions : ``` public class MyService { public Object myMethod() throws MyException { [...] } } ``` I then generated the WSDL using Axis2 ant task. With the WSDL I generate a client stub to test my service. The generated code contains a "MyExceptionException" and the "myMethod" in the stub declare to throw this : ``` public class MyServiceStub extends org.apache.axis2.client.Stub { [...] public MyServiceStub.MyMethodResponse myMethod(MyServiceStub.MyMethod myMethod) throws java.rmi.RemoteException, MyExceptionException0 { [...] } [...] } ``` But when calling the method surrounded by a catch, the "MyExceptionException" is never transmitted by the server which transmit an AxisFault instead (subclass of RemoteException). I assume the problem is server-side but don't find where. The service is deployed as an aar file in the axis2 webapp on a tomcat 5.5 server. The services.xml looks like this : ``` <?xml version="1.0" encoding="UTF-8"?> <service name="MyService" scope="application"> <description></description> <messageReceivers> <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/> <messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/> </messageReceivers> <parameter name="ServiceClass">MyService</parameter> <parameter name="ServiceTCCL">composite</parameter> </service> ``` If the behavior is normal then I'll drop the use of Exceptions (which is not vital to my project) but I'm circumspect why Java2WSDL generate custom <wsdl:fault> in operation input & output declaration and WSDL2Java generate an Exception class (and declare to throw it in the stub method) if this is not usable...
I don't really think there is a problem. Your Client calls a method on the server. That method results in an exception. Axis transforms this exception to something which can be send to the client to indicate the error. All exceptions, as far as I know, are wrapped into an AxisFault which is then transmitted to the client as, I believe, a SoapFault message with as description the exception message. In other words, the client should only see AxisFaults as the exception (exception class) is not serialized and send. Server exceptions should become AxisFaults at the client side.
191,842
<p>If I have a native C++ windows program (i.e. the entry point is WinMain) how do I view output from console functions like std::cout?</p>
[ { "answer_id": 191850, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 0, "selected": false, "text": "<p>Since there's no console window, this is <strike>impossible</strike> difficult. (Learn something new every day - I never knew about the console functions!)</p>\n\n<p>Is it possible for you to replace your output calls? I will often use TRACE or OutputDebugString to send information to the Visual Studio output window.</p>\n" }, { "answer_id": 191872, "author": "Chris Charabaruk", "author_id": 5697, "author_profile": "https://Stackoverflow.com/users/5697", "pm_score": 2, "selected": false, "text": "<p>Don't quote me on this, but the Win32 <a href=\"http://msdn.microsoft.com/en-us/library/ms682087(VS.85).aspx\" rel=\"nofollow noreferrer\">console API</a> might be what you're looking for. If you're just doing this for debugging purposes, however, you might be more interested in running <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx\" rel=\"nofollow noreferrer\">DebugView</a> and calling the <a href=\"http://msdn.microsoft.com/en-us/library/ms792790.aspx\" rel=\"nofollow noreferrer\">DbgPrint</a> function.</p>\n\n<p>This of course assumes its your application you want sending console output, not reading it from another application. In that case, pipes might be your friend.</p>\n" }, { "answer_id": 191880, "author": "luke", "author_id": 16434, "author_profile": "https://Stackoverflow.com/users/16434", "pm_score": 5, "selected": false, "text": "<p>Check out <a href=\"http://dslweb.nwnexus.com/~ast/dload/guicon.htm\" rel=\"noreferrer\">Adding Console I/O to a Win32 GUI App</a>. This may help you do what you want. </p>\n\n<p>If you don't have, or can't modify the code, try the suggestions found <a href=\"http://support.microsoft.com/kb/110930/en-us\" rel=\"noreferrer\">here</a> to redirect console output to a file.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> bit of thread necromancy here. I first answered this 9ish years ago, in the early days of SO, before the (good) policy of non-link-only answers came into effect. I'll repost the code from the original article in the hope to atone for my past sins.</p>\n\n<p><strong>guicon.cpp -- A console redirection function</strong></p>\n\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;fcntl.h&gt;\n#include &lt;io.h&gt;\n#include &lt;iostream&gt;\n#include &lt;fstream&gt;\n#ifndef _USE_OLD_IOSTREAMS\nusing namespace std;\n#endif\n// maximum mumber of lines the output console should have\nstatic const WORD MAX_CONSOLE_LINES = 500;\n#ifdef _DEBUG\nvoid RedirectIOToConsole()\n{\n int hConHandle;\n long lStdHandle;\n CONSOLE_SCREEN_BUFFER_INFO coninfo;\n FILE *fp;\n\n // allocate a console for this app\n AllocConsole();\n\n // set the screen buffer to be big enough to let us scroll text\n GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &amp;coninfo);\n coninfo.dwSize.Y = MAX_CONSOLE_LINES;\n SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize);\n\n // redirect unbuffered STDOUT to the console\n lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);\n hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);\n fp = _fdopen( hConHandle, \"w\" );\n *stdout = *fp;\n setvbuf( stdout, NULL, _IONBF, 0 );\n\n // redirect unbuffered STDIN to the console\n lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);\n hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);\n fp = _fdopen( hConHandle, \"r\" );\n *stdin = *fp;\n setvbuf( stdin, NULL, _IONBF, 0 );\n\n // redirect unbuffered STDERR to the console\n lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);\n hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);\n fp = _fdopen( hConHandle, \"w\" );\n *stderr = *fp;\n setvbuf( stderr, NULL, _IONBF, 0 );\n\n // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog\n // point to console as well\n ios::sync_with_stdio();\n}\n\n#endif\n//End of File\n</code></pre>\n\n<p><strong>guicon.h -- Interface to console redirection function</strong></p>\n\n<pre><code>#ifndef __GUICON_H__\n#define __GUICON_H__\n#ifdef _DEBUG\n\nvoid RedirectIOToConsole();\n\n#endif\n#endif\n\n// End of File\n</code></pre>\n\n<p><strong>test.cpp -- Demonstrating console redirection</strong></p>\n\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;iostream&gt;\n#include &lt;fstream&gt;\n#include &lt;conio.h&gt;\n#include &lt;stdio.h&gt;\n#ifndef _USE_OLD_OSTREAMS\nusing namespace std;\n#endif\n#include \"guicon.h\"\n\n\n#include &lt;crtdbg.h&gt;\n\nint APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)\n{\n #ifdef _DEBUG\n RedirectIOToConsole();\n #endif\n int iVar;\n\n // test stdio\n fprintf(stdout, \"Test output to stdout\\n\");\n fprintf(stderr, \"Test output to stderr\\n\");\n fprintf(stdout, \"Enter an integer to test stdin: \");\n scanf(\"%d\", &amp;iVar);\n printf(\"You entered %d\\n\", iVar);\n\n //test iostreams\n cout &lt;&lt; \"Test output to cout\" &lt;&lt; endl;\n cerr &lt;&lt; \"Test output to cerr\" &lt;&lt; endl;\n clog &lt;&lt; \"Test output to clog\" &lt;&lt; endl;\n cout &lt;&lt; \"Enter an integer to test cin: \";\n cin &gt;&gt; iVar;\n cout &lt;&lt; \"You entered \" &lt;&lt; iVar &lt;&lt; endl;\n #ifndef _USE_OLD_IOSTREAMS\n\n // test wide iostreams\n wcout &lt;&lt; L\"Test output to wcout\" &lt;&lt; endl;\n wcerr &lt;&lt; L\"Test output to wcerr\" &lt;&lt; endl;\n wclog &lt;&lt; L\"Test output to wclog\" &lt;&lt; endl;\n wcout &lt;&lt; L\"Enter an integer to test wcin: \";\n wcin &gt;&gt; iVar;\n wcout &lt;&lt; L\"You entered \" &lt;&lt; iVar &lt;&lt; endl;\n #endif\n\n // test CrtDbg output\n _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE );\n _CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDERR );\n _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );\n _CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDERR);\n _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE );\n _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR);\n _RPT0(_CRT_WARN, \"This is testing _CRT_WARN output\\n\");\n _RPT0(_CRT_ERROR, \"This is testing _CRT_ERROR output\\n\");\n _ASSERT( 0 &amp;&amp; \"testing _ASSERT\" );\n _ASSERTE( 0 &amp;&amp; \"testing _ASSERTE\" );\n Sleep(2000);\n return 0;\n}\n\n//End of File\n</code></pre>\n" }, { "answer_id": 191912, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 4, "selected": false, "text": "<p>You can also reopen the cout and cerr streams to output to a file as well. The following should work for this:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;fstream&gt;\n\nint main ()\n{\n std::ofstream file;\n file.open (\"cout.txt\");\n std::streambuf* sbuf = std::cout.rdbuf();\n std::cout.rdbuf(file.rdbuf());\n //cout is now pointing to a file\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 433333, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>creating a pipe, execute the program console CreateProcess() and read with ReadFile() or writes in console WriteFile() </p>\n\n<pre><code> HANDLE hRead ; // ConsoleStdInput\n HANDLE hWrite; // ConsoleStdOutput and ConsoleStdError\n\n STARTUPINFO stiConsole;\n SECURITY_ATTRIBUTES segConsole;\n PROCESS_INFORMATION priConsole;\n\n segConsole.nLength = sizeof(segConsole);\n segConsole.lpSecurityDescriptor = NULL;\n segConsole.bInheritHandle = TRUE;\n\nif(CreatePipe(&amp;hRead,&amp;hWrite,&amp;segConsole,0) )\n{\n\n FillMemory(&amp;stiConsole,sizeof(stiConsole),0);\n stiConsole.cb = sizeof(stiConsole);\nGetStartupInfo(&amp;stiConsole);\nstiConsole.hStdOutput = hWrite;\nstiConsole.hStdError = hWrite;\nstiConsole.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;\nstiConsole.wShowWindow = SW_HIDE; // execute hide \n\n if(CreateProcess(NULL, \"c:\\\\teste.exe\",NULL,NULL,TRUE,NULL,\n NULL,NULL,&amp;stiConsole,&amp;priConsole) == TRUE)\n {\n //readfile and/or writefile\n} \n</code></pre>\n\n<p>} </p>\n" }, { "answer_id": 42422951, "author": "Kamran Bigdely", "author_id": 81306, "author_profile": "https://Stackoverflow.com/users/81306", "pm_score": 2, "selected": false, "text": "<p>Go to Project>Project Properties>Linker>System and in the right pane, set <strong>SubSystems</strong> option to <strong>Console(/SUBSYSTEM:CONSOLE)</strong></p>\n\n<p>Then compile your program and run it from console to see whether you command prompt shows your outputs or not.</p>\n" }, { "answer_id": 45439182, "author": "Florian Winter", "author_id": 2279059, "author_profile": "https://Stackoverflow.com/users/2279059", "pm_score": 3, "selected": false, "text": "<p>If you are sending the output of your program to a file or pipe, e.g.</p>\n\n<pre><code>myprogram.exe &gt; file.txt\nmyprogram.exe | anotherprogram.exe\n</code></pre>\n\n<p>or you are invoking your program from another program and capturing its output through a pipe, then you don't need to change anything. It will just work, even if the entry point is <code>WinMain</code>.</p>\n\n<p>However, if you are running your program in a console or in Visual Studio, then the output will not appear in the console or in the Output window of Visual Studio. If you want to see the output \"live\", then try one of the other answers.</p>\n\n<p>Basically, this means that standard output works just like with console applications, but it isn't connected to a console in which you are running your application, and there seems to be no easy way to do that (all the other solutions presented here connect the output to a new console window that will pop up when you run your application, even from another console).</p>\n" }, { "answer_id": 46050762, "author": "Sev", "author_id": 1513612, "author_profile": "https://Stackoverflow.com/users/1513612", "pm_score": 3, "selected": false, "text": "<p>Using a combination of <a href=\"https://stackoverflow.com/a/191880\">luke's answer</a> and <a href=\"https://stackoverflow.com/a/25927081/1513612\">Roger's answer here</a> worked for me in my Windows Desktop Application project.</p>\n\n<pre><code>void RedirectIOToConsole() {\n\n //Create a console for this application\n AllocConsole();\n\n // Get STDOUT handle\n HANDLE ConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);\n int SystemOutput = _open_osfhandle(intptr_t(ConsoleOutput), _O_TEXT);\n FILE *COutputHandle = _fdopen(SystemOutput, \"w\");\n\n // Get STDERR handle\n HANDLE ConsoleError = GetStdHandle(STD_ERROR_HANDLE);\n int SystemError = _open_osfhandle(intptr_t(ConsoleError), _O_TEXT);\n FILE *CErrorHandle = _fdopen(SystemError, \"w\");\n\n // Get STDIN handle\n HANDLE ConsoleInput = GetStdHandle(STD_INPUT_HANDLE);\n int SystemInput = _open_osfhandle(intptr_t(ConsoleInput), _O_TEXT);\n FILE *CInputHandle = _fdopen(SystemInput, \"r\");\n\n //make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog point to console as well\n ios::sync_with_stdio(true);\n\n // Redirect the CRT standard input, output, and error handles to the console\n freopen_s(&amp;CInputHandle, \"CONIN$\", \"r\", stdin);\n freopen_s(&amp;COutputHandle, \"CONOUT$\", \"w\", stdout);\n freopen_s(&amp;CErrorHandle, \"CONOUT$\", \"w\", stderr);\n\n //Clear the error state for each of the C++ standard stream objects. We need to do this, as\n //attempts to access the standard streams before they refer to a valid target will cause the\n //iostream objects to enter an error state. In versions of Visual Studio after 2005, this seems\n //to always occur during startup regardless of whether anything has been read from or written to\n //the console or not.\n std::wcout.clear();\n std::cout.clear();\n std::wcerr.clear();\n std::cerr.clear();\n std::wcin.clear();\n std::cin.clear();\n\n}\n</code></pre>\n" }, { "answer_id": 52717331, "author": "John Blackburn", "author_id": 8966081, "author_profile": "https://Stackoverflow.com/users/8966081", "pm_score": 3, "selected": false, "text": "<p>Actually there is a much simpler solution than any proposed so far. Your Windows program will have a WinMain function so just add this \"dummy\" main function as well</p>\n\n<pre><code>int main()\n{\n return WinMain(GetModuleHandle(NULL), NULL, GetCommandLineA(), SW_SHOWNORMAL);\n}\n</code></pre>\n\n<p>You can now compile using MSVC like this</p>\n\n<pre><code>cl /nologo /c /EHsc myprog.c\nlink /nologo /out:myprog.exe /subsystem:console myprog.obj user32.lib gdi32.lib\n</code></pre>\n\n<p>(you may need to add more library links)</p>\n\n<p>When you run the program any <code>printf</code> will be written to the command prompt.</p>\n\n<p>If you are using gcc (mingw) to compile for Windows you don't need a dummy main function, just do</p>\n\n<pre><code>gcc -o myprog.exe myprog.c -luser32 -lgdi32\n</code></pre>\n\n<p>(ie avoid using the <code>-mwindows</code> flag which will prevent writing to a console. That flag will be useful when you create the final GUI release) Again you may need to specify more libraries if using more windows features)</p>\n" }, { "answer_id": 55875595, "author": "Chris Olsen", "author_id": 2118271, "author_profile": "https://Stackoverflow.com/users/2118271", "pm_score": 5, "selected": false, "text": "<p>The problem some of the other answers is that they unnecessarily create new <code>FILE</code> instances which are then leaked and can cause debug assertions in the CRT cleanup code.</p>\n<p><a href=\"https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/freopen-s-wfreopen-s?view=vs-2019\" rel=\"noreferrer\">freopen_s</a> is all that is really needed:</p>\n<pre><code>FILE* fp = nullptr;\nfreopen_s(&amp;fp, &quot;CONIN$&quot;, &quot;r&quot;, stdin);\nfreopen_s(&amp;fp, &quot;CONOUT$&quot;, &quot;w&quot;, stdout);\nfreopen_s(&amp;fp, &quot;CONOUT$&quot;, &quot;w&quot;, stderr);\n</code></pre>\n<p>You'll probably want to do a little error checking and cleanup as well. Below is the complete solution that I currently use.</p>\n<p><strong>Redirecting Console Standard IO:</strong></p>\n<pre><code>bool RedirectConsoleIO()\n{\n bool result = true;\n FILE* fp;\n\n // Redirect STDIN if the console has an input handle\n if (GetStdHandle(STD_INPUT_HANDLE) != INVALID_HANDLE_VALUE)\n if (freopen_s(&amp;fp, &quot;CONIN$&quot;, &quot;r&quot;, stdin) != 0)\n result = false;\n else\n setvbuf(stdin, NULL, _IONBF, 0);\n\n // Redirect STDOUT if the console has an output handle\n if (GetStdHandle(STD_OUTPUT_HANDLE) != INVALID_HANDLE_VALUE)\n if (freopen_s(&amp;fp, &quot;CONOUT$&quot;, &quot;w&quot;, stdout) != 0)\n result = false;\n else\n setvbuf(stdout, NULL, _IONBF, 0);\n\n // Redirect STDERR if the console has an error handle\n if (GetStdHandle(STD_ERROR_HANDLE) != INVALID_HANDLE_VALUE)\n if (freopen_s(&amp;fp, &quot;CONOUT$&quot;, &quot;w&quot;, stderr) != 0)\n result = false;\n else\n setvbuf(stderr, NULL, _IONBF, 0);\n\n // Make C++ standard streams point to console as well.\n ios::sync_with_stdio(true);\n\n // Clear the error state for each of the C++ standard streams.\n std::wcout.clear();\n std::cout.clear();\n std::wcerr.clear();\n std::cerr.clear();\n std::wcin.clear();\n std::cin.clear();\n\n return result;\n}\n</code></pre>\n<p><strong>Releasing a Console:</strong></p>\n<pre><code>bool ReleaseConsole()\n{\n bool result = true;\n FILE* fp;\n\n // Just to be safe, redirect standard IO to NUL before releasing.\n\n // Redirect STDIN to NUL\n if (freopen_s(&amp;fp, &quot;NUL:&quot;, &quot;r&quot;, stdin) != 0)\n result = false;\n else\n setvbuf(stdin, NULL, _IONBF, 0);\n\n // Redirect STDOUT to NUL\n if (freopen_s(&amp;fp, &quot;NUL:&quot;, &quot;w&quot;, stdout) != 0)\n result = false;\n else\n setvbuf(stdout, NULL, _IONBF, 0);\n\n // Redirect STDERR to NUL\n if (freopen_s(&amp;fp, &quot;NUL:&quot;, &quot;w&quot;, stderr) != 0)\n result = false;\n else\n setvbuf(stderr, NULL, _IONBF, 0);\n\n // Detach from console\n if (!FreeConsole())\n result = false;\n\n return result;\n}\n</code></pre>\n<p><strong>Resizing Console Buffer:</strong></p>\n<pre><code>void AdjustConsoleBuffer(int16_t minLength)\n{\n // Set the screen buffer to be big enough to scroll some text\n CONSOLE_SCREEN_BUFFER_INFO conInfo;\n GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &amp;conInfo);\n if (conInfo.dwSize.Y &lt; minLength)\n conInfo.dwSize.Y = minLength;\n SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), conInfo.dwSize);\n}\n</code></pre>\n<p><strong>Allocating a New Console:</strong></p>\n<pre><code>bool CreateNewConsole(int16_t minLength)\n{\n bool result = false;\n\n // Release any current console and redirect IO to NUL\n ReleaseConsole();\n\n // Attempt to create new console\n if (AllocConsole())\n {\n AdjustConsoleBuffer(minLength);\n result = RedirectConsoleIO();\n }\n\n return result;\n}\n</code></pre>\n<p><strong>Attaching to Parent's Console:</strong></p>\n<pre><code>bool AttachParentConsole(int16_t minLength)\n{\n bool result = false;\n\n // Release any current console and redirect IO to NUL\n ReleaseConsole();\n\n // Attempt to attach to parent process's console\n if (AttachConsole(ATTACH_PARENT_PROCESS))\n {\n AdjustConsoleBuffer(minLength);\n result = RedirectConsoleIO();\n }\n\n return result;\n}\n</code></pre>\n<p><strong>Calling from WinMain:</strong></p>\n<p>Link with <code>/SUBSYSTEM:Windows</code></p>\n<pre><code>int APIENTRY WinMain(\n HINSTANCE /*hInstance*/,\n HINSTANCE /*hPrevInstance*/,\n LPTSTR /*lpCmdLine*/,\n int /*cmdShow*/)\n{\n if (CreateNewConsole(1024))\n {\n int i;\n\n // test stdio\n fprintf(stdout, &quot;Test output to stdout\\n&quot;);\n fprintf(stderr, &quot;Test output to stderr\\n&quot;);\n fprintf(stdout, &quot;Enter an integer to test stdin: &quot;);\n scanf(&quot;%d&quot;, &amp;i);\n printf(&quot;You entered %d\\n&quot;, i);\n\n // test iostreams\n std::cout &lt;&lt; &quot;Test output to std::cout&quot; &lt;&lt; std::endl;\n std::cerr &lt;&lt; &quot;Test output to std::cerr&quot; &lt;&lt; std::endl;\n std::clog &lt;&lt; &quot;Test output to std::clog&quot; &lt;&lt; std::endl;\n std::cout &lt;&lt; &quot;Enter an integer to test std::cin: &quot;;\n std::cin &gt;&gt; i;\n std::cout &lt;&lt; &quot;You entered &quot; &lt;&lt; i &lt;&lt; std::endl;\n\n std::cout &lt;&lt; endl &lt;&lt; &quot;Press any key to continue...&quot; &lt;&lt; endl;\n _getch();\n\n ReleaseConsole();\n }\n\n return 0;\n};\n</code></pre>\n" }, { "answer_id": 56834698, "author": "Slion", "author_id": 3969362, "author_profile": "https://Stackoverflow.com/users/3969362", "pm_score": 2, "selected": false, "text": "<p>As mentioned <a href=\"https://stackoverflow.com/a/42422951/3969362\">there</a> and <a href=\"https://stackoverflow.com/a/52717331/3969362\">there</a> the easiest solution is to use your Project Property Pages to switch back and forth between <code>CONSOLE</code> and <code>WINDOWS</code> SubSytems to enable or disable console output at will.</p>\n\n<p><a href=\"https://i.stack.imgur.com/Cg1SH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Cg1SH.png\" alt=\"Project Properties\"></a></p>\n\n<p>Your program will just need <code>main</code> and <code>WinMain</code> entry points to make sure both configuration are compiling.\nThe <code>main</code> function simply calling <code>WinMain</code> as shown below for instance:</p>\n\n<pre><code>int main()\n{\ncout &lt;&lt; \"Output standard\\n\";\ncerr &lt;&lt; \"Output error\\n\";\n\nreturn WinMain(GetModuleHandle(NULL), NULL, GetCommandLineA(), SW_SHOWNORMAL);\n}\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23120/" ]
If I have a native C++ windows program (i.e. the entry point is WinMain) how do I view output from console functions like std::cout?
Check out [Adding Console I/O to a Win32 GUI App](http://dslweb.nwnexus.com/~ast/dload/guicon.htm). This may help you do what you want. If you don't have, or can't modify the code, try the suggestions found [here](http://support.microsoft.com/kb/110930/en-us) to redirect console output to a file. --- **Edit:** bit of thread necromancy here. I first answered this 9ish years ago, in the early days of SO, before the (good) policy of non-link-only answers came into effect. I'll repost the code from the original article in the hope to atone for my past sins. **guicon.cpp -- A console redirection function** ``` #include <windows.h> #include <stdio.h> #include <fcntl.h> #include <io.h> #include <iostream> #include <fstream> #ifndef _USE_OLD_IOSTREAMS using namespace std; #endif // maximum mumber of lines the output console should have static const WORD MAX_CONSOLE_LINES = 500; #ifdef _DEBUG void RedirectIOToConsole() { int hConHandle; long lStdHandle; CONSOLE_SCREEN_BUFFER_INFO coninfo; FILE *fp; // allocate a console for this app AllocConsole(); // set the screen buffer to be big enough to let us scroll text GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &coninfo); coninfo.dwSize.Y = MAX_CONSOLE_LINES; SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE), coninfo.dwSize); // redirect unbuffered STDOUT to the console lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "w" ); *stdout = *fp; setvbuf( stdout, NULL, _IONBF, 0 ); // redirect unbuffered STDIN to the console lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "r" ); *stdin = *fp; setvbuf( stdin, NULL, _IONBF, 0 ); // redirect unbuffered STDERR to the console lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE); hConHandle = _open_osfhandle(lStdHandle, _O_TEXT); fp = _fdopen( hConHandle, "w" ); *stderr = *fp; setvbuf( stderr, NULL, _IONBF, 0 ); // make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog // point to console as well ios::sync_with_stdio(); } #endif //End of File ``` **guicon.h -- Interface to console redirection function** ``` #ifndef __GUICON_H__ #define __GUICON_H__ #ifdef _DEBUG void RedirectIOToConsole(); #endif #endif // End of File ``` **test.cpp -- Demonstrating console redirection** ``` #include <windows.h> #include <iostream> #include <fstream> #include <conio.h> #include <stdio.h> #ifndef _USE_OLD_OSTREAMS using namespace std; #endif #include "guicon.h" #include <crtdbg.h> int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { #ifdef _DEBUG RedirectIOToConsole(); #endif int iVar; // test stdio fprintf(stdout, "Test output to stdout\n"); fprintf(stderr, "Test output to stderr\n"); fprintf(stdout, "Enter an integer to test stdin: "); scanf("%d", &iVar); printf("You entered %d\n", iVar); //test iostreams cout << "Test output to cout" << endl; cerr << "Test output to cerr" << endl; clog << "Test output to clog" << endl; cout << "Enter an integer to test cin: "; cin >> iVar; cout << "You entered " << iVar << endl; #ifndef _USE_OLD_IOSTREAMS // test wide iostreams wcout << L"Test output to wcout" << endl; wcerr << L"Test output to wcerr" << endl; wclog << L"Test output to wclog" << endl; wcout << L"Enter an integer to test wcin: "; wcin >> iVar; wcout << L"You entered " << iVar << endl; #endif // test CrtDbg output _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDERR ); _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDERR); _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDERR); _RPT0(_CRT_WARN, "This is testing _CRT_WARN output\n"); _RPT0(_CRT_ERROR, "This is testing _CRT_ERROR output\n"); _ASSERT( 0 && "testing _ASSERT" ); _ASSERTE( 0 && "testing _ASSERTE" ); Sleep(2000); return 0; } //End of File ```
191,844
<p>I have a Java array such as: </p> <pre><code>String[] arr = new String[] {"123","doc","projectReport.doc"}; </code></pre> <p>In my opinion the natural way to access would be: </p> <pre><code> #set($att_id = $arr[0]) #set($att_type = $arr[1]) #set($att_name = $arr[2]) </code></pre> <p>But that it is not working. I have come with this workaround. But it a bit too much code for such an easy task. </p> <pre><code>#set($counter = 0) #foreach($el in $arr) #if($counter==0) #set($att_id = $el) #elseif($counter==1) #set($att_type = $el) #elseif($counter==2) #set($att_name = $el) #end #set($counter = $counter + 1) #end </code></pre> <p>Is there any other way?</p>
[ { "answer_id": 192018, "author": "Brian", "author_id": 8959, "author_profile": "https://Stackoverflow.com/users/8959", "pm_score": 3, "selected": false, "text": "<p>You could wrap the array in a <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/util/List.html\" rel=\"nofollow noreferrer\"><code>List</code></a> using <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Arrays.html#asList%28T...%29\" rel=\"nofollow noreferrer\"><code>Arrays.asList(T... a)</code></a>. The new List object is backed by the original array so it doesn't wastefully allocate a copy. Even changes made to the new List will propagate back to the array.</p>\n\n<p>Then you can use <code>$list.get(int index)</code> to get your objects out in Velocity.</p>\n\n<p>If you need to get just one or two objects from an array, you can also use <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/reflect/Array.html#get%28java.lang.Object%2C%20int%29\" rel=\"nofollow noreferrer\"><code>Array.get(Object array, int index)</code></a>\nto get an item from an array.</p>\n" }, { "answer_id": 198758, "author": "Angelo van der Sijpt", "author_id": 19144, "author_profile": "https://Stackoverflow.com/users/19144", "pm_score": 1, "selected": false, "text": "<p><a href=\"https://stackoverflow.com/questions/191844/what-is-the-best-way-to-access-an-array-inside-velocity#192018\">Brian's answer</a> is indeed correct, although you might like to know that upcoming Velocity 1.6 has direct support for arrays; see the <a href=\"http://velocity.apache.org/engine/devel/developer-guide.html#support-for-iterative-objects-for-foreach\" rel=\"nofollow noreferrer\">Velocity documentation</a> for more information.</p>\n" }, { "answer_id": 505343, "author": "Nathan Bubna", "author_id": 8131, "author_profile": "https://Stackoverflow.com/users/8131", "pm_score": 5, "selected": false, "text": "<p>You can use use Velocity 1.6: for an array named <code>$array</code> one can simply do <code>$array.get($index)</code>.</p>\n\n<p>In the upcoming Velocity 1.7, one will be able to do <code>$array[$index]</code> (as well as <code>$list[$index]</code> and <code>$map[$key]</code>).</p>\n" }, { "answer_id": 856296, "author": "Luke Quinane", "author_id": 18437, "author_profile": "https://Stackoverflow.com/users/18437", "pm_score": 0, "selected": false, "text": "<p>I ended up using the <a href=\"http://velocity.apache.org/tools/releases/1.4/javadoc/org/apache/velocity/tools/generic/ListTool.html\" rel=\"nofollow noreferrer\">ListTool</a> from the velocity-tools.jar. It has methods to access an array's elements and also get its size.</p>\n" }, { "answer_id": 1309539, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>there is an implicit counter $velocityCount which starts with value 1 so you do not have to create your own counter.</p>\n" }, { "answer_id": 1944487, "author": "Rajesh Chowdary", "author_id": 236613, "author_profile": "https://Stackoverflow.com/users/236613", "pm_score": 2, "selected": false, "text": "<pre><code>String[] arr = new String[] {\"123\", \"doc\", \"projectReport.doc\"}; \n</code></pre>\n\n<p>In my opinion the natural way to access would be: </p>\n\n<pre><code> #set($att_id = $arr[0]) \n #set($att_type = $arr[1]) \n #set($att_name = $arr[2]) \n</code></pre>\n\n<p>The value for this can be get by using <code>$array.get(\"arr\", 1)</code> because there is no direct way to get the value from array like <code>$att_id = $arr[0]</code> in velocity.<br>\nHope it works :)</p>\n" }, { "answer_id": 27402057, "author": "Valentino Ciciarelli", "author_id": 4345827, "author_profile": "https://Stackoverflow.com/users/4345827", "pm_score": 0, "selected": false, "text": "<p>I has the same question and it got answered on another thread</p>\n\n<pre><code>#set ( $Page = $additionalParams.get('Page') )\n#set ( $Pages = [] )\n#if ( $Page != $null &amp;&amp; $Page != \"\" )\n #foreach($i in $Page.split(\";\"))\n $Pages.add($i)\n #end\n#end\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/17035177/array-indexing-in-confluence-velocity-templates/17100999#17100999?newreg=4b7840e98b0a44b3b8112a26bcd3689c\">Array indexing in Confluence / Velocity templates</a></p>\n" }, { "answer_id": 54374469, "author": "trndjc", "author_id": 9086770, "author_profile": "https://Stackoverflow.com/users/9086770", "pm_score": 2, "selected": false, "text": "<p><strong>Velocity 1.6</strong></p>\n\n<pre><code>$myarray.isEmpty()\n$myarray.size()\n$myarray.get(2)\n$myarray.set(1, 'test')\n</code></pre>\n\n<p><a href=\"http://velocity.apache.org/engine/1.7/user-guide.html\" rel=\"nofollow noreferrer\">http://velocity.apache.org/engine/1.7/user-guide.html</a></p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
I have a Java array such as: ``` String[] arr = new String[] {"123","doc","projectReport.doc"}; ``` In my opinion the natural way to access would be: ``` #set($att_id = $arr[0]) #set($att_type = $arr[1]) #set($att_name = $arr[2]) ``` But that it is not working. I have come with this workaround. But it a bit too much code for such an easy task. ``` #set($counter = 0) #foreach($el in $arr) #if($counter==0) #set($att_id = $el) #elseif($counter==1) #set($att_type = $el) #elseif($counter==2) #set($att_name = $el) #end #set($counter = $counter + 1) #end ``` Is there any other way?
You can use use Velocity 1.6: for an array named `$array` one can simply do `$array.get($index)`. In the upcoming Velocity 1.7, one will be able to do `$array[$index]` (as well as `$list[$index]` and `$map[$key]`).
191,845
<p>Currently, I've got images (max. 6MB) stored as BLOB in a InnoDB table. As the size of the data is growing, the nightly backup is growing slower and slower hindering normal performance.</p> <p>So, the binary data needs to go to the file system. (pointers to the files will be kept in the DB.)</p> <p>The data has a tree like relation:</p> <pre><code>- main site - user_0 - album_0 - album_1 - album_n - user_1 - user_n etc... </code></pre> <p>Now I want the data to be distributed evenly trough the directory structure. How should I accomplish this?</p> <p>I guess I could try <code>MD5('userId, albumId, imageId');</code> and slice up the resulting string to get my directory path:</p> <pre> /var/imageStorage/f/347e/013b/c042/51cf/985f7ad0daa987d.jpeg </pre> <p>This would allow me to map the first character to a server and evenly distribute the directory structure over multiple servers.</p> <p>This would however <em>not</em> keep images organised per user, likely spreading the images for 1 album over multiple servers.</p> <p>My question is:<br> What is the best way to store the image data in the file system in a balanced way, while keeping user/album data together ?</p> <p>Am I thinking in the right direction? or is this the wrong way of doing things altogether?</p> <p><strong>Update:</strong><br> I will go for the <code>md5(user_id)</code> string slicing for the split up on highest level. And then put all user data in that same bucket. This will ensure an even distribution of data while keeping user data stored close together.</p> <pre> /var - imageStorage - f/347e/013b - f347e013bc04251cf985f7ad0daa987d - 0 - album1_10 - picture_1.jpeg - 1 - album1_1 - picture_2.jpeg - picture_3.jpeg - album1_11 - picture_n.jpeg - n - album1_n </pre> <p>I think I will use albumId splitted up from behind (I like that idea!) as to keep the number of albums per directory smaller (although it won't be necessary for most users). </p> <p>Thanks!</p>
[ { "answer_id": 191863, "author": "Node", "author_id": 7190, "author_profile": "https://Stackoverflow.com/users/7190", "pm_score": 6, "selected": true, "text": "<p>Just split your userid from behind. e.g.</p>\n\n<pre><code>UserID = 6435624 \nPath = /images/24/56/6435624\n</code></pre>\n\n<p>As for the backup you could use MySQL Replication and backup the slave \ndatabase to avoid problems (e.g. locks) while backuping.</p>\n" }, { "answer_id": 194206, "author": "Alex Lehmann", "author_id": 27069, "author_profile": "https://Stackoverflow.com/users/27069", "pm_score": 3, "selected": false, "text": "<p>one thing about distributing the filenames into different directories, if you consider splitting your md5 filenames into different subdirectories (which is generally a good idea), I would suggest keeping the complete hash as filename and duplicate the first few chars as directory names. This way you will make it easier to identify files e.g. when you have to move directories.</p>\n\n<p>e.g.</p>\n\n<p>abcdefgh.jpg -> a/ab/abc/abcdefgh.jpg</p>\n\n<p>if your filenames are not evenly distributed (not a hash), try to choose a splitting method that gets an even distribution, e.g. the last characters if it is an incrementing user-id</p>\n" }, { "answer_id": 21829997, "author": "fustaki", "author_id": 1578918, "author_profile": "https://Stackoverflow.com/users/1578918", "pm_score": 2, "selected": false, "text": "<p>I'm using this strategy given a unique picture ID</p>\n\n<ul>\n<li>reverse the string</li>\n<li>zerofill it with leading zero if there's an odd number of digits</li>\n<li>chunk the string into two-digits substrings</li>\n<li><p>build the path as below</p>\n\n<pre><code>17 &gt;&gt; 71 &gt;&gt; /71.jpg\n163 &gt;&gt; 0361 &gt;&gt; /03/61.jpg\n6978 &gt;&gt; 8796 &gt;&gt; /87/96.jpg \n1687941 &gt;&gt; 01497861 &gt;&gt; /01/49/78/61.jpg\n</code></pre></li>\n</ul>\n\n<p>This method ensures that each folder contains up to 100 pictures and 100 sub-folders and the load is evenly distributed between the left-most folders.</p>\n\n<p>Moreover, you just need the ID of the picture to reach the file, no need to read picture table containing other metadata.\nUser data are not stored close together indeed and the ID-Path relation is predictable, it depends on your needs.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22674/" ]
Currently, I've got images (max. 6MB) stored as BLOB in a InnoDB table. As the size of the data is growing, the nightly backup is growing slower and slower hindering normal performance. So, the binary data needs to go to the file system. (pointers to the files will be kept in the DB.) The data has a tree like relation: ``` - main site - user_0 - album_0 - album_1 - album_n - user_1 - user_n etc... ``` Now I want the data to be distributed evenly trough the directory structure. How should I accomplish this? I guess I could try `MD5('userId, albumId, imageId');` and slice up the resulting string to get my directory path: ``` /var/imageStorage/f/347e/013b/c042/51cf/985f7ad0daa987d.jpeg ``` This would allow me to map the first character to a server and evenly distribute the directory structure over multiple servers. This would however *not* keep images organised per user, likely spreading the images for 1 album over multiple servers. My question is: What is the best way to store the image data in the file system in a balanced way, while keeping user/album data together ? Am I thinking in the right direction? or is this the wrong way of doing things altogether? **Update:** I will go for the `md5(user_id)` string slicing for the split up on highest level. And then put all user data in that same bucket. This will ensure an even distribution of data while keeping user data stored close together. ``` /var - imageStorage - f/347e/013b - f347e013bc04251cf985f7ad0daa987d - 0 - album1_10 - picture_1.jpeg - 1 - album1_1 - picture_2.jpeg - picture_3.jpeg - album1_11 - picture_n.jpeg - n - album1_n ``` I think I will use albumId splitted up from behind (I like that idea!) as to keep the number of albums per directory smaller (although it won't be necessary for most users). Thanks!
Just split your userid from behind. e.g. ``` UserID = 6435624 Path = /images/24/56/6435624 ``` As for the backup you could use MySQL Replication and backup the slave database to avoid problems (e.g. locks) while backuping.
191,855
<p>If I have added/removed/modified a large number of files in my local ClearCase view, how can I be certain that all the files have been added to source control?</p>
[ { "answer_id": 191857, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 3, "selected": false, "text": "<p>Use <code>cleartool ls -view_only -r</code> from the your local view VOB directory.</p>\n\n<p>To add any files recursively to source control that are only in the local view, see <a href=\"https://stackoverflow.com/questions/138321/how-can-i-use-clearcase-to-add-to-source-control-recursively\">How can I use ClearCase to “add to source control …” recursively?</a>.</p>\n" }, { "answer_id": 191964, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": true, "text": "<p>Your answer is correct, for <strong><em>snapshot</em></strong> views (which you call 'local view' ?)<br>\nIn a dynamic view, a simple</p>\n\n<pre><code>cleartool lsprivate\n</code></pre>\n\n<p>would suffice.</p>\n\n<p>But that would leave out <em>hijacked</em> files (which are already added to source control, but may have been modified without ClearCase knowing it)</p>\n\n<p>So I would recommend to complete your command with (for Windows):</p>\n\n<pre><code>for /F \"usebackq delims= \" %i in (`cleartool ls -r -nxn ^| find \"hijacked\"`) do @echo %i\n</code></pre>\n\n<p>For Unix:</p>\n\n<pre><code>cleartool ls -r -nxn | grep hijacked\n</code></pre>\n\n<p>That would also leave files in checkouts (granted, they also are added to source control, but should be also listed as they must be eventually committed or cancelled).<br>\nIn Snapshot views:</p>\n\n<pre><code>cleartool lscheckout -recur\n</code></pre>\n\n<p>In Dynamic views:</p>\n\n<pre><code>cleartool lsprivate –co\n</code></pre>\n" }, { "answer_id": 9827214, "author": "MoMo", "author_id": 176728, "author_profile": "https://Stackoverflow.com/users/176728", "pm_score": 3, "selected": false, "text": "<p>I use a similar dos command for windows, but I also pipe the results of the clear tool command to findstr to '<b>ignore</b>' specific patterns (using regex) such as .keep files, dll's, and compiled files and folder locations that I don't want to add to source.</p>\n\n<p>Run the following command from the root folder of your view. If you have multiple top level folders then you'll need to run it once for each folder. Also, I believe this only works for <b>SnapShot</b> views.</p>\n\n<pre><code>cleartool ls -recurse -view_only | findstr /vi \".dll$ .pdb$ .suo$ .keep$ .unloaded$ \\\\bin$ \\\\bin\\\\ \\\\debug$ \\\\debug\\\\ \\\\release$ \\\\release\\\\ \\\\obj$ \\\\obj\\\\ ^cleartool$\" &gt; c:\\ItemsNotInSource.txt\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9254/" ]
If I have added/removed/modified a large number of files in my local ClearCase view, how can I be certain that all the files have been added to source control?
Your answer is correct, for ***snapshot*** views (which you call 'local view' ?) In a dynamic view, a simple ``` cleartool lsprivate ``` would suffice. But that would leave out *hijacked* files (which are already added to source control, but may have been modified without ClearCase knowing it) So I would recommend to complete your command with (for Windows): ``` for /F "usebackq delims= " %i in (`cleartool ls -r -nxn ^| find "hijacked"`) do @echo %i ``` For Unix: ``` cleartool ls -r -nxn | grep hijacked ``` That would also leave files in checkouts (granted, they also are added to source control, but should be also listed as they must be eventually committed or cancelled). In Snapshot views: ``` cleartool lscheckout -recur ``` In Dynamic views: ``` cleartool lsprivate –co ```
191,879
<p>Eg.</p> <pre><code>ConnectionDetails cd = new ConnectionDetails (); cd.ProviderName = "System.Data.OleDb"; cd.DataSource = "serverAddress"; cd.Catalog = "database"; cd.UserId = "userId"; cd.Password = "password"; string connectionString = cs.CreateConnectionString(); // Should return: // "Provider=SQLOLEDB;Data Source=serverAddress;Initial Catalog=database;User Id=userId;Password=password;" </code></pre> <p>I'd write my own class but I'm not sure how to retrieve a connection string provider property (SQLOLEDB in this example) programmatically from an invariant db provider name (System.Data.OleDb).</p> <p>Edit:</p> <p>You can do a</p> <pre><code>DbProviderFactories.GetFactory("System.Data.OleDB").CreateConnectionStringBuilder() </code></pre> <p>But the DBConnectionStringBuilder that is returned still doesn't know it's connection string provider property, even though in this case it the derived class has a "Provider" property.</p>
[ { "answer_id": 191932, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 2, "selected": false, "text": "<p>The closest thing I know of is <a href=\"http://msdn.microsoft.com/en-us/library/system.data.common.dbconnectionstringbuilder.aspx\" rel=\"nofollow noreferrer\">DbConnectionStringBuilder</a>.</p>\n\n<p>Because the properties required by different providers vary, it uses an associative array (name value collection) rather than fixed properties.</p>\n\n<p>So your example would look like</p>\n\n<pre><code>DbConnectionStringBuilder csb = new DbConnectionStringBuilder();\ncsb[\"ProviderName\"] = \"System.Data.OleDb\";\ncsb[\"DataSource\"] = \"serverAddress\";\ncsb[\"Catalog\"] = \"database\";\ncsb[\"UserId\"] = \"userId\";\ncsb[\"Password\"] = \"password\";\n\nstring connectionString = csb.ConnectionString;\n</code></pre>\n" }, { "answer_id": 193060, "author": "Jeffrey L Whitledge", "author_id": 10174, "author_profile": "https://Stackoverflow.com/users/10174", "pm_score": 0, "selected": false, "text": "<p>There is an OleDbConnectionStringBuilder class that will create the connection string for you. </p>\n\n<p>But it sounds like you are trying to get it to generate the provider name for you, and I don't think it really works that way. Since the provider name can vary, that is something that you are going to have to supply to tell the connection what to do. Whatever mechanism you are using to select your database connection (or to drive your database connection factory methods if you're going that route), it will also have to provide the provider name.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9825/" ]
Eg. ``` ConnectionDetails cd = new ConnectionDetails (); cd.ProviderName = "System.Data.OleDb"; cd.DataSource = "serverAddress"; cd.Catalog = "database"; cd.UserId = "userId"; cd.Password = "password"; string connectionString = cs.CreateConnectionString(); // Should return: // "Provider=SQLOLEDB;Data Source=serverAddress;Initial Catalog=database;User Id=userId;Password=password;" ``` I'd write my own class but I'm not sure how to retrieve a connection string provider property (SQLOLEDB in this example) programmatically from an invariant db provider name (System.Data.OleDb). Edit: You can do a ``` DbProviderFactories.GetFactory("System.Data.OleDB").CreateConnectionStringBuilder() ``` But the DBConnectionStringBuilder that is returned still doesn't know it's connection string provider property, even though in this case it the derived class has a "Provider" property.
The closest thing I know of is [DbConnectionStringBuilder](http://msdn.microsoft.com/en-us/library/system.data.common.dbconnectionstringbuilder.aspx). Because the properties required by different providers vary, it uses an associative array (name value collection) rather than fixed properties. So your example would look like ``` DbConnectionStringBuilder csb = new DbConnectionStringBuilder(); csb["ProviderName"] = "System.Data.OleDb"; csb["DataSource"] = "serverAddress"; csb["Catalog"] = "database"; csb["UserId"] = "userId"; csb["Password"] = "password"; string connectionString = csb.ConnectionString; ```
191,881
<p>I need to <a href="https://en.wikipedia.org/wiki/Serialization" rel="noreferrer">serialize</a> an object to <a href="https://www.json.org/" rel="noreferrer">JSON</a>. I'm using <a href="https://api.jquery.com/" rel="noreferrer">jQuery</a>. Is there a "standard" way to do this?</p> <p>My specific situation: I have an array defined as shown below:</p> <pre><code>var countries = new Array(); countries[0] = 'ga'; countries[1] = 'cd'; ... </code></pre> <p>and I need to turn this into a string to pass to <a href="https://www.w3schools.com/jquery/ajax_ajax.asp" rel="noreferrer"><code>$.ajax()</code></a> like this:</p> <pre><code>$.ajax({ type: "POST", url: "Concessions.aspx/GetConcessions", data: "{'countries':['ga','cd']}", ... </code></pre>
[ { "answer_id": 191911, "author": "Tahir Akhtar", "author_id": 18027, "author_profile": "https://Stackoverflow.com/users/18027", "pm_score": 6, "selected": false, "text": "<p>I haven't used it but you might want to try the <strong><a href=\"http://jollytoad.googlepages.com/json.js\" rel=\"noreferrer\">jQuery plugin written by Mark Gibson</a></strong> </p>\n\n<p>It adds the two functions: <code>$.toJSON(value)</code>, <code>$.parseJSON(json_str, [safe])</code>.</p>\n" }, { "answer_id": 191959, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 5, "selected": false, "text": "<p>No, the standard way to serialize to JSON is to use an existing JSON serialization library. If you don't wish to do this, then you're going to have to write your own serialization methods.</p>\n\n<p>If you want guidance on how to do this, I'd suggest examining the source of some of the available libraries.</p>\n\n<p><strong>EDIT:</strong> I'm not going to come out and say that writing your own serliazation methods is bad, but you must consider that if it's important to your application to use well-formed JSON, then you have to weigh the overhead of \"one more dependency\" against the possibility that your custom methods may one day encounter a failure case that you hadn't anticipated. Whether that risk is acceptable is your call.</p>\n" }, { "answer_id": 912247, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 11, "selected": true, "text": "<p><a href=\"https://github.com/douglascrockford/JSON-js\" rel=\"noreferrer\">JSON-js</a> - JSON in JavaScript.</p>\n\n<p>To convert an object to a string, use <code>JSON.stringify</code>:</p>\n\n<pre><code>var json_text = JSON.stringify(your_object, null, 2);\n</code></pre>\n\n<p>To convert a JSON string to object, use <code>JSON.parse</code>:</p>\n\n<pre><code>var your_object = JSON.parse(json_text);\n</code></pre>\n\n<p>It was recently recommended by <a href=\"http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/\" rel=\"noreferrer\">John Resig</a>:</p>\n\n<blockquote>\n <p>...PLEASE start migrating\n your JSON-using applications over to\n Crockford's json2.js. It is fully\n compatible with the ECMAScript 5\n specification and gracefully degrades\n if a native (faster!) implementation\n exists.</p>\n \n <p>In fact, I just landed a change in jQuery yesterday that utilizes the\n JSON.parse method if it exists, now\n that it has been completely specified.</p>\n</blockquote>\n\n<p>I tend to trust what he says on JavaScript matters :)</p>\n\n<p><a href=\"http://caniuse.com/json\" rel=\"noreferrer\">All modern browsers</a> (and many older ones which aren't ancient) support the <a href=\"http://ecma262-5.com/ELS5_Section_15.htm#Section_15.12\" rel=\"noreferrer\">JSON object</a> natively. The current version of Crockford's JSON library will only define <code>JSON.stringify</code> and <code>JSON.parse</code> if they're not already defined, leaving any browser native implementation intact.</p>\n" }, { "answer_id": 1829139, "author": "Kain Haart", "author_id": 222448, "author_profile": "https://Stackoverflow.com/users/222448", "pm_score": 4, "selected": false, "text": "<p>If you don't want to use external libraries there is <code>.toSource()</code> native JavaScript method, but it's not perfectly cross-browser.</p>\n" }, { "answer_id": 4577642, "author": "jamesmortensen", "author_id": 552792, "author_profile": "https://Stackoverflow.com/users/552792", "pm_score": 5, "selected": false, "text": "<p>I did find this somewhere. Can't remember where though... probably on StackOverflow :)</p>\n\n<pre><code>$.fn.serializeObject = function(){\n var o = {};\n var a = this.serializeArray();\n $.each(a, function() {\n if (o[this.name]) {\n if (!o[this.name].push) {\n o[this.name] = [o[this.name]];\n }\n o[this.name].push(this.value || '');\n } else {\n o[this.name] = this.value || '';\n }\n });\n return o;\n};\n</code></pre>\n" }, { "answer_id": 6208070, "author": "Jay Taylor", "author_id": 293064, "author_profile": "https://Stackoverflow.com/users/293064", "pm_score": 8, "selected": false, "text": "<p>I've been using <a href=\"https://code.google.com/p/jquery-json/\">jquery-json</a> for 6 months and it works great. It's very simple to use:</p>\n\n<pre><code>var myObj = {foo: \"bar\", \"baz\": \"wockaflockafliz\"};\n$.toJSON(myObj);\n\n// Result: {\"foo\":\"bar\",\"baz\":\"wockaflockafliz\"}\n</code></pre>\n" }, { "answer_id": 7227040, "author": "pestatije", "author_id": 917318, "author_profile": "https://Stackoverflow.com/users/917318", "pm_score": 7, "selected": false, "text": "<p><a href=\"http://caniuse.com/#search=JSON.stringify\" rel=\"noreferrer\"><strong>Works on IE8+</strong></a></p>\n\n<p>No need for jQuery, use:</p>\n\n<pre><code>JSON.stringify(countries); \n</code></pre>\n" }, { "answer_id": 24289943, "author": "Tim Burkhart", "author_id": 1442652, "author_profile": "https://Stackoverflow.com/users/1442652", "pm_score": 3, "selected": false, "text": "<p>One thing that the above solutions don't take into account is if you have an array of inputs but only one value was supplied.</p>\n\n<p>For instance, if the back end expects an array of People, but in this particular case, you are just dealing with a single person. Then doing:</p>\n\n<pre><code>&lt;input type=\"hidden\" name=\"People\" value=\"Joe\" /&gt;\n</code></pre>\n\n<p>Then with the previous solutions, it would just map to something like:</p>\n\n<pre><code>{\n \"People\" : \"Joe\"\n}\n</code></pre>\n\n<p>But it should really map to</p>\n\n<pre><code>{\n \"People\" : [ \"Joe\" ]\n}\n</code></pre>\n\n<p>To fix that, the input should look like:</p>\n\n<pre><code>&lt;input type=\"hidden\" name=\"People[]\" value=\"Joe\" /&gt;\n</code></pre>\n\n<p>And you would use the following function (based off of other solutions, but extended a bit)</p>\n\n<pre><code>$.fn.serializeObject = function() {\nvar o = {};\nvar a = this.serializeArray();\n$.each(a, function() {\n if (this.name.substr(-2) == \"[]\"){\n this.name = this.name.substr(0, this.name.length - 2);\n o[this.name] = [];\n }\n\n if (o[this.name]) {\n if (!o[this.name].push) {\n o[this.name] = [o[this.name]];\n }\n o[this.name].push(this.value || '');\n } else {\n o[this.name] = this.value || '';\n }\n});\nreturn o;\n};\n</code></pre>\n" }, { "answer_id": 29574586, "author": "jherax", "author_id": 2247494, "author_profile": "https://Stackoverflow.com/users/2247494", "pm_score": 3, "selected": false, "text": "<p>The best way is to include the polyfill for <a href=\"https://github.com/douglascrockford/JSON-js\" rel=\"noreferrer\">JSON</a> object.</p>\n\n<p>But if you insist create a method for serializing an object to JSON notation (<a href=\"http://json.org/\" rel=\"noreferrer\">valid values for JSON</a>) inside the jQuery namespace, you can do something like this:</p>\n\n<h2>Implementation</h2>\n\n\n\n<pre class=\"lang-js prettyprint-override\"><code>// This is a reference to JSON.stringify and provides a polyfill for old browsers.\n// stringify serializes an object, array or primitive value and return it as JSON.\njQuery.stringify = (function ($) {\n var _PRIMITIVE, _OPEN, _CLOSE;\n if (window.JSON &amp;&amp; typeof JSON.stringify === \"function\")\n return JSON.stringify;\n\n _PRIMITIVE = /string|number|boolean|null/;\n\n _OPEN = {\n object: \"{\",\n array: \"[\"\n };\n\n _CLOSE = {\n object: \"}\",\n array: \"]\"\n };\n\n //actions to execute in each iteration\n function action(key, value) {\n var type = $.type(value),\n prop = \"\";\n\n //key is not an array index\n if (typeof key !== \"number\") {\n prop = '\"' + key + '\":';\n }\n if (type === \"string\") {\n prop += '\"' + value + '\"';\n } else if (_PRIMITIVE.test(type)) {\n prop += value;\n } else if (type === \"array\" || type === \"object\") {\n prop += toJson(value, type);\n } else return;\n this.push(prop);\n }\n\n //iterates over an object or array\n function each(obj, callback, thisArg) {\n for (var key in obj) {\n if (obj instanceof Array) key = +key;\n callback.call(thisArg, key, obj[key]);\n }\n }\n\n //generates the json\n function toJson(obj, type) {\n var items = [];\n each(obj, action, items);\n return _OPEN[type] + items.join(\",\") + _CLOSE[type];\n }\n\n //exported function that generates the json\n return function stringify(obj) {\n if (!arguments.length) return \"\";\n var type = $.type(obj);\n if (_PRIMITIVE.test(type))\n return (obj === null ? type : obj.toString());\n //obj is array or object\n return toJson(obj, type);\n }\n}(jQuery));\n</code></pre>\n\n<h2>Usage</h2>\n\n<pre class=\"lang-js prettyprint-override\"><code>var myObject = {\n \"0\": null,\n \"total-items\": 10,\n \"undefined-prop\": void(0),\n sorted: true,\n images: [\"bg-menu.png\", \"bg-body.jpg\", [1, 2]],\n position: { //nested object literal\n \"x\": 40,\n \"y\": 300,\n offset: [{ top: 23 }]\n },\n onChange: function() { return !0 },\n pattern: /^bg-.+\\.(?:png|jpe?g)$/i\n};\n\nvar json = jQuery.stringify(myObject);\nconsole.log(json);\n</code></pre>\n" }, { "answer_id": 31116841, "author": "Shrish Shrivastava", "author_id": 2581488, "author_profile": "https://Stackoverflow.com/users/2581488", "pm_score": 3, "selected": false, "text": "<p>It's basically 2 step process:</p>\n\n<p>First, you need to stringify like this:</p>\n\n<pre><code>var JSON_VAR = JSON.stringify(OBJECT_NAME, null, 2); \n</code></pre>\n\n<p>After that, you need to convert the <code>string</code> to <code>Object</code>:</p>\n\n<pre><code>var obj = JSON.parse(JSON_VAR);\n</code></pre>\n" }, { "answer_id": 36192956, "author": "bruce", "author_id": 4903050, "author_profile": "https://Stackoverflow.com/users/4903050", "pm_score": 4, "selected": false, "text": "<p>Yes, you should <code>JSON.stringify</code> and <code>JSON.parse</code> your <code>Json_PostData</code> before calling <code>$.ajax</code>:</p>\n\n<pre><code>$.ajax({\n url: post_http_site, \n type: \"POST\", \n data: JSON.parse(JSON.stringify(Json_PostData)), \n cache: false,\n error: function (xhr, ajaxOptions, thrownError) {\n alert(\" write json item, Ajax error! \" + xhr.status + \" error =\" + thrownError + \" xhr.responseText = \" + xhr.responseText ); \n },\n success: function (data) {\n alert(\"write json item, Ajax OK\");\n\n } \n});\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
I need to [serialize](https://en.wikipedia.org/wiki/Serialization) an object to [JSON](https://www.json.org/). I'm using [jQuery](https://api.jquery.com/). Is there a "standard" way to do this? My specific situation: I have an array defined as shown below: ``` var countries = new Array(); countries[0] = 'ga'; countries[1] = 'cd'; ... ``` and I need to turn this into a string to pass to [`$.ajax()`](https://www.w3schools.com/jquery/ajax_ajax.asp) like this: ``` $.ajax({ type: "POST", url: "Concessions.aspx/GetConcessions", data: "{'countries':['ga','cd']}", ... ```
[JSON-js](https://github.com/douglascrockford/JSON-js) - JSON in JavaScript. To convert an object to a string, use `JSON.stringify`: ``` var json_text = JSON.stringify(your_object, null, 2); ``` To convert a JSON string to object, use `JSON.parse`: ``` var your_object = JSON.parse(json_text); ``` It was recently recommended by [John Resig](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/): > > ...PLEASE start migrating > your JSON-using applications over to > Crockford's json2.js. It is fully > compatible with the ECMAScript 5 > specification and gracefully degrades > if a native (faster!) implementation > exists. > > > In fact, I just landed a change in jQuery yesterday that utilizes the > JSON.parse method if it exists, now > that it has been completely specified. > > > I tend to trust what he says on JavaScript matters :) [All modern browsers](http://caniuse.com/json) (and many older ones which aren't ancient) support the [JSON object](http://ecma262-5.com/ELS5_Section_15.htm#Section_15.12) natively. The current version of Crockford's JSON library will only define `JSON.stringify` and `JSON.parse` if they're not already defined, leaving any browser native implementation intact.
191,883
<p>I want to be able to do the following:</p> <pre><code>$normal_array = array(); $array_of_arrayrefs = array( &amp;$normal_array ); // Here I want to access the $normal_array reference **as a reference**, // but that doesn't work obviously. How to do it? end( $array_of_arrayrefs )["one"] = 1; // choking on this one print $normal_array["one"]; // should output 1 </code></pre> <p>Regards</p> <p>/R</p>
[ { "answer_id": 191939, "author": "Joe Scylla", "author_id": 25771, "author_profile": "https://Stackoverflow.com/users/25771", "pm_score": -1, "selected": false, "text": "<p>The line:</p>\n\n<blockquote>\n <p>end( $array_of_arrayrefs )[\"one\"] = 1; // choking on this one</p>\n</blockquote>\n\n<p>throws a parse error: </p>\n\n<blockquote>\n <p>Parse error: syntax error, unexpected '[' in /file.php on line 65</p>\n</blockquote>\n\n<p>Make sure you have <code>error_reporting</code> and <code>display_error</code> activated.</p>\n\n<p>I'm not sure what you want to do but this works:</p>\n\n<pre><code>$normal_array = array();\n$array_of_arrayrefs = array( &amp;$normal_array );\n// Here I want to access the $normal_array reference **as a reference**,\n// but that doesn't work obviously. How to do it?\n$array_of_arrayrefs[0][\"one\"] = 1;\n//end($array_of_arrayrefs )[\"one\"] = 1; // choking on this one\nprint $normal_array[\"one\"]; // should output 1\n</code></pre>\n" }, { "answer_id": 191947, "author": "Andrew Moore", "author_id": 26210, "author_profile": "https://Stackoverflow.com/users/26210", "pm_score": 3, "selected": true, "text": "<p><code>end()</code> doesn't return a reference of the last value, but rather the last value itself. Here is a workaround:</p>\n\n<pre><code>$normal_array = array();\n$array_of_arrayrefs = array( &amp;$normal_array );\n\n$refArray = &amp;end_byref( $array_of_arrayrefs );\n$refArray[\"one\"] = 1;\n\nprint $normal_array[\"one\"]; // should output 1\n\nfunction &amp;end_byref( &amp;$array ) {\n $lastKey = end(array_keys($array));\n end($array);\n return $array[$lastKey];\n}\n</code></pre>\n" }, { "answer_id": 192004, "author": "rewbs", "author_id": 6095, "author_profile": "https://Stackoverflow.com/users/6095", "pm_score": 1, "selected": false, "text": "<p>Here are a couple of approaches, neither of which I find particularly satisfying.\nI'm sure there's a better way..</p>\n\n<pre><code>&lt;?php\n$normal_array = array();\n$array_of_arrayrefs = array( \"blah\", &amp;$normal_array );\n\nforeach ($array_of_arrayrefs as &amp;$v);\n$v[\"one\"] = 1;\n\necho $normal_array[\"one\"]; //prints 1\n?&gt;\n\n\n&lt;?php\n$normal_array = array();\n$array_of_arrayrefs = array( \"blah\", &amp;$normal_array );\n\n$lastIndex = @end(array_keys($array_of_arrayrefs)); //raises E_STRICT because end() expects referable.\n$array_of_arrayrefs[$lastIndex][\"one\"] = 1;\n\necho $normal_array[\"one\"]; //prints 1\n?&gt;\n</code></pre>\n" }, { "answer_id": 193983, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 1, "selected": false, "text": "<p>You probably shouldn't be passing by reference in the first place. It's generally considered bad practise to do so, because it makes it hard to see where state gets modified.</p>\n\n<p>It's a very common misconception that references are faster. This is not the case - In fact, they are a little bit slower, but it's by such a small amount, that it really doesn't matter. PHP has a system called copy-on-write, which means that variables aren't actually copied, before you write to them.</p>\n\n<p>The only place where you really need references, were in PHP4, where objects would get cloned otherwise. This is not needed in PHP5.</p>\n" }, { "answer_id": 430284, "author": "Preston", "author_id": 25213, "author_profile": "https://Stackoverflow.com/users/25213", "pm_score": 0, "selected": false, "text": "<p>The function end() doesn't just return a value. It also moves the array's internal pointer. Then we can use key() to get the index, after which we're able to use regular array access for the assignment.</p>\n\n<pre><code>$normal_array = array();\n$array_of_arrayrefs = array( &amp;$normal_array );\n\nend($array_of_arrayrefs);\n$array_of_arrayrefs[ key($array_of_arrayrefs) ][\"one\"] = 1;\n\nprint $normal_array[\"one\"];\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7891/" ]
I want to be able to do the following: ``` $normal_array = array(); $array_of_arrayrefs = array( &$normal_array ); // Here I want to access the $normal_array reference **as a reference**, // but that doesn't work obviously. How to do it? end( $array_of_arrayrefs )["one"] = 1; // choking on this one print $normal_array["one"]; // should output 1 ``` Regards /R
`end()` doesn't return a reference of the last value, but rather the last value itself. Here is a workaround: ``` $normal_array = array(); $array_of_arrayrefs = array( &$normal_array ); $refArray = &end_byref( $array_of_arrayrefs ); $refArray["one"] = 1; print $normal_array["one"]; // should output 1 function &end_byref( &$array ) { $lastKey = end(array_keys($array)); end($array); return $array[$lastKey]; } ```
191,894
<p>I have the following component </p> <pre><code>public class MyTimer : IMyTimer { public MyTimer(TimeSpan timespan){...} } </code></pre> <p>Where timespan should be provided by the property ISettings.MyTimerFrequency.</p> <p>How do I wire this up in windsor container xml? I thought I could do something like this:</p> <pre><code> &lt;component id="settings" service="MySample.ISettings, MySample" type="MySample.Settings, MySample" factoryId="settings_dao" factoryCreate="GetSettingsForInstance"&gt; &lt;parameters&gt;&lt;instance_id&gt;1&lt;/instance_id&gt;&lt;/parameters&gt; &lt;/component&gt; &lt;component id="my_timer_frequency" type="System.TimeSpan" factoryId="settings" factoryCreate="MyTimerFrequency" /&gt; &lt;component id="my_timer" service="MySample.IMyTimer, MySample" type="MySample.MyTimer, MySample"&gt; &lt;parameters&gt;&lt;timespan&gt;${my_timer_frequency}&lt;/timespan&gt;&lt;/parameters&gt; </code></pre> <p>but I am getting an error because MyTimerFrequency is a property when the factory facility expects a method.</p> <p>Is there a simple resolution here? Am I approaching the whole thing the wrong way?</p> <p><strong>EDIT:</strong> There is definitely a solution, see my answer below.</p>
[ { "answer_id": 193193, "author": "RKitson", "author_id": 16947, "author_profile": "https://Stackoverflow.com/users/16947", "pm_score": 0, "selected": false, "text": "<p>Wouldn't the simplest solution be to add a method which wraps the property?</p>\n" }, { "answer_id": 197501, "author": "George Mauer", "author_id": 5056, "author_profile": "https://Stackoverflow.com/users/5056", "pm_score": 3, "selected": true, "text": "<p>The solution actually came to me in a dream. Keep in mind that properties are not a CLR construct but rather C# syntactic sugar. If you don't believe me just try compiling</p>\n\n<pre><code>public class MyClass {\n public object Item {\n get;\n }\n public object get_Item() {return null;}\n}\n</code></pre>\n\n<p>results in a Error: <strong>Type 'TestApp.MyClass' already reserves a member called 'get_Item' with the same parameter types</strong></p>\n\n<p>Since the Xml configuration is pursed at runtime after compilation, we can simply bind to a factoryCreate property by binding to the method that it compiles to so the above example becomes: </p>\n\n<pre><code>&lt;component id=\"my_timer_frequency\"\n type=\"System.TimeSpan\"\n factoryId=\"settings\" factoryCreate=\"get_MyTimerFrequency\" /&gt;\n</code></pre>\n\n<p>And voila! </p>\n\n<p>Someone vote this up since I can't mark it as an answer.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I have the following component ``` public class MyTimer : IMyTimer { public MyTimer(TimeSpan timespan){...} } ``` Where timespan should be provided by the property ISettings.MyTimerFrequency. How do I wire this up in windsor container xml? I thought I could do something like this: ``` <component id="settings" service="MySample.ISettings, MySample" type="MySample.Settings, MySample" factoryId="settings_dao" factoryCreate="GetSettingsForInstance"> <parameters><instance_id>1</instance_id></parameters> </component> <component id="my_timer_frequency" type="System.TimeSpan" factoryId="settings" factoryCreate="MyTimerFrequency" /> <component id="my_timer" service="MySample.IMyTimer, MySample" type="MySample.MyTimer, MySample"> <parameters><timespan>${my_timer_frequency}</timespan></parameters> ``` but I am getting an error because MyTimerFrequency is a property when the factory facility expects a method. Is there a simple resolution here? Am I approaching the whole thing the wrong way? **EDIT:** There is definitely a solution, see my answer below.
The solution actually came to me in a dream. Keep in mind that properties are not a CLR construct but rather C# syntactic sugar. If you don't believe me just try compiling ``` public class MyClass { public object Item { get; } public object get_Item() {return null;} } ``` results in a Error: **Type 'TestApp.MyClass' already reserves a member called 'get\_Item' with the same parameter types** Since the Xml configuration is pursed at runtime after compilation, we can simply bind to a factoryCreate property by binding to the method that it compiles to so the above example becomes: ``` <component id="my_timer_frequency" type="System.TimeSpan" factoryId="settings" factoryCreate="get_MyTimerFrequency" /> ``` And voila! Someone vote this up since I can't mark it as an answer.
191,897
<p>I have around 3500 flood control facilities that I would like to represent as a network to determine flow paths (essentially a directed graph). I'm currently using SqlServer and a CTE to recursively examine all the nodes and their upstream components and this works as long as the upstream path doesn't fork alot. However, some queries take exponentially longer than others even when they are not much farther physically down the path (i.e. two or three segments "downstream") because of the added upstream complexity; in some cases I've let it go over ten minutes before killing the query. I'm using a simple two-column table, one column being the facility itself and the other being the facility that is upstream from the one listed in the first column.</p> <p>I tried adding an index using the current facility to help speed things up but that made no difference. And, as for the possible connections in the graph, any nodes could have multiple upstream connections and could be connected to from multiple "downstream" nodes.</p> <p>It is certainly possible that there are cycles in the data but I have not yet figured out a good way to verify this (other than when the CTE query reported a maximum recursive count hit; those were easy to fix).</p> <p>So, my question is, am I storing this information wrong? Is there a better way other than a CTE to query the upstream points? </p>
[ { "answer_id": 191948, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 2, "selected": false, "text": "<p>Traditionally graphs are either represented by a matrix or a vector. The matrix takes more space, but is easier to process(3500x3500 entries in your case); the vector takes less space(3500 entries, each have a list of who they connect to).</p>\n\n<p>Does that help you?</p>\n" }, { "answer_id": 191977, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 2, "selected": false, "text": "<p>i think your data structure is fine (for SQL Server) but a CTE may not be the most efficient solution for your queries. You might try making a stored procedure that traverses the graph using a temp table as a queue instead, this should be more efficient.</p>\n\n<p>the temp table can also be used to eliminate cycles in the graph, though there shouldn't be any</p>\n" }, { "answer_id": 191986, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 1, "selected": false, "text": "<p>Yes (maybe). Your data set sounds relatively small, you could load the graph to memory as an adjacency matrix or adjacency list and query the graph directly - assuming you program. </p>\n\n<p>As far as on-disk format, <a href=\"http://en.wikipedia.org/wiki/DOT_language\" rel=\"nofollow noreferrer\">DOT</a> is fairly portable/popular among others. It also seems pretty common to store a list of edges in a flat file format like:</p>\n\n<pre><code>vertex1 vertex2 {edge_label1}+\n</code></pre>\n\n<p>Where the first line of the file contains the number of vertices in the graph, and every line after that describes edges. Whether the edges are directed or undirected is up to the implementor. If you want explicit directed edges, then describe them using directed edges like:</p>\n\n<pre><code>vertex1 vertex2\nvertex2 vertex1\n</code></pre>\n" }, { "answer_id": 192020, "author": "Cervo", "author_id": 16219, "author_profile": "https://Stackoverflow.com/users/16219", "pm_score": 3, "selected": true, "text": "<p>I know nothing about flood control facilities. But I would take the first facility. And use a temp table and a while loop to generate the path.</p>\n\n<p><PRE>\n-- Pseudo Code\nTempTable (LastNode, CurrentNode, N)</p>\n\n<p>DECLARE @intN INT\nSET @intN = 1</p>\n\n<p>INSERT INTO TempTable(LastNode, CurrentNode, N)\n -- Insert first item in list with no up stream items...call this initial condition\n SELECT LastNode, CurrentNode, @intN\n FROM your table\n WHERE node has nothing upstream</p>\n\n<p>WHILE @intN &lt;= 3500\nBEGIN\n SEt @intN = @intN + 1\n INSERT INTO TempTable(LastNode, CurrentNode, N)\n SELECT LastNode, CurrentNode, @intN\n FROM your table\n WHERE LastNode IN (SELECT CurrentNode FROM TempTable WHERE N = @intN-1)</p>\n\n<pre><code>IF @@ROWCOUNT = 0\n BREAK\n</code></pre>\n\n<p>END\n</PRE></p>\n\n<p>If we assume that every node points to one child. Then this should take no longer than 3500 iterations. If multiple nodes have the same upstream provider then it will take less. But more importantly, this lets you do this...</p>\n\n<p>SELECT LastNode, CurrentNode, N\nFROM TempTable\nORDER BY N</p>\n\n<p>And that will let you see if there are any loops or any other issues with your provider. Incidentally 3500 rows is not that much so even in the worst case of each provider pointing to a different upstream provider, this should not take that long.</p>\n" }, { "answer_id": 347443, "author": "nawroth", "author_id": 36710, "author_profile": "https://Stackoverflow.com/users/36710", "pm_score": 3, "selected": false, "text": "<p>The best way to store graphs is of course to use a native graph db :-)</p>\n\n<p>Take a look at <a href=\"http://neo4j.org/\" rel=\"noreferrer\">neo4j</a>.\nIt's implemented in Java and has Python and Ruby bindings as well.</p>\n\n<p>I wrote up two wiki pages with simple examples of domain models represented as graphs using neo4j: <a href=\"http://wiki.neo4j.org/content/Assembly\" rel=\"noreferrer\">assembly</a> and <a href=\"http://wiki.neo4j.org/content/Roles\" rel=\"noreferrer\">roles</a>. More examples are found on the <a href=\"http://wiki.neo4j.org/content/Domain_Modeling_Gallery\" rel=\"noreferrer\">domain modeling gallery</a> page.</p>\n" }, { "answer_id": 347471, "author": "Tomas Pajonk", "author_id": 4694, "author_profile": "https://Stackoverflow.com/users/4694", "pm_score": 0, "selected": false, "text": "<p>My experiences with storing something like you described in a SQL Server database:</p>\n\n<p>I was storing a distance matrix, telling how long does it take to travel from point A to point B. I have done the naive representation and stored them directly into a table called distances with columns A,B,distance,time. </p>\n\n<p>This is very slow on simple retreival. I found it is lot better to store my whole matrix as text. Then retreive it into memory before the computations, create an matrix struxture in memory and work with it there.</p>\n\n<p>I could provide with some code, but it would be C#.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16623/" ]
I have around 3500 flood control facilities that I would like to represent as a network to determine flow paths (essentially a directed graph). I'm currently using SqlServer and a CTE to recursively examine all the nodes and their upstream components and this works as long as the upstream path doesn't fork alot. However, some queries take exponentially longer than others even when they are not much farther physically down the path (i.e. two or three segments "downstream") because of the added upstream complexity; in some cases I've let it go over ten minutes before killing the query. I'm using a simple two-column table, one column being the facility itself and the other being the facility that is upstream from the one listed in the first column. I tried adding an index using the current facility to help speed things up but that made no difference. And, as for the possible connections in the graph, any nodes could have multiple upstream connections and could be connected to from multiple "downstream" nodes. It is certainly possible that there are cycles in the data but I have not yet figured out a good way to verify this (other than when the CTE query reported a maximum recursive count hit; those were easy to fix). So, my question is, am I storing this information wrong? Is there a better way other than a CTE to query the upstream points?
I know nothing about flood control facilities. But I would take the first facility. And use a temp table and a while loop to generate the path. ``` -- Pseudo Code TempTable (LastNode, CurrentNode, N) ``` DECLARE @intN INT SET @intN = 1 INSERT INTO TempTable(LastNode, CurrentNode, N) -- Insert first item in list with no up stream items...call this initial condition SELECT LastNode, CurrentNode, @intN FROM your table WHERE node has nothing upstream WHILE @intN <= 3500 BEGIN SEt @intN = @intN + 1 INSERT INTO TempTable(LastNode, CurrentNode, N) SELECT LastNode, CurrentNode, @intN FROM your table WHERE LastNode IN (SELECT CurrentNode FROM TempTable WHERE N = @intN-1) ``` IF @@ROWCOUNT = 0 BREAK ``` END If we assume that every node points to one child. Then this should take no longer than 3500 iterations. If multiple nodes have the same upstream provider then it will take less. But more importantly, this lets you do this... SELECT LastNode, CurrentNode, N FROM TempTable ORDER BY N And that will let you see if there are any loops or any other issues with your provider. Incidentally 3500 rows is not that much so even in the worst case of each provider pointing to a different upstream provider, this should not take that long.
191,923
<p>I have an XML file loaded into a DOM document, I wish to iterate through all 'foo' tags, getting values from every tag below it. I know I can get values via </p> <pre><code>$element = $dom-&gt;getElementsByTagName('foo')-&gt;item(0); foreach($element-&gt;childNodes as $node){ $data[$node-&gt;nodeName] = $node-&gt;nodeValue; } </code></pre> <p>However, what I'm trying to do, is from an XML like, </p> <pre><code>&lt;stuff&gt; &lt;foo&gt; &lt;bar&gt;&lt;/bar&gt; &lt;value/&gt; &lt;pub&gt;&lt;/pub&gt; &lt;/foo&gt; &lt;foo&gt; &lt;bar&gt;&lt;/bar&gt; &lt;pub&gt;&lt;/pub&gt; &lt;/foo&gt; &lt;foo&gt; &lt;bar&gt;&lt;/bar&gt; &lt;pub&gt;&lt;/pub&gt; &lt;/foo&gt; &lt;/stuff&gt; </code></pre> <p>iterate over every <em>foo</em> tag, and get specific <em>bar</em> or <em>pub</em>, and get values from there. Now, how do I iterate over <em>foo</em> so that I can still access specific child nodes by name?</p>
[ { "answer_id": 192015, "author": "roryf", "author_id": 270, "author_profile": "https://Stackoverflow.com/users/270", "pm_score": 7, "selected": true, "text": "<p>Not tested, but what about:</p>\n\n<pre><code>$elements = $dom-&gt;getElementsByTagName('foo');\n$data = array();\nforeach($elements as $node){\n foreach($node-&gt;childNodes as $child) {\n $data[] = array($child-&gt;nodeName =&gt; $child-&gt;nodeValue);\n }\n}\n</code></pre>\n" }, { "answer_id": 192909, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 2, "selected": false, "text": "<p>It's generally much better to use XPath to query a document than it is to write code that depends on knowledge of the document's structure. There are two reasons. First, there's a lot less code to test and debug. Second, if the document's structure changes it's a lot easier to change an XPath query than it is to change a bunch of code.</p>\n\n<p>Of course, you have to learn XPath, but (most of) XPath isn't rocket science.</p>\n\n<p>PHP's DOM uses the <code>xpath_eval</code> method to perform XPath queries. It's documented <a href=\"http://us3.php.net/manual/en/function.xpath-eval.php\" rel=\"nofollow noreferrer\">here</a>, and the user notes include some pretty good examples.</p>\n" }, { "answer_id": 353364, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Here's another (lazy) way to do it.</p>\n\n<pre><code>$data[][$node-&gt;nodeName] = $node-&gt;nodeValue;\n</code></pre>\n" }, { "answer_id": 34971104, "author": "Daniele Orlando", "author_id": 1750243, "author_profile": "https://Stackoverflow.com/users/1750243", "pm_score": -1, "selected": false, "text": "<p>With <a href=\"https://github.com/servo-php/fluidxml\" rel=\"nofollow\"><strong>FluidXML</strong></a> you can query and iterate XML very easly.</p>\n\n<pre><code>$data = [];\n\n$store_child = function($i, $fooChild) use (&amp;$data) {\n $data[] = [ $fooChild-&gt;nodeName =&gt; $fooChild-&gt;nodeValue ];\n};\n\nfluidxml($dom)-&gt;query('//foo/*')-&gt;each($store_child);\n</code></pre>\n\n<p><a href=\"https://github.com/servo-php/fluidxml\" rel=\"nofollow\">https://github.com/servo-php/fluidxml</a></p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4224/" ]
I have an XML file loaded into a DOM document, I wish to iterate through all 'foo' tags, getting values from every tag below it. I know I can get values via ``` $element = $dom->getElementsByTagName('foo')->item(0); foreach($element->childNodes as $node){ $data[$node->nodeName] = $node->nodeValue; } ``` However, what I'm trying to do, is from an XML like, ``` <stuff> <foo> <bar></bar> <value/> <pub></pub> </foo> <foo> <bar></bar> <pub></pub> </foo> <foo> <bar></bar> <pub></pub> </foo> </stuff> ``` iterate over every *foo* tag, and get specific *bar* or *pub*, and get values from there. Now, how do I iterate over *foo* so that I can still access specific child nodes by name?
Not tested, but what about: ``` $elements = $dom->getElementsByTagName('foo'); $data = array(); foreach($elements as $node){ foreach($node->childNodes as $child) { $data[] = array($child->nodeName => $child->nodeValue); } } ```
191,929
<p>If I were to use more than one, what order should I use modifier keywords such as:</p> <p><code>public</code>, <code>private</code>, <code>protected</code>, <code>virtual</code>, <code>abstract</code>, <code>override</code>, <code>new</code>, <code>static</code>, <code>internal</code>, <code>sealed</code>, and any others I'm forgetting.</p>
[ { "answer_id": 191942, "author": "Chris Charabaruk", "author_id": 5697, "author_profile": "https://Stackoverflow.com/users/5697", "pm_score": 2, "selected": false, "text": "<p>I usually start off with the access modifier first, then virtual/abstract/sealed, then override/new/etc. although others might do it differently. Almost invariably, the access modifier will be first, however.</p>\n" }, { "answer_id": 191944, "author": "Mark Heath", "author_id": 7532, "author_profile": "https://Stackoverflow.com/users/7532", "pm_score": 4, "selected": false, "text": "<p><a href=\"https://stylecop.codeplex.com\" rel=\"nofollow noreferrer\">StyleCop</a> is available as a <a href=\"https://marketplace.visualstudio.com/items?itemName=ChrisDahlberg.StyleCop\" rel=\"nofollow noreferrer\">Visual Studio extension</a> or a <a href=\"https://www.nuget.org/packages/StyleCop.MSBuild\" rel=\"nofollow noreferrer\">NuGet package</a> and can validate your source code against the rules some teams in Microsoft use. StyleCop likes the access modifier to come first.</p>\n\n<p>EDIT: Microsoft isn't itself totally consistent; different teams use different styles. For example StyleCop suggests putting using directives in the namespace, but this is not followed in the Roslyn source code.</p>\n" }, { "answer_id": 18270569, "author": "Jeppe Stig Nielsen", "author_id": 1336654, "author_profile": "https://Stackoverflow.com/users/1336654", "pm_score": 1, "selected": false, "text": "<p>In some cases there are very many possibilities. For example with the below class <code>C</code> with base class <code>B</code>,</p>\n\n<pre><code>public class B\n{\n public void X()\n {\n }\n}\npublic class C : B\n{\n protected internal new static readonly DateTime X;\n}\n</code></pre>\n\n<p>the field of type <code>DateTime</code> in <code>C</code> has no fewer than five distinct modifiers, so there are <code>5! == 5*4*3*2*1 == 120</code> different ways to write the same field! It would be <em>very</em> confusing not to have <code>protected</code> and <code>internal</code> next to each other, but it is still legal.</p>\n\n<p>Not sure if everyone agrees on a convention for the order. For example I have seen some people put the <code>new</code> modifier <em>before</em> the access level (protection level) modifier, although many people like to always have the protection level modifier first.</p>\n" }, { "answer_id": 33237262, "author": "Wai Ha Lee", "author_id": 1364007, "author_profile": "https://Stackoverflow.com/users/1364007", "pm_score": 6, "selected": true, "text": "<p>I had a look at Microsoft's <a href=\"https://msdn.microsoft.com/en-us/library/ms229042%28v=vs.100%29\" rel=\"noreferrer\">Framework Design Guidelines</a> and couldn't find any references to what order modifiers should be put on members. Likewise, a look at the <a href=\"https://www.microsoft.com/en-gb/download/details.aspx?id=7029\" rel=\"noreferrer\">C# 5.0 language specification</a> proved fruitless. There were two other avenues to follow, though: <a href=\"https://learn.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2017\" rel=\"noreferrer\">EditorConfig files</a> and <a href=\"https://www.jetbrains.com/resharper\" rel=\"noreferrer\">ReSharper</a>.</p>\n\n<hr>\n\n<h1>.editorconfig</h1>\n\n<p>The MSDN page, <a href=\"https://learn.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference?view=vs-2017\" rel=\"noreferrer\">.NET coding convention settings for EditorConfig</a> says:</p>\n\n<blockquote>\n <p>In Visual Studio 2017, you can define and maintain consistent code style in your codebase with the use of an <a href=\"https://learn.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2017\" rel=\"noreferrer\">EditorConfig</a> file.</p>\n \n <h1>Example EditorConfig file</h1>\n \n <p>To help you get started, here is an example .editorconfig file with the default options:</p>\n\n<pre><code>###############################\n# C# Code Style Rules #\n###############################\n\n# Modifier preferences\ncsharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion\n</code></pre>\n</blockquote>\n\n<p>In other words: the default order for modifiers, following the default editorconfig settings is:</p>\n\n<pre><code>{ public / private / protected / internal / protected internal / private protected } // access modifiers\nstatic\nextern\nnew\n{ virtual / abstract / override / sealed override } // inheritance modifiers\nreadonly\nunsafe\nvolatile\nasync\n</code></pre>\n\n<hr>\n\n<h2>ReSharper</h2>\n\n<p><a href=\"https://www.jetbrains.com/resharper/\" rel=\"noreferrer\">ReSharper</a>, however, is more forthcoming. The defaults for ReSharper 2018.1<sup>1</sup>, with access modifiers (which are exclusive) and inheritance modifiers (which are exclusive), grouped together is:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>{ public / protected / internal / private / protected internal / private protected } // access modifiers\nnew\n{ abstract / virtual / override / sealed override } // inheritance modifiers\nstatic\nreadonly\nextern\nunsafe\nvolatile\nasync\n</code></pre>\n\n<p>This is stored in the <code>{solution}.dotsettings</code> file under the</p>\n\n<pre><code>\"/Default/CodeStyle/CodeFormatting/CSharpFormat/MODIFIERS_ORDER/@EntryValue\"\n</code></pre>\n\n<p>node - the ReSharper default<sup>2</sup> is:</p>\n\n<pre><code>&lt;s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/MODIFIERS_ORDER/@EntryValue\"&gt;\n public protected internal private new abstract virtual sealed override static readonly extern unsafe volatile async\n&lt;/s:String&gt;\n</code></pre>\n\n<p><sup>1</sup> <a href=\"https://www.jetbrains.com/resharper/whatsnew/#v2018-1\" rel=\"noreferrer\">ReSharper 2018.1</a> says that it has \"<em>Full understanding of C# 7.2</em>\" and explicitly mentions the <code>private protected</code> access modifier.</p>\n\n<p><sup>2</sup> ReSharper only saves settings which differ from the default, so in general this node, as it is, will not be seen in the <code>dotsettings</code> file.</p>\n\n<hr>\n\n<h2><code>new static</code> vs <code>static new</code></h2>\n\n<p>The MSDN page for <a href=\"https://msdn.microsoft.com/en-us/library/3s8070fc.aspx\" rel=\"noreferrer\">Compiler Warning CS0108</a> gives the example of a public field <code>i</code> on a base class being hidden by a public static field <code>i</code> on a derived class: their suggestion is to change <code>static</code> to <code>static new</code>:</p>\n\n<blockquote>\n<pre><code>public class clx\n{\n public int i = 1;\n}\n\npublic class cly : clx\n{\n public static int i = 2; // CS0108, use the new keyword\n // Use the following line instead:\n // public static new int i = 2;\n}\n</code></pre>\n</blockquote>\n\n<p>Likewise, the IntelliSense in Visual Studio 2015 also suggests changing <code>static</code> to <code>static new</code></p>\n\n<p><a href=\"https://i.stack.imgur.com/7vWEY.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/7vWEY.png\" alt=\"CS0108 Visual Studio recommended change\"></a></p>\n\n<p>which is the same if the field <code>i</code> in the base class is also <code>static</code>.</p>\n\n<p>That said, a cursory search on GitHub found that some projects override this default to put <code>static</code> <em>before</em>, not <em>after</em> <code>new</code>, the inheritance modifiers and <code>sealed</code>, e.g.\n<a href=\"https://github.com/StyleCop/StyleCop/blob/master/Project/Src/AddIns/ReSharper/StyleCop.dotSettings#L75\" rel=\"noreferrer\">the ReSharper settings for StyleCop GitHub project</a>:</p>\n\n<pre><code>&lt;s:String x:Key=\"/Default/CodeStyle/CodeFormatting/CSharpFormat/MODIFIERS_ORDER/@EntryValue\"&gt;\n public protected internal private static new abstract virtual override sealed readonly extern unsafe volatile async\n&lt;/s:String&gt;\n</code></pre>\n\n<p>however since <code>static</code> cannot be used in conjunction with the inheritance modifiers or <code>sealed</code>, this is just a distinction between <code>new static</code> (the default, and suggested by the default editorconfig file) and <code>static new</code> (suggested by ReSharper).</p>\n\n<p>Personally I prefer the latter, but Google searches in <a href=\"http://referencesource.microsoft.com/\" rel=\"noreferrer\">referencesource.microsoft.com</a> for <a href=\"https://www.google.co.uk/?gws_rd=ssl#q=inurl:referencesource.microsoft.com%2F+%22new+static%22\" rel=\"noreferrer\"><code>new static</code></a> vs <a href=\"https://www.google.co.uk/?gws_rd=ssl#q=inurl:referencesource.microsoft.com%2F+%22static+new%22\" rel=\"noreferrer\"><code>static new</code></a> in 2015 and 2018 gave:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> (in 2015) (in 2018)\nnew static 203 427\nstatic new 10 990\n</code></pre>\n\n<p>which implies that the preference at Microsoft is <code>static new</code>.</p>\n" }, { "answer_id": 74365260, "author": "David R. Williamson", "author_id": 2019302, "author_profile": "https://Stackoverflow.com/users/2019302", "pm_score": 0, "selected": false, "text": "<p>In my experience, there's no functional difference in how they are ordered, but just like with grammar, it sounds weird if it is out of order.</p>\n<p>I've heard before there is a preferred order but couldn't find a C# guide that indicated it either, but there is this Language Rules code style to refer to: <a href=\"https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0036\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0036</a>.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16260/" ]
If I were to use more than one, what order should I use modifier keywords such as: `public`, `private`, `protected`, `virtual`, `abstract`, `override`, `new`, `static`, `internal`, `sealed`, and any others I'm forgetting.
I had a look at Microsoft's [Framework Design Guidelines](https://msdn.microsoft.com/en-us/library/ms229042%28v=vs.100%29) and couldn't find any references to what order modifiers should be put on members. Likewise, a look at the [C# 5.0 language specification](https://www.microsoft.com/en-gb/download/details.aspx?id=7029) proved fruitless. There were two other avenues to follow, though: [EditorConfig files](https://learn.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2017) and [ReSharper](https://www.jetbrains.com/resharper). --- .editorconfig ============= The MSDN page, [.NET coding convention settings for EditorConfig](https://learn.microsoft.com/en-us/visualstudio/ide/editorconfig-code-style-settings-reference?view=vs-2017) says: > > In Visual Studio 2017, you can define and maintain consistent code style in your codebase with the use of an [EditorConfig](https://learn.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2017) file. > > > Example EditorConfig file > ========================= > > > To help you get started, here is an example .editorconfig file with the default options: > > > > ``` > ############################### > # C# Code Style Rules # > ############################### > > # Modifier preferences > csharp_preferred_modifier_order = public,private,protected,internal,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,volatile,async:suggestion > > ``` > > In other words: the default order for modifiers, following the default editorconfig settings is: ``` { public / private / protected / internal / protected internal / private protected } // access modifiers static extern new { virtual / abstract / override / sealed override } // inheritance modifiers readonly unsafe volatile async ``` --- ReSharper --------- [ReSharper](https://www.jetbrains.com/resharper/), however, is more forthcoming. The defaults for ReSharper 2018.11, with access modifiers (which are exclusive) and inheritance modifiers (which are exclusive), grouped together is: ```cs { public / protected / internal / private / protected internal / private protected } // access modifiers new { abstract / virtual / override / sealed override } // inheritance modifiers static readonly extern unsafe volatile async ``` This is stored in the `{solution}.dotsettings` file under the ``` "/Default/CodeStyle/CodeFormatting/CSharpFormat/MODIFIERS_ORDER/@EntryValue" ``` node - the ReSharper default2 is: ``` <s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/MODIFIERS_ORDER/@EntryValue"> public protected internal private new abstract virtual sealed override static readonly extern unsafe volatile async </s:String> ``` 1 [ReSharper 2018.1](https://www.jetbrains.com/resharper/whatsnew/#v2018-1) says that it has "*Full understanding of C# 7.2*" and explicitly mentions the `private protected` access modifier. 2 ReSharper only saves settings which differ from the default, so in general this node, as it is, will not be seen in the `dotsettings` file. --- `new static` vs `static new` ---------------------------- The MSDN page for [Compiler Warning CS0108](https://msdn.microsoft.com/en-us/library/3s8070fc.aspx) gives the example of a public field `i` on a base class being hidden by a public static field `i` on a derived class: their suggestion is to change `static` to `static new`: > > > ``` > public class clx > { > public int i = 1; > } > > public class cly : clx > { > public static int i = 2; // CS0108, use the new keyword > // Use the following line instead: > // public static new int i = 2; > } > > ``` > > Likewise, the IntelliSense in Visual Studio 2015 also suggests changing `static` to `static new` [![CS0108 Visual Studio recommended change](https://i.stack.imgur.com/7vWEY.png)](https://i.stack.imgur.com/7vWEY.png) which is the same if the field `i` in the base class is also `static`. That said, a cursory search on GitHub found that some projects override this default to put `static` *before*, not *after* `new`, the inheritance modifiers and `sealed`, e.g. [the ReSharper settings for StyleCop GitHub project](https://github.com/StyleCop/StyleCop/blob/master/Project/Src/AddIns/ReSharper/StyleCop.dotSettings#L75): ``` <s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/MODIFIERS_ORDER/@EntryValue"> public protected internal private static new abstract virtual override sealed readonly extern unsafe volatile async </s:String> ``` however since `static` cannot be used in conjunction with the inheritance modifiers or `sealed`, this is just a distinction between `new static` (the default, and suggested by the default editorconfig file) and `static new` (suggested by ReSharper). Personally I prefer the latter, but Google searches in [referencesource.microsoft.com](http://referencesource.microsoft.com/) for [`new static`](https://www.google.co.uk/?gws_rd=ssl#q=inurl:referencesource.microsoft.com%2F+%22new+static%22) vs [`static new`](https://www.google.co.uk/?gws_rd=ssl#q=inurl:referencesource.microsoft.com%2F+%22static+new%22) in 2015 and 2018 gave: ```none (in 2015) (in 2018) new static 203 427 static new 10 990 ``` which implies that the preference at Microsoft is `static new`.
191,940
<p>Is it possible to define a class in C# such that</p> <pre><code>class GenericCollection&lt;T&gt; : SomeBaseCollection&lt;T&gt; where T : Delegate </code></pre> <p>I couldn't for the life of me accomplish this last night in .NET 3.5. I tried using</p> <p><code>delegate, Delegate, Action&lt;T&gt; and Func&lt;T, T&gt;</code></p> <p>It seems to me that this should be allowable in some way. I'm trying to implement my own EventQueue.</p> <p>I ended up just doing this [primitive approximation mind you].</p> <pre><code>internal delegate void DWork(); class EventQueue { private Queue&lt;DWork&gt; eventq; } </code></pre> <p>But then I lose the ability to reuse the same definition for different types of functions.</p> <p>Thoughts?</p>
[ { "answer_id": 191949, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 7, "selected": true, "text": "<p>A number of classes are unavailable as generic contraints - Enum being another.</p>\n\n<p>For delegates, the closest you can get is \": class\", perhaps using reflection to check (for example, in the static constructor) that the T <em>is</em> a delegate:</p>\n\n<pre><code>static GenericCollection()\n{\n if (!typeof(T).IsSubclassOf(typeof(Delegate)))\n {\n throw new InvalidOperationException(typeof(T).Name + \" is not a delegate type\");\n }\n}\n</code></pre>\n" }, { "answer_id": 191994, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 4, "selected": false, "text": "<p><strong>Edit:</strong> Some proposed work-arounds are proposed in these articles:</p>\n\n<p><a href=\"http://jacobcarpenters.blogspot.com/2006/06/c-30-and-delegate-conversion.html\" rel=\"noreferrer\">http://jacobcarpenters.blogspot.com/2006/06/c-30-and-delegate-conversion.html</a></p>\n\n<p><a href=\"http://jacobcarpenters.blogspot.com/2006_11_01_archive.html\" rel=\"noreferrer\">http://jacobcarpenters.blogspot.com/2006_11_01_archive.html</a></p>\n\n<hr>\n\n<p>From the <a href=\"http://download.microsoft.com/download/9/8/f/98fdf0c7-2bbd-40d3-9fd1-5a4159fa8044/CSharp%202.0%20Specification_Sept_2005.doc\" rel=\"noreferrer\">C# 2.0 specification</a> we can read (20.7, Constraints):</p>\n\n<p>A class-type constraint must satisfy the following rules:</p>\n\n<ul>\n<li>The type must be a class type.</li>\n<li>The type must not be sealed.</li>\n<li><strong>The type must not be one of the following types: System.Array, System.Delegate, System.Enum, or System.ValueType</strong>.</li>\n<li>The type must not be object. Because all types derive from object, such a constraint would have no effect if it were permitted.</li>\n<li>At most one constraint for a given type parameter can be a class type.</li>\n</ul>\n\n<p>And sure enough VS2008 spits out an error:</p>\n\n<pre><code>error CS0702: Constraint cannot be special class 'System.Delegate'\n</code></pre>\n\n<p>For info and investigation on this issue read <a href=\"http://www.pluralsight.com/community/blogs/mike/archive/2005/12/06/17307.aspx\" rel=\"noreferrer\">here</a>.</p>\n" }, { "answer_id": 192531, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "<p>Delegate already supports chaining. Doesn't this meet your needs?</p>\n\n<pre><code>public class EventQueueTests\n{\n public void Test1()\n {\n Action myAction = () =&gt; Console.WriteLine(\"foo\");\n myAction += () =&gt; Console.WriteLine(\"bar\");\n\n myAction();\n //foo\n //bar\n }\n\n public void Test2()\n {\n Action&lt;int&gt; myAction = x =&gt; Console.WriteLine(\"foo {0}\", x);\n myAction += x =&gt; Console.WriteLine(\"bar {0}\", x);\n myAction(3);\n //foo 3\n //bar 3\n }\n\n public void Test3()\n {\n Func&lt;int, int&gt; myFunc = x =&gt; { Console.WriteLine(\"foo {0}\", x); return x + 2; };\n myFunc += x =&gt; { Console.WriteLine(\"bar {0}\", x); return x + 1; };\n int y = myFunc(3);\n Console.WriteLine(y);\n\n //foo 3\n //bar 3\n //4\n }\n\n public void Test4()\n {\n Func&lt;int, int&gt; myFunc = x =&gt; { Console.WriteLine(\"foo {0}\", x); return x + 2; };\n Func&lt;int, int&gt; myNextFunc = x =&gt; { x = myFunc(x); Console.WriteLine(\"bar {0}\", x); return x + 1; };\n int y = myNextFunc(3);\n Console.WriteLine(y);\n\n //foo 3\n //bar 5\n //6\n }\n\n}\n</code></pre>\n" }, { "answer_id": 2088271, "author": "Justin Bailey", "author_id": 169359, "author_profile": "https://Stackoverflow.com/users/169359", "pm_score": 2, "selected": false, "text": "<p>I came across a situation where I needed to deal with a <code>Delegate</code> internally but I wanted a generic constraint. Specifically, I wanted to add an event handler using reflection, but I wanted to use a generic argument for the delegate. The code below does NOT work, since \"Handler\" is a type variable, and the compiler won't cast <code>Handler</code> to <code>Delegate</code>:</p>\n\n<pre><code>public void AddHandler&lt;Handler&gt;(Control c, string eventName, Handler d) {\n c.GetType().GetEvent(eventName).AddEventHandler(c, (Delegate) d);\n}\n</code></pre>\n\n<p>However, you can pass a function that does the conversion for you. <code>convert</code> takes a <code>Handler</code> argument and returns a <code>Delegate</code>:</p>\n\n<pre><code>public void AddHandler&lt;Handler&gt;(Control c, string eventName, \n Func&lt;Delegate, Handler&gt; convert, Handler d) {\n c.GetType().GetEvent(eventName).AddEventHandler(c, convert(d));\n}\n</code></pre>\n\n<p>Now the compiler is happy. Calling the method is easy. For example, attaching to the <code>KeyPress</code> event on a Windows Forms control:</p>\n\n<pre><code>AddHandler&lt;KeyEventHandler&gt;(someControl, \n \"KeyPress\", \n (h) =&gt; (KeyEventHandler) h,\n SomeControl_KeyPress);\n</code></pre>\n\n<p>where <code>SomeControl_KeyPress</code> is the event target. The key is the converter lambda - it does no work, but it convinces the compiler you gave it a valid delegate.</p>\n\n<p>(Begin 280Z28) @Justin: Why not use this?</p>\n\n<pre><code>public void AddHandler&lt;Handler&gt;(Control c, string eventName, Handler d) { \n c.GetType().GetEvent(eventName).AddEventHandler(c, d as Delegate); \n} \n</code></pre>\n\n<p>(End 280Z28)</p>\n" }, { "answer_id": 10846397, "author": "Simon", "author_id": 53158, "author_profile": "https://Stackoverflow.com/users/53158", "pm_score": 3, "selected": false, "text": "<p>If you are willing to take a compile time dependency on an IL Weaver you can do this with <a href=\"https://github.com/Fody/Fody\" rel=\"noreferrer\">Fody</a>.</p>\n\n<p>Using this addin to Fody <a href=\"https://github.com/Fody/ExtraConstraints\" rel=\"noreferrer\">https://github.com/Fody/ExtraConstraints</a></p>\n\n<p><strong>Your code can look like this</strong> </p>\n\n<pre><code>public class Sample\n{\n public void MethodWithDelegateConstraint&lt;[DelegateConstraint] T&gt; ()\n { \n }\n public void MethodWithEnumConstraint&lt;[EnumConstraint] T&gt;()\n {\n }\n} \n</code></pre>\n\n<p><strong>And be compiled to this</strong> </p>\n\n<pre><code>public class Sample\n{\n public void MethodWithDelegateConstraint&lt;T&gt;() where T: Delegate\n {\n }\n\n public void MethodWithEnumConstraint&lt;T&gt;() where T: struct, Enum\n {\n }\n}\n</code></pre>\n" }, { "answer_id": 23728873, "author": "maxspan", "author_id": 2209468, "author_profile": "https://Stackoverflow.com/users/2209468", "pm_score": 2, "selected": false, "text": "<p>As mentioned above, you cannot have Delegates and Enum as a generic constraint. <code>System.Object</code> and <code>System.ValueType</code> also cannot be used as a generic constraint.</p>\n\n<p>The work around can be if you construct an appropriate call in you IL. It will work fine.</p>\n\n<p>Here is a good example by Jon Skeet. </p>\n\n<p><a href=\"http://code.google.com/p/unconstrained-melody/\" rel=\"nofollow noreferrer\">http://code.google.com/p/unconstrained-melody/</a></p>\n\n<p>I have taken my references from Jon Skeet's book <em>C# in Depth</em>, 3rd edition.</p>\n" }, { "answer_id": 29962594, "author": "Rahul Nikate", "author_id": 3936696, "author_profile": "https://Stackoverflow.com/users/3936696", "pm_score": 1, "selected": false, "text": "<p>According to <a href=\"https://msdn.microsoft.com/en-us/library/56b2hk61.aspx\" rel=\"nofollow\">MSDN</a> </p>\n\n<p><strong>Compiler Error CS0702</strong></p>\n\n<p>Constraint cannot be special class 'identifier' The following types may not be used as constraints: </p>\n\n<ul>\n<li>System.Object</li>\n<li>System.Array</li>\n<li>System.Delegate</li>\n<li>System.Enum</li>\n<li>System.ValueType.</li>\n</ul>\n" }, { "answer_id": 50291345, "author": "mshwf", "author_id": 6197785, "author_profile": "https://Stackoverflow.com/users/6197785", "pm_score": 4, "selected": false, "text": "<p>Yes it's possible in C# 7.3, Constraints family increased to include <code>Enum</code>, <code>Delegate</code> and <code>unmanaged</code> types.\nYou can write this code without a problem:</p>\n<pre><code>void M&lt;D, E, T&gt;(D d, E e, T* t) where D : Delegate where E : Enum where T : unmanaged\n {\n\n }\n</code></pre>\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/constraints-on-type-parameters#unmanaged-constraint\" rel=\"nofollow noreferrer\">From Docs</a>:</p>\n<blockquote>\n<p>Beginning with C# 7.3, you can use the unmanaged constraint to specify\nthat the type parameter must be a non-nullable unmanaged type. The\nunmanaged constraint enables you to write reusable routines to work\nwith types that can be manipulated as blocks of memory</p>\n</blockquote>\n<p>Useful links:</p>\n<p><a href=\"https://www.youtube.com/watch?v=QZ0rWLaMZeI&amp;t=650s\" rel=\"nofollow noreferrer\">The future of C#</a>, from Microsoft Build 2018</p>\n<p><a href=\"https://dev.to/borrrden/whats-new-in-c-73-26fk\" rel=\"nofollow noreferrer\">What's new in C# 7.3?</a></p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8945/" ]
Is it possible to define a class in C# such that ``` class GenericCollection<T> : SomeBaseCollection<T> where T : Delegate ``` I couldn't for the life of me accomplish this last night in .NET 3.5. I tried using `delegate, Delegate, Action<T> and Func<T, T>` It seems to me that this should be allowable in some way. I'm trying to implement my own EventQueue. I ended up just doing this [primitive approximation mind you]. ``` internal delegate void DWork(); class EventQueue { private Queue<DWork> eventq; } ``` But then I lose the ability to reuse the same definition for different types of functions. Thoughts?
A number of classes are unavailable as generic contraints - Enum being another. For delegates, the closest you can get is ": class", perhaps using reflection to check (for example, in the static constructor) that the T *is* a delegate: ``` static GenericCollection() { if (!typeof(T).IsSubclassOf(typeof(Delegate))) { throw new InvalidOperationException(typeof(T).Name + " is not a delegate type"); } } ```
191,950
<p>In my project I have a class that is inherited by many other classes. We'll call it ClassBase.</p> <pre><code>public class ClassInheritFromBase : ClassBase </code></pre> <p>When ClassBase is being inherited, <a href="http://en.wikipedia.org/wiki/ReSharper" rel="noreferrer">ReSharper</a> throws an "Ambiguous reference" warning on the ClassBase, and anything inside the new class that inherited from ClassBase does not have IntelliSense and gets warnings that it cannot find it.</p> <p>The project compiles and runs fine.</p> <p>If I change the namespace ClassBase is in and then change the inheriting classes, they find it fine and ReSharper has no problem, IntelliSense works ... until it is compiled. After the compile it goes back to having the ambiguous reference warnings and everything else.</p> <p>Has this been seen before and how can it be fixed? I saw an entry in JetBrains bug tracking for an issue just like this, but they closed it as unable to reproduce.</p>
[ { "answer_id": 263760, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I've seen this bug in ReSharper 4.1. It happens when the base class is in the App_Code directory. I don't know how to fix it; it is very annoying, but the code still compiles though.</p>\n" }, { "answer_id": 369770, "author": "terjetyl", "author_id": 29519, "author_profile": "https://Stackoverflow.com/users/29519", "pm_score": 2, "selected": true, "text": "<p>This is a bug in ReSharper 4.1 and is fixed in one of the later nightly builds.</p>\n\n<p>Download the last nightly build at\n<a href=\"http://www.jetbrains.net/confluence/display/ReSharper/ReSharper+4.0+Nightly+Builds\" rel=\"nofollow noreferrer\">http://www.jetbrains.net/confluence/display/ReSharper/ReSharper+4.0+Nightly+Builds</a>.</p>\n" }, { "answer_id": 606123, "author": "Dennito", "author_id": 2342930, "author_profile": "https://Stackoverflow.com/users/2342930", "pm_score": 0, "selected": false, "text": "<p>I encountered the same problem. The issue I had was caused by a custom build provider (from an open source library I'm using called <a href=\"http://www.codeplex.com/PageMethods\" rel=\"nofollow noreferrer\">PageMethods</a>) and the fact that all my .aspx pages inherit from a BasePage class which lives in the App_Code folder.</p>\n\n<p>I couldn't get any build of ReSharper to work with my project (4.1.933, 4.1.943 (latest) or 4.5). The fix in the latest ReSharper build fixes the \"Ambiguous Reference\" problem, but breaks the custom build provider.</p>\n\n<p>The only way I could get both the build provider and base classes to work with ReSharper was to put the Base Classes into a separate class library.</p>\n\n<p>The following are the logged Jira bugs that seem to relate to this issue:</p>\n\n<ul>\n<li><a href=\"http://www.jetbrains.net/jira/browse/RSRP-92804\" rel=\"nofollow noreferrer\">False \"Ambiguous reference\" for\nsymbols from App_Code</a></li>\n<li><a href=\"http://www.jetbrains.net/jira/browse/RSRP-68028\" rel=\"nofollow noreferrer\">Custom build provider may generate partial\nclass with second part residing in\napp_code</a></li>\n</ul>\n" }, { "answer_id": 1636785, "author": "Jonathan Williams", "author_id": 197993, "author_profile": "https://Stackoverflow.com/users/197993", "pm_score": 0, "selected": false, "text": "<p>I was experiencing the same problem with references to C# classes in the AppCode folder.</p>\n\n<p>I resolved this by upgrading my ReSharper to version 4.5 (from version 4.1).</p>\n\n<p>It was a very simple upgrade, I just had to get the latest version from the JetBrains website (<a href=\"http://www.jetbrains.com/resharper/download/\" rel=\"nofollow noreferrer\">http://www.jetbrains.com/resharper/download/</a>) and run it.</p>\n\n<p>I did not have to uninstall the previous version (v4.1).\nI did not have to re-enter my existing licence key.</p>\n\n<p>All references are now recognised correctly and I can naviage to the classes as expected.</p>\n" }, { "answer_id": 3458805, "author": "Gokce Mutlu", "author_id": 417290, "author_profile": "https://Stackoverflow.com/users/417290", "pm_score": 1, "selected": false, "text": "<p>ReSharper -> Options -> General: Click # Clear Caches # button.</p>\n" }, { "answer_id": 4744901, "author": "MortenRøgenes", "author_id": 572822, "author_profile": "https://Stackoverflow.com/users/572822", "pm_score": 4, "selected": false, "text": "<p>For those who still have a problem with this, (I still get it from time to time) here's the steps I did to get rid of the ambiguous reference warning in ReSharper.</p>\n\n<ol>\n<li>First I went to all my class libraries and made sure that all references to my other class libraries had the <em>Copy Local</em> property set to false.</li>\n<li>In the project where I actually got the ambiguous reference warning, I went to my bin catalog and deleted all .dll and .pdb files for all the libraries that had their own project.</li>\n<li>After a new build, or in my case \"update reference\" on the .dll files in VS, the errors from Resharper were gone.</li>\n</ol>\n\n<p>I'm using Resharper 5.1 in Visual Studio 2008 with only a reference to the dlls I'm using which is why I had to \"update reference\"</p>\n" }, { "answer_id": 5126650, "author": "Henrik", "author_id": 63621, "author_profile": "https://Stackoverflow.com/users/63621", "pm_score": 1, "selected": false, "text": "<p>For me it was a matter of me not using the solution folder for caches. Changing it from the TEMP location to in the solution solved my problem.</p>\n" }, { "answer_id": 5242546, "author": "Andreas Presthammer", "author_id": 596855, "author_profile": "https://Stackoverflow.com/users/596855", "pm_score": 0, "selected": false, "text": "<p>I had same problem with ReSharper 5.1 and solved it by restarting Visual Studio 2010.</p>\n" }, { "answer_id": 7201856, "author": "Peter", "author_id": 333427, "author_profile": "https://Stackoverflow.com/users/333427", "pm_score": 1, "selected": false, "text": "<p>I deleted the _ReSharper.SolutionName folder found in the root of my solution and restarted.</p>\n\n<p>I was using Visual&nbsp;Studio&nbsp;2010 with ReSharper 5.1... Clearing the cache <strong>DID NOT</strong> help (ReSharper -> menu <em>Options</em> -> <em>General</em> -> #Clear Cache#).</p>\n" }, { "answer_id": 21991172, "author": "Miguel", "author_id": 416255, "author_profile": "https://Stackoverflow.com/users/416255", "pm_score": 3, "selected": false, "text": "<p>I'm using VS 2012 and ReSharper 7 and sometimes I found the same behavior. These are the steps that worked for me:</p>\n\n<ol>\n<li>Clean Solution</li>\n<li>Close Visual Studio</li>\n<li>Go to the root folder of your solution and find a folder called _ReSharper.[Name of your solution] and delete it.</li>\n<li>Go back to Visual Studio, open up your solution the folder gets recreated and no more \"ambiguous reference\" errors after that.</li>\n</ol>\n" }, { "answer_id": 22411256, "author": "HiredMind", "author_id": 79648, "author_profile": "https://Stackoverflow.com/users/79648", "pm_score": 0, "selected": false, "text": "<p>Using VS 2013 Premium &amp; Resharper 8.1, and was getting this problem on an ASP.Net project. </p>\n\n<p>The solution that worked for me: </p>\n\n<ol>\n<li>Do a clean Solution.</li>\n<li>Open references for the offending project</li>\n<li>On each reference that refers to another project in the solution, set <code>Copy Local = false</code>.</li>\n<li>Attempt a Rebuild Solution. You will likely get unresolved reference errors - that's normal.</li>\n<li>Set each reference back to <code>Copy Local = true</code> (where appropriate)</li>\n</ol>\n" }, { "answer_id": 31254550, "author": "Evan", "author_id": 4343254, "author_profile": "https://Stackoverflow.com/users/4343254", "pm_score": 2, "selected": false, "text": "<p>You may really have an ambiguous reference. In the project where the ambiguous reference error occurs, make sure to check in your project references. You might have the same reference twice but scoped through different namespaces. In my case there were two, but with different paths (example):</p>\n\n<pre><code>XXX.YYY.ZZZ.myassembly\nZZZ.myassembly\n</code></pre>\n\n<p>Make sure you don't have this kind of thing in your references.</p>\n" }, { "answer_id": 58864437, "author": "Dave Cousineau", "author_id": 621316, "author_profile": "https://Stackoverflow.com/users/621316", "pm_score": 1, "selected": false, "text": "<p>With R# 2019.2.3 and using the new SDK .csproj format, which splits references between .NET references, NUGET packages, and project dependencies, there is a tendency for R# to still add a project reference under Assemblies, even when there is already a project reference under Dependencies. This results in the ambiguity error but can be hard to notice since the reference is in two separate places. Look for any project references that appear under Assemblies and remove them.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191950", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1215/" ]
In my project I have a class that is inherited by many other classes. We'll call it ClassBase. ``` public class ClassInheritFromBase : ClassBase ``` When ClassBase is being inherited, [ReSharper](http://en.wikipedia.org/wiki/ReSharper) throws an "Ambiguous reference" warning on the ClassBase, and anything inside the new class that inherited from ClassBase does not have IntelliSense and gets warnings that it cannot find it. The project compiles and runs fine. If I change the namespace ClassBase is in and then change the inheriting classes, they find it fine and ReSharper has no problem, IntelliSense works ... until it is compiled. After the compile it goes back to having the ambiguous reference warnings and everything else. Has this been seen before and how can it be fixed? I saw an entry in JetBrains bug tracking for an issue just like this, but they closed it as unable to reproduce.
This is a bug in ReSharper 4.1 and is fixed in one of the later nightly builds. Download the last nightly build at <http://www.jetbrains.net/confluence/display/ReSharper/ReSharper+4.0+Nightly+Builds>.
191,952
<p>If I have the following Linq code:</p> <pre><code>context.Table1s.InsertOnSubmit(t); context.Table1s.InsertOnSubmit(t2); context.Table1s.InsertOnSubmit(t3); context.SubmitChanges(); </code></pre> <p>And I get a database error due to the 2nd insert, Linq throws an exception that there was an error. But, is there a way to find out that it was the 2nd insert that had the problem and not the 1st or 3rd?</p> <p>To clarify, there are business reasons that I would expect the 2nd to fail (I am using a stored procedure to do the insert and am also doing some validation and raising an error if it fails). I want to be able to tell the user which one failed and why. I know this validation would be better done in the C# code and not in the database, but that is currently not an option.</p>
[ { "answer_id": 263760, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I've seen this bug in ReSharper 4.1. It happens when the base class is in the App_Code directory. I don't know how to fix it; it is very annoying, but the code still compiles though.</p>\n" }, { "answer_id": 369770, "author": "terjetyl", "author_id": 29519, "author_profile": "https://Stackoverflow.com/users/29519", "pm_score": 2, "selected": true, "text": "<p>This is a bug in ReSharper 4.1 and is fixed in one of the later nightly builds.</p>\n\n<p>Download the last nightly build at\n<a href=\"http://www.jetbrains.net/confluence/display/ReSharper/ReSharper+4.0+Nightly+Builds\" rel=\"nofollow noreferrer\">http://www.jetbrains.net/confluence/display/ReSharper/ReSharper+4.0+Nightly+Builds</a>.</p>\n" }, { "answer_id": 606123, "author": "Dennito", "author_id": 2342930, "author_profile": "https://Stackoverflow.com/users/2342930", "pm_score": 0, "selected": false, "text": "<p>I encountered the same problem. The issue I had was caused by a custom build provider (from an open source library I'm using called <a href=\"http://www.codeplex.com/PageMethods\" rel=\"nofollow noreferrer\">PageMethods</a>) and the fact that all my .aspx pages inherit from a BasePage class which lives in the App_Code folder.</p>\n\n<p>I couldn't get any build of ReSharper to work with my project (4.1.933, 4.1.943 (latest) or 4.5). The fix in the latest ReSharper build fixes the \"Ambiguous Reference\" problem, but breaks the custom build provider.</p>\n\n<p>The only way I could get both the build provider and base classes to work with ReSharper was to put the Base Classes into a separate class library.</p>\n\n<p>The following are the logged Jira bugs that seem to relate to this issue:</p>\n\n<ul>\n<li><a href=\"http://www.jetbrains.net/jira/browse/RSRP-92804\" rel=\"nofollow noreferrer\">False \"Ambiguous reference\" for\nsymbols from App_Code</a></li>\n<li><a href=\"http://www.jetbrains.net/jira/browse/RSRP-68028\" rel=\"nofollow noreferrer\">Custom build provider may generate partial\nclass with second part residing in\napp_code</a></li>\n</ul>\n" }, { "answer_id": 1636785, "author": "Jonathan Williams", "author_id": 197993, "author_profile": "https://Stackoverflow.com/users/197993", "pm_score": 0, "selected": false, "text": "<p>I was experiencing the same problem with references to C# classes in the AppCode folder.</p>\n\n<p>I resolved this by upgrading my ReSharper to version 4.5 (from version 4.1).</p>\n\n<p>It was a very simple upgrade, I just had to get the latest version from the JetBrains website (<a href=\"http://www.jetbrains.com/resharper/download/\" rel=\"nofollow noreferrer\">http://www.jetbrains.com/resharper/download/</a>) and run it.</p>\n\n<p>I did not have to uninstall the previous version (v4.1).\nI did not have to re-enter my existing licence key.</p>\n\n<p>All references are now recognised correctly and I can naviage to the classes as expected.</p>\n" }, { "answer_id": 3458805, "author": "Gokce Mutlu", "author_id": 417290, "author_profile": "https://Stackoverflow.com/users/417290", "pm_score": 1, "selected": false, "text": "<p>ReSharper -> Options -> General: Click # Clear Caches # button.</p>\n" }, { "answer_id": 4744901, "author": "MortenRøgenes", "author_id": 572822, "author_profile": "https://Stackoverflow.com/users/572822", "pm_score": 4, "selected": false, "text": "<p>For those who still have a problem with this, (I still get it from time to time) here's the steps I did to get rid of the ambiguous reference warning in ReSharper.</p>\n\n<ol>\n<li>First I went to all my class libraries and made sure that all references to my other class libraries had the <em>Copy Local</em> property set to false.</li>\n<li>In the project where I actually got the ambiguous reference warning, I went to my bin catalog and deleted all .dll and .pdb files for all the libraries that had their own project.</li>\n<li>After a new build, or in my case \"update reference\" on the .dll files in VS, the errors from Resharper were gone.</li>\n</ol>\n\n<p>I'm using Resharper 5.1 in Visual Studio 2008 with only a reference to the dlls I'm using which is why I had to \"update reference\"</p>\n" }, { "answer_id": 5126650, "author": "Henrik", "author_id": 63621, "author_profile": "https://Stackoverflow.com/users/63621", "pm_score": 1, "selected": false, "text": "<p>For me it was a matter of me not using the solution folder for caches. Changing it from the TEMP location to in the solution solved my problem.</p>\n" }, { "answer_id": 5242546, "author": "Andreas Presthammer", "author_id": 596855, "author_profile": "https://Stackoverflow.com/users/596855", "pm_score": 0, "selected": false, "text": "<p>I had same problem with ReSharper 5.1 and solved it by restarting Visual Studio 2010.</p>\n" }, { "answer_id": 7201856, "author": "Peter", "author_id": 333427, "author_profile": "https://Stackoverflow.com/users/333427", "pm_score": 1, "selected": false, "text": "<p>I deleted the _ReSharper.SolutionName folder found in the root of my solution and restarted.</p>\n\n<p>I was using Visual&nbsp;Studio&nbsp;2010 with ReSharper 5.1... Clearing the cache <strong>DID NOT</strong> help (ReSharper -> menu <em>Options</em> -> <em>General</em> -> #Clear Cache#).</p>\n" }, { "answer_id": 21991172, "author": "Miguel", "author_id": 416255, "author_profile": "https://Stackoverflow.com/users/416255", "pm_score": 3, "selected": false, "text": "<p>I'm using VS 2012 and ReSharper 7 and sometimes I found the same behavior. These are the steps that worked for me:</p>\n\n<ol>\n<li>Clean Solution</li>\n<li>Close Visual Studio</li>\n<li>Go to the root folder of your solution and find a folder called _ReSharper.[Name of your solution] and delete it.</li>\n<li>Go back to Visual Studio, open up your solution the folder gets recreated and no more \"ambiguous reference\" errors after that.</li>\n</ol>\n" }, { "answer_id": 22411256, "author": "HiredMind", "author_id": 79648, "author_profile": "https://Stackoverflow.com/users/79648", "pm_score": 0, "selected": false, "text": "<p>Using VS 2013 Premium &amp; Resharper 8.1, and was getting this problem on an ASP.Net project. </p>\n\n<p>The solution that worked for me: </p>\n\n<ol>\n<li>Do a clean Solution.</li>\n<li>Open references for the offending project</li>\n<li>On each reference that refers to another project in the solution, set <code>Copy Local = false</code>.</li>\n<li>Attempt a Rebuild Solution. You will likely get unresolved reference errors - that's normal.</li>\n<li>Set each reference back to <code>Copy Local = true</code> (where appropriate)</li>\n</ol>\n" }, { "answer_id": 31254550, "author": "Evan", "author_id": 4343254, "author_profile": "https://Stackoverflow.com/users/4343254", "pm_score": 2, "selected": false, "text": "<p>You may really have an ambiguous reference. In the project where the ambiguous reference error occurs, make sure to check in your project references. You might have the same reference twice but scoped through different namespaces. In my case there were two, but with different paths (example):</p>\n\n<pre><code>XXX.YYY.ZZZ.myassembly\nZZZ.myassembly\n</code></pre>\n\n<p>Make sure you don't have this kind of thing in your references.</p>\n" }, { "answer_id": 58864437, "author": "Dave Cousineau", "author_id": 621316, "author_profile": "https://Stackoverflow.com/users/621316", "pm_score": 1, "selected": false, "text": "<p>With R# 2019.2.3 and using the new SDK .csproj format, which splits references between .NET references, NUGET packages, and project dependencies, there is a tendency for R# to still add a project reference under Assemblies, even when there is already a project reference under Dependencies. This results in the ambiguity error but can be hard to notice since the reference is in two separate places. Look for any project references that appear under Assemblies and remove them.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3291/" ]
If I have the following Linq code: ``` context.Table1s.InsertOnSubmit(t); context.Table1s.InsertOnSubmit(t2); context.Table1s.InsertOnSubmit(t3); context.SubmitChanges(); ``` And I get a database error due to the 2nd insert, Linq throws an exception that there was an error. But, is there a way to find out that it was the 2nd insert that had the problem and not the 1st or 3rd? To clarify, there are business reasons that I would expect the 2nd to fail (I am using a stored procedure to do the insert and am also doing some validation and raising an error if it fails). I want to be able to tell the user which one failed and why. I know this validation would be better done in the C# code and not in the database, but that is currently not an option.
This is a bug in ReSharper 4.1 and is fixed in one of the later nightly builds. Download the last nightly build at <http://www.jetbrains.net/confluence/display/ReSharper/ReSharper+4.0+Nightly+Builds>.
191,955
<p>What is the correct way to do this? For example, how would I change a stored procedure with this signature:</p> <pre><code>CREATE PROCEDURE dbo.MyProcedure @Param BIT = NULL AS SELECT * FROM dbo.SomeTable T WHERE T.SomeColumn = @Param </code></pre> <p>So that giving @Param with a value of 1 or 0 performs the filter, but not specifying it or passing NULL performs no filtering?</p>
[ { "answer_id": 191971, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": true, "text": "<p>Assuming that NULL means \"don't care\" then use</p>\n\n<pre><code>CREATE PROCEDURE dbo.MyProcedure \n @Param BIT = NULL\nAS\n SELECT *\n FROM dbo.SomeTable T\n WHERE T.SomeColumn = @Param OR @Param IS NULL\n</code></pre>\n" }, { "answer_id": 192156, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "<p>I happen to think that the cleanest way of doing this is (in T-SQL) is:</p>\n\n<pre><code>SELECT * FROM TABLE WHERE column = ISNULL(@param, column)\n</code></pre>\n\n<p>Other RDBMS would prefer COALESCE instead of ISNULL.</p>\n\n<p>I think it's more obvious what the intent is here, especially as you start to add other OR clauses, and it also keeps you from needing parens when combining with AND clauses.</p>\n\n<p>In my (very) limited testing, there was also a negligible perf increase using ISNULL versus OR @p IS NULL. Not that I'm advocating using ISNULL <em>because</em> of the perf increase (which is extremely marginal at best, and is subject to very specific cases at worst) but it's nice to know it doesn't have a significant cost. Frankly, I'm not sure why it'd make a difference either way, but the execution plan shows about a 1% difference in the filter cost.</p>\n" }, { "answer_id": 192159, "author": "bart", "author_id": 19966, "author_profile": "https://Stackoverflow.com/users/19966", "pm_score": 1, "selected": false, "text": "<p>There's more than one way. Here's one:</p>\n\n<pre><code>SELECT *\n FROM dbo.SomeTable T\n WHERE T.SomeColumn = COALESCE(@Param, T.SomeColumn)\n</code></pre>\n\n<p>but this will not include rows for which T.SomeColumn is NULL. </p>\n\n<p>The following alternative will include those rows:</p>\n\n<pre><code>SELECT *\n FROM dbo.SomeTable T\n WHERE T.SomeColumn = @Param OR @Param IS NULL\n</code></pre>\n\n<p>but it has the disadvantage of the repeated parameter, which is not nice in case you're using another way to pass in parameters, for example, using a placeholder.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6651/" ]
What is the correct way to do this? For example, how would I change a stored procedure with this signature: ``` CREATE PROCEDURE dbo.MyProcedure @Param BIT = NULL AS SELECT * FROM dbo.SomeTable T WHERE T.SomeColumn = @Param ``` So that giving @Param with a value of 1 or 0 performs the filter, but not specifying it or passing NULL performs no filtering?
Assuming that NULL means "don't care" then use ``` CREATE PROCEDURE dbo.MyProcedure @Param BIT = NULL AS SELECT * FROM dbo.SomeTable T WHERE T.SomeColumn = @Param OR @Param IS NULL ```
191,984
<p>I am writing a little application, which is writing jpeg images at a constant rate on a SD card. I choose an EXT3 filesystem, but the same behaviour was observed with an EXT2 filesystem.</p> <p>My writing loop looks like this :</p> <pre><code>get_image() fwrite() fsync() </code></pre> <p>Or like this :</p> <pre><code>get_image() fopen() fwrite() fsync() fclose() </code></pre> <p>I also display some timing statistics, and I can see my program is sometime blocked for several seconds. The average rate is still good, because if I keep the incoming images into a fifo, then I will write many image in a short period of time after such a stall. Do you know if it is a problem with the OS or if it is related to the SD card itself ? How could I move closer to realtime ? I don't need strong realtime, but being stalled for several seconds is not acceptable.</p> <p>Some precision : Yes it is necessary to fsync after every file, because I want the image to be on disk, not in some user or kernel buffer. Without fsyncing, I have much better throughoutput, but still unacceptable stall. I don't think it is a buffer problem, since the first stall happens after 50 Mbytes have been written. And according to the man page, fsync is here precisely to ensure there is no data buffered.</p> <p>Precision regarding the average write rate : I am writing at a rate that is sustainable by the card I am using. If I pile incoming image while waiting for an fsync to complete, then after this stall the write transfer rate will increase and I will quickly go back to the average rate. The average transfer rate is around 1.4 MBytes /s.</p> <p>The systeme is a modern laptop running ubuntu 8.04 with stock kee (2.6.24.19)</p>
[ { "answer_id": 192102, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 1, "selected": false, "text": "<p>I'm not very knowledgeable in this area, but the symptoms you describe sound an awful lot like filling up a buffer. You may be filling a buffer in the file writer or in the I/O device communicating with the SD card itself. You then have to wait until it actually writes the data to the card (thus emptying the buffer) before you can write more. SD cards are not particularly fast writers. If you can find a way to check if data is actually being written to the card during these pauses, that would verify my theory. Some card readers have an LED that blinks when data is being accessed -- that would probably be a good indicator.</p>\n\n<p>Just a hunch... take it with some salt :)</p>\n" }, { "answer_id": 192107, "author": "Matt J", "author_id": 18528, "author_profile": "https://Stackoverflow.com/users/18528", "pm_score": 2, "selected": false, "text": "<p>Is it necessary to <code>fsync()</code> after every file? You may have better luck letting the OS decide when a good time is to write out all enqueued images to the SD card (amortizing the startup cost of manipulating the SD card filesystem over many images, rather than incurring it for every image).</p>\n\n<p>Can you provide some more details about your platform? Slow I/O times may have to do with other processes on the system, a slow I/O controller, etc..</p>\n\n<p>You might also consider using a filesystem more suited to how flash memory works. FAT32 is more common than <code>extN</code>, but a filesystem specifically built for SD may be in order as well. <a href=\"http://en.wikipedia.org/wiki/JFFS\" rel=\"nofollow noreferrer\">JFFS</a> is a good example of this. You will probably get better performance with a filesystem designed for flash (as opposed to spinning magnetic media), and you get better wear-leveling (and thus device lifetime/reliability) properties as well.</p>\n" }, { "answer_id": 198935, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>AFAIK some flash disks have really bad write performance (esp. cheap brands). So if you measure the write speed of your application (including the time required for fsync), what do you get? It might easily be in the order of very few megabytes per second - just because the hardware doesn't do better.</p>\n\n<p>Also, apparently writing can be much slower if you write many small blocks instead of one big block (the flash disk might only get about 10 writes per second done, in bad cases). This is probably something that can be mitigated by the kernel buffer, so using fsync frequently might slow down the writing...</p>\n\n<p>Btw. did you measure write performance on FAT32? I would guess it is about the same, but if not, maybe there's some optimization still available?</p>\n" }, { "answer_id": 434254, "author": "Malx", "author_id": 51086, "author_profile": "https://Stackoverflow.com/users/51086", "pm_score": 1, "selected": false, "text": "<p>May be this will help - <a href=\"http://linuxgazette.net/102/piszcz.html\" rel=\"nofollow noreferrer\">Benchmarking Filesystems</a>:</p>\n\n<blockquote>\n <p>...I was quite surprised how slow ext3 was overall, as many distributions use this file system as their default file system...</p>\n</blockquote>\n\n<p>And <a href=\"http://lkml.indiana.edu/hypermail/linux/kernel/0808.2/1195.html\" rel=\"nofollow noreferrer\">\"ext3 fsync batching\"</a>:</p>\n\n<blockquote>\n <p>...This patch measures the time it takes to commit a transaction to the disk, and sleeps based on the speed of the underlying disk.</p>\n</blockquote>\n" }, { "answer_id": 543093, "author": "ja.", "author_id": 15467, "author_profile": "https://Stackoverflow.com/users/15467", "pm_score": -1, "selected": false, "text": "<p>Might also consider the SD Card, is it NOR or NAND? This page shows an order of magnitude between sd cards (2M/s vs 20M/s).<br>\n <a href=\"http://www.robgalbraith.com/bins/camera_multi_page.asp?cid=6007-9597\" rel=\"nofollow noreferrer\">http://www.robgalbraith.com/bins/camera_multi_page.asp?cid=6007-9597\n</a><br>\nI think ZFS is optimized for flash memory.</p>\n" }, { "answer_id": 2098613, "author": "pierrotlefou", "author_id": 115722, "author_profile": "https://Stackoverflow.com/users/115722", "pm_score": 2, "selected": false, "text": "<p>Try to open the file with <code>O_DIRECT</code> and do the caching in application level.</p>\n\n<p>We met the similar issue when we were implementing a PVR (Personal Video Record) feature in STB Box. The <code>O_DIRECT</code> trick satisfied our need finaly.(*)</p>\n\n<p>Without <code>O_DIRECT</code>. The data of <code>write()</code> will firstly be cached in the kernel buffer and then be flushed to the media when you call <code>fsync</code> or when the kernel cache buffer is full.(**). </p>\n\n<p>With <code>O_DIRECT</code>.Th kernel will do DMA directly to the physical memory pointed by the userspace buffer passed as parameter to the <code>write</code> syscalls. So there will be no CPU and mem bandwidth spent in the copies between userspace memory and kernel cache, and there will be no CPU time spent in kernel in the management of the cache (like cache lookups, per-page locks etc..).( copied from <a href=\"http://www.ukuug.org/events/linux2001/papers/html/AArcangeli-o_direct.html\" rel=\"nofollow noreferrer\">here</a> )</p>\n\n<p>Not sure it can also solve your problem, but you might want to have a try.</p>\n\n<p>*Despite of Linus's <a href=\"http://kerneltrap.org/node/7563\" rel=\"nofollow noreferrer\">critize</a> of <code>O_DIRECT</code> ,it did solve our problems.</p>\n\n<p>** suppose you did not open the file with <code>O_DSYNC</code> or <code>O_SYNC</code></p>\n" }, { "answer_id": 21766889, "author": "jcarballo", "author_id": 1247192, "author_profile": "https://Stackoverflow.com/users/1247192", "pm_score": 0, "selected": false, "text": "<p>For anyone reading this and using a kernel above 2.6.28, the recommendation is to use ext4 instead of ext3, which is a filesystem that you can tune for better performance. The best performance is obtained in data=writeback mode, where data is not journaled. Read the <strong>Data Mode</strong> section from <a href=\"https://www.kernel.org/doc/Documentation/filesystems/ext4.txt\" rel=\"nofollow\">https://www.kernel.org/doc/Documentation/filesystems/ext4.txt</a>.</p>\n\n<p>If you have a partition already created, say <code>/dev/sdb1</code>, then these are some steps that can be used to format it with ext4 without journaling:</p>\n\n<pre><code>mkfs.ext4 /dev/sdb1 -L jp # Creates the ext4 filesystem\ntune2fs -o journal_data_writeback /dev/sdb1 # Set to writeback mode\ntune2fs -O ^has_journal /dev/sdb1 # Disable journaling\nsudo e2fsck -f /dev/sdb1 # Filesystem check is required\n</code></pre>\n\n<p>Then, you can mount this partition (or set an entry <code>/etc/fstab</code> if you know what you're doing) with the corresponding flags:</p>\n\n<pre><code>mount -t ext4 -O noatime,nodirame,data=writeback /dev/mmcblk0p1 /mnt/sd\n</code></pre>\n\n<p>Moving from ext3 to an optimized ext4 filesystem should be a drastic difference. And, of course, if your SD card is quicker that should help (i.e. class 10).</p>\n\n<p>See also <a href=\"https://developer.ridgerun.com/wiki/index.php/High_performance_SD_card_tuning_using_the_EXT4_file_system\" rel=\"nofollow\" title=\"High performance SD card tuning using the EXT4 file system\">https://developer.ridgerun.com/wiki/index.php/High_performance_SD_card_tuning_using_the_EXT4_file_system</a></p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11589/" ]
I am writing a little application, which is writing jpeg images at a constant rate on a SD card. I choose an EXT3 filesystem, but the same behaviour was observed with an EXT2 filesystem. My writing loop looks like this : ``` get_image() fwrite() fsync() ``` Or like this : ``` get_image() fopen() fwrite() fsync() fclose() ``` I also display some timing statistics, and I can see my program is sometime blocked for several seconds. The average rate is still good, because if I keep the incoming images into a fifo, then I will write many image in a short period of time after such a stall. Do you know if it is a problem with the OS or if it is related to the SD card itself ? How could I move closer to realtime ? I don't need strong realtime, but being stalled for several seconds is not acceptable. Some precision : Yes it is necessary to fsync after every file, because I want the image to be on disk, not in some user or kernel buffer. Without fsyncing, I have much better throughoutput, but still unacceptable stall. I don't think it is a buffer problem, since the first stall happens after 50 Mbytes have been written. And according to the man page, fsync is here precisely to ensure there is no data buffered. Precision regarding the average write rate : I am writing at a rate that is sustainable by the card I am using. If I pile incoming image while waiting for an fsync to complete, then after this stall the write transfer rate will increase and I will quickly go back to the average rate. The average transfer rate is around 1.4 MBytes /s. The systeme is a modern laptop running ubuntu 8.04 with stock kee (2.6.24.19)
Is it necessary to `fsync()` after every file? You may have better luck letting the OS decide when a good time is to write out all enqueued images to the SD card (amortizing the startup cost of manipulating the SD card filesystem over many images, rather than incurring it for every image). Can you provide some more details about your platform? Slow I/O times may have to do with other processes on the system, a slow I/O controller, etc.. You might also consider using a filesystem more suited to how flash memory works. FAT32 is more common than `extN`, but a filesystem specifically built for SD may be in order as well. [JFFS](http://en.wikipedia.org/wiki/JFFS) is a good example of this. You will probably get better performance with a filesystem designed for flash (as opposed to spinning magnetic media), and you get better wear-leveling (and thus device lifetime/reliability) properties as well.
191,998
<p>In Eclipse (Ganymede) I'm debugging some code that uses Apache Commons HttpClient and would like to step into the HttpClient code. I've downloaded the source code and tried to attach it in the normal fashion (CTRL-click on the method name and use the Attach Source button). I've tried to attach both as external file and external folder with no success. I've attached source before with no issues and can currently step into Hibernate source code successfully.</p> <p>I've even tried editing the .classpath file directly to add sourcepath manually. Still no luck. Refreshing the project, doing a clean build, closing and re-opening Eclipse do not solve the issue. Frustratingly, Eclipse provides no error message; it just does not attach the source.</p> <p>Here are the entries in .claspath:</p> <pre><code>&lt;!-- Hibernate. Works --&gt; &lt;classpathentry kind="lib" path="/myEAP/EarContent/APP-INF/lib/hibernate.jar" sourcepath="D:/Data/Download/hibernate-3.2.2.ga/hibernate-3.2/src"/&gt; &lt;!-- Commons HttpClient. Will not attach --&gt; &lt;classpathentry kind="lib" path="/myEAP/EarContent/APP-INF/lib/commons-httpclient.jar" sourcepath="D:/Data/Download/commons-httpclient-3.1/src/java"/&gt; </code></pre> <p>I've tried changing the path to D:/Data/Download/commons-httpclient-3.1/src and that does not work either.</p> <p>The directory structure is:</p> <pre><code>D Data Download commons-httpclient-3.1 src java org apache commons httpclient AutoCloseInputStream.java ... (and so forth) </code></pre>
[ { "answer_id": 192054, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 2, "selected": false, "text": "<p>Try attaching the src.zip instead of the unzipped src?</p>\n" }, { "answer_id": 192240, "author": "Dave Dunkin", "author_id": 453303, "author_profile": "https://Stackoverflow.com/users/453303", "pm_score": 2, "selected": false, "text": "<p>Try adding it to the source path of your launch configuration.</p>\n" }, { "answer_id": 193261, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 1, "selected": false, "text": "<p>Attaching sources is not all that is required to step into a library on the classpath; that library must also be compiled with debug symbols. This usually isn't a problem, since most Java libraries are compiled and distributed in such a fashion, but as you have found, some of them are not.</p>\n\n<p>It is interesting to note that you can actually step into external libraries even without the source attached, you just can't see the line-by-line sources (all of the debug info still works).</p>\n\n<p>You could \"fix\" this problem by compiling a custom version of Commons HttpClient (not too difficult), or just skip the whole \"step into the library\" idea. As a general development practice, stepping into third-party libraries will rarely yield useful information. I've done it maybe once or twice in the last ten years, neither time did it actually bring me any closer to solving the dilemma at hand.</p>\n" }, { "answer_id": 193385, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 4, "selected": true, "text": "<p>Try pointing it at a directory containing the top level package directly, \"D:/Data/Download/commons-httpclient-3.1/src/java\" for you. What worked for me was creating a new src zip file containing the \"org\" folder and everything beneath it.</p>\n\n<p>Here's my .classpath entry, (which works for me) in case it helps:</p>\n\n<pre><code>&lt;classpathentry kind=\"lib\" path=\"/blib/java/commons-httpclient-3.1/commons-httpclient-3.1.jar\" sourcepath=\"/blib/java/commons-httpclient-3.1/commons-httpclient-3.1-src.zip\"/&gt;\n</code></pre>\n" }, { "answer_id": 3289567, "author": "stolsvik", "author_id": 39334, "author_profile": "https://Stackoverflow.com/users/39334", "pm_score": 2, "selected": false, "text": "<p>I've found that sometimes, you point to the directory you'd assume was correct, and then it still states that it can't find the file in the attached source blah blah.</p>\n\n<p>These times, I've realized that the last path element was \"src\". Just removing this path element (thus indeed pointing one level above the actual path where the \"org\" or \"com\" folder is located) magically makes it work.</p>\n\n<p>Somehow, Eclipse seems to imply this \"src\" path element if present, and if you then have it included in the source path, Eclipse chokes. Or something like that.</p>\n" }, { "answer_id": 5565934, "author": "Evgeny P", "author_id": 694768, "author_profile": "https://Stackoverflow.com/users/694768", "pm_score": 1, "selected": false, "text": "<p>I think, problem in space (or localized) simbols in path to source archive. Try to move it to another place with simple path.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/191998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18995/" ]
In Eclipse (Ganymede) I'm debugging some code that uses Apache Commons HttpClient and would like to step into the HttpClient code. I've downloaded the source code and tried to attach it in the normal fashion (CTRL-click on the method name and use the Attach Source button). I've tried to attach both as external file and external folder with no success. I've attached source before with no issues and can currently step into Hibernate source code successfully. I've even tried editing the .classpath file directly to add sourcepath manually. Still no luck. Refreshing the project, doing a clean build, closing and re-opening Eclipse do not solve the issue. Frustratingly, Eclipse provides no error message; it just does not attach the source. Here are the entries in .claspath: ``` <!-- Hibernate. Works --> <classpathentry kind="lib" path="/myEAP/EarContent/APP-INF/lib/hibernate.jar" sourcepath="D:/Data/Download/hibernate-3.2.2.ga/hibernate-3.2/src"/> <!-- Commons HttpClient. Will not attach --> <classpathentry kind="lib" path="/myEAP/EarContent/APP-INF/lib/commons-httpclient.jar" sourcepath="D:/Data/Download/commons-httpclient-3.1/src/java"/> ``` I've tried changing the path to D:/Data/Download/commons-httpclient-3.1/src and that does not work either. The directory structure is: ``` D Data Download commons-httpclient-3.1 src java org apache commons httpclient AutoCloseInputStream.java ... (and so forth) ```
Try pointing it at a directory containing the top level package directly, "D:/Data/Download/commons-httpclient-3.1/src/java" for you. What worked for me was creating a new src zip file containing the "org" folder and everything beneath it. Here's my .classpath entry, (which works for me) in case it helps: ``` <classpathentry kind="lib" path="/blib/java/commons-httpclient-3.1/commons-httpclient-3.1.jar" sourcepath="/blib/java/commons-httpclient-3.1/commons-httpclient-3.1-src.zip"/> ```
192,028
<p>I am trying to use concat_ws inside a group_concat command. With a query, which simplified looks like: </p> <pre><code>SELECT item.title, GROUP_CONCAT( CONCAT_WS( ',', attachments.id, attachments.type, attachments.name ) ) as attachments FROM story AS item LEFT OUTER JOIN story_attachment AS attachments ON item.id = attachments.item_id GROUP BY item.id </code></pre> <p>I get the attachments column as a Blob type. is it it possible to get it as a string instead of Blob?</p>
[ { "answer_id": 192057, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 3, "selected": true, "text": "<p>You need to cast as a char..</p>\n\n<pre><code>SELECT item.title, GROUP_CONCAT( CAST(CONCAT_WS(',', attachments.id, \nattachments.type, attachments.name ) as CHAR ) ) as attachments \nFROM story AS item \nLEFT OUTER JOIN story_attachment AS attachments \nON item.id = attachments.item_id GROUP BY item.id\n</code></pre>\n" }, { "answer_id": 192068, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 0, "selected": false, "text": "<p>Although I suspect CAST is the appropriate answer, it's worth mentioning that I ran into a similar thing in the past which turned out to be down to a strange/conflicting collation type and character set.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192028", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
I am trying to use concat\_ws inside a group\_concat command. With a query, which simplified looks like: ``` SELECT item.title, GROUP_CONCAT( CONCAT_WS( ',', attachments.id, attachments.type, attachments.name ) ) as attachments FROM story AS item LEFT OUTER JOIN story_attachment AS attachments ON item.id = attachments.item_id GROUP BY item.id ``` I get the attachments column as a Blob type. is it it possible to get it as a string instead of Blob?
You need to cast as a char.. ``` SELECT item.title, GROUP_CONCAT( CAST(CONCAT_WS(',', attachments.id, attachments.type, attachments.name ) as CHAR ) ) as attachments FROM story AS item LEFT OUTER JOIN story_attachment AS attachments ON item.id = attachments.item_id GROUP BY item.id ```
192,048
<p>I understand that an id must be unique within an HTML/XHTML page.</p> <p>For a given element, can I assign multiple ids to it?</p> <pre><code>&lt;div id=&quot;nested_element_123 task_123&quot;&gt;&lt;/div&gt; </code></pre> <p>I realize I have an easy solution with simply using a class. I'm just curious about using ids in this manner.</p>
[ { "answer_id": 192058, "author": "Robert K", "author_id": 24950, "author_profile": "https://Stackoverflow.com/users/24950", "pm_score": 0, "selected": false, "text": "<p>That's interesting, but as far as I know the answer is a firm no. I don't see why you need a nested ID, since you'll usually cross it with another element that has the same nested ID. If you don't there's no point, if you do there's still very little point.</p>\n" }, { "answer_id": 192064, "author": "tpower", "author_id": 18107, "author_profile": "https://Stackoverflow.com/users/18107", "pm_score": 2, "selected": false, "text": "<p>No, you cannot have multiple ids for a single tag, but I have seen a tag with a <code>name</code> attribute and an <code>id</code> attribute which are treated the same by some applications.</p>\n" }, { "answer_id": 192066, "author": "timmow", "author_id": 16634, "author_profile": "https://Stackoverflow.com/users/16634", "pm_score": 9, "selected": true, "text": "<p>No. From the <a href=\"http://www.w3.org/TR/xhtml1/#h-4.10\" rel=\"noreferrer\">XHTML 1.0 Spec</a></p>\n\n<blockquote>\n <p>In XML, fragment identifiers are of\n type ID, and there can only be a\n single attribute of type ID per\n element. Therefore, in XHTML 1.0 the\n id attribute is defined to be of type\n ID. In order to ensure that XHTML 1.0\n documents are well-structured XML\n documents, XHTML 1.0 documents MUST\n use the id attribute when defining\n fragment identifiers on the elements\n listed above. See the HTML\n Compatibility Guidelines for\n information on ensuring such anchors\n are backward compatible when serving\n XHTML documents as media type\n text/html.</p>\n</blockquote>\n" }, { "answer_id": 192070, "author": "acrosman", "author_id": 24215, "author_profile": "https://Stackoverflow.com/users/24215", "pm_score": 5, "selected": false, "text": "<p><strong>No.</strong> While the <a href=\"http://www.w3.org/TR/REC-html40/struct/global.html#adef-id\" rel=\"nofollow noreferrer\">definition from W3C</a> for HTML 4 doesn't seem to explicitly cover your question, the <a href=\"http://www.w3.org/TR/REC-html40/types.html#type-name\" rel=\"nofollow noreferrer\">definition of the name and id attribute</a> says no spaces in the identifier:</p>\n<blockquote>\n<p>ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens (&quot;-&quot;), underscores (&quot;_&quot;), colons (&quot;:&quot;), and periods (&quot;.&quot;).</p>\n</blockquote>\n" }, { "answer_id": 192071, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 4, "selected": false, "text": "<p>No. Every DOM element, if it has an id, has a single, unique id. You could approximate it using something like:</p>\n\n<pre><code>&lt;div id='enclosing_id_123'&gt;&lt;span id='enclosed_id_123'&gt;&lt;/span&gt;&lt;/div&gt;\n</code></pre>\n\n<p>and then use navigation to get what you really want.</p>\n\n<p>If you are just looking to apply styles, class names are better.</p>\n" }, { "answer_id": 192081, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 5, "selected": false, "text": "<p>My understanding has always been:</p>\n<ul>\n<li><p>IDs are <strong>single use</strong> and are only applied to one element...</p>\n<ul>\n<li>Each is <strong>attributed as a</strong> <em><strong>unique identifier</strong></em> <strong>to (only) one single element</strong>.</li>\n</ul>\n</li>\n<li><p>Classes can be used <strong>more than once</strong>...</p>\n<ul>\n<li>They can therefore be applied to <strong>more than one element</strong>, and similarly yet different, there can be <strong>more than one class (i.e., multiple classes) per element</strong>.</li>\n</ul>\n</li>\n</ul>\n" }, { "answer_id": 192101, "author": "Anjisan", "author_id": 25304, "author_profile": "https://Stackoverflow.com/users/25304", "pm_score": 2, "selected": false, "text": "<p>No, you should use nested DIVs if you want to head down that path. Besides, even if you could, imagine the confusion it would cause when you run document.getElementByID(). What ID is it going to grab if there are multiple ones?</p>\n\n<p>On a slightly related topic, you can add multiple <em>classes</em> to a DIV. See Eric Myers discussion at,</p>\n\n<p><a href=\"http://meyerweb.com/eric/articles/webrev/199802a.html\" rel=\"nofollow noreferrer\">http://meyerweb.com/eric/articles/webrev/199802a.html</a> </p>\n" }, { "answer_id": 193311, "author": "AmbroseChapel", "author_id": 242241, "author_profile": "https://Stackoverflow.com/users/242241", "pm_score": 4, "selected": false, "text": "<p>You can only have one ID per element, but you can indeed have more than one class. But don't have multiple class attributes; put multiple class values into one attribute.</p>\n<pre><code>&lt;div id=&quot;foo&quot; class=&quot;bar baz bax&quot;&gt;\n</code></pre>\n<p>is perfectly legal.</p>\n" }, { "answer_id": 2674696, "author": "Taylor", "author_id": 275899, "author_profile": "https://Stackoverflow.com/users/275899", "pm_score": 1, "selected": false, "text": "<p>The simple answer is no, as others have said before me. An element can't have more than one ID and an ID can't be used more than once in a page. Try it out and you'll see how well it <em>doesn't</em> work.</p>\n<p>In response to <a href=\"https://stackoverflow.com/questions/192048/can-an-html-element-have-multiple-ids/192071#192071\">tvanfosson's answer</a> regarding the use of the same ID in two different elements. As far as I'm aware, an ID can only be used once in a page regardless of whether it's attached to a different tag.</p>\n<p>By definition, an element needing an ID should be unique, but if you need two ID's then it's not really unique and needs a class instead.</p>\n" }, { "answer_id": 3699734, "author": "Ole Reidar Johansen", "author_id": 446216, "author_profile": "https://Stackoverflow.com/users/446216", "pm_score": -1, "selected": false, "text": "<p>I don´t think you can have two Id´s but it should be possible. Using the same id twice is a different case... like two people using the same passport. However one person could have multiple passports... Came looking for this since I have a situation where a single employee can have several functions. Say \"sysadm\" and \"team coordinator\" having the id=\"sysadm teamcoordinator\" would let me reference them from other pages so that employees.html#sysadm and employees.html#teamcoordinator would lead to the same place... One day somebody else might take over the team coordinator function while the sysadm remains the sysadm... then I only have to change the ids on the employees.html page ... but like I said - it doesn´t work :(</p>\n" }, { "answer_id": 5685221, "author": "user123444555621", "author_id": 27862, "author_profile": "https://Stackoverflow.com/users/27862", "pm_score": 8, "selected": false, "text": "<p>Contrary to what everyone else said, the correct answer is <strong>YES</strong></p>\n\n<p>The <a href=\"http://www.w3.org/TR/selectors/#id-selectors\" rel=\"noreferrer\">Selectors spec</a> is very clear about this:</p>\n\n<blockquote>\n <p>If an element has multiple ID attributes, all of them must be treated as IDs for that element for the purposes of the ID selector.Such a situation could be reached using mixtures of xml:id, DOM3 Core, XML DTDs, and namespace-specific knowledge.</p>\n</blockquote>\n\n<hr>\n\n<p><strong>Edit</strong></p>\n\n<p>Just to clarify: Yes, an XHTML element can have multiple ids, e.g.</p>\n\n<pre><code>&lt;p id=\"foo\" xml:id=\"bar\"&gt;\n</code></pre>\n\n<p>but assigning multiple ids to the same <code>id</code> attribute using a space-separated list is not possible.</p>\n" }, { "answer_id": 10215524, "author": "James", "author_id": 1342195, "author_profile": "https://Stackoverflow.com/users/1342195", "pm_score": 2, "selected": false, "text": "<p>I'd like to say technically yes, since really what gets rendered is technically always browser-dependent. Most browsers try to keep to the specifications as best they can and as far as I know there is nothing in the CSS specifications against it. I'm only going to vouch for the actual HTML, CSS, and JavaScript code that gets sent to the browser before any other interpreter steps in.</p>\n<p>However, I also say no since every browser I typically test on doesn't actually let you.</p>\n<p>If you need to see for yourself, save the following as a .html file and open it up in the major browsers. In all browsers I tested on, the JavaScript function will not match to an element. However, remove either &quot;hunkojunk&quot; from the id tag and all works fine.</p>\n<h3>Sample Code</h3>\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;/head&gt;\n&lt;body&gt;\n &lt;p id=&quot;hunkojunk1 hunkojunk2&quot;&gt;&lt;/p&gt;\n\n &lt;script type=&quot;text/javascript&quot;&gt;\n document.getElementById('hunkojunk2').innerHTML = &quot;JUNK JUNK JUNK JUNK JUNK JUNK&quot;;\n &lt;/script&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 18210758, "author": "Alexandr", "author_id": 634281, "author_profile": "https://Stackoverflow.com/users/634281", "pm_score": 2, "selected": false, "text": "<p>From <em><a href=\"http://www.w3.org/TR/REC-html40/struct/global.html#h-7.5.2\" rel=\"nofollow noreferrer\">7.5.2 Element identifiers: the id and class attributes</a></em>:</p>\n<blockquote>\n<p>The id attribute assigns a <strong>unique</strong> identifier to an element (which may\nbe verified by an SGML parser).</p>\n</blockquote>\n<p>and</p>\n<blockquote>\n<p>ID and NAME tokens must begin with a letter ([A-Za-z]) and may be\nfollowed by any number of letters, digits ([0-9]), hyphens (&quot;-&quot;),\nunderscores (&quot;_&quot;), colons (&quot;:&quot;), and periods (&quot;.&quot;).</p>\n</blockquote>\n<p>So &quot;id&quot; must be unique and can't contain a space.</p>\n" }, { "answer_id": 22116772, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Classes are specially made for this, and\nhere is the code from which you can understand it:</p>\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n &lt;style type=&quot;text/css&quot;&gt;\n .personal{\n height:100px;\n width: 100px;\n\n }\n .fam{\n border: 2px solid #ccc;\n }\n .x{\n background-color:#ccc;\n }\n\n &lt;/style&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n &lt;div class=&quot;personal fam x&quot;&gt;&lt;/div&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 29868685, "author": "Snowcrash", "author_id": 343204, "author_profile": "https://Stackoverflow.com/users/343204", "pm_score": 1, "selected": false, "text": "<p>No.</p>\n<p>Having said that, there's nothing to stop you doing it. But you'll get inconsistent behaviour with the various browsers. Don't do it. One ID per element.</p>\n<p>If you want multiple assignations to an element use classes (separated by a space).</p>\n" }, { "answer_id": 47846045, "author": "corysimmons", "author_id": 175825, "author_profile": "https://Stackoverflow.com/users/175825", "pm_score": 1, "selected": false, "text": "<p>Nay.</p>\n<p>From <em><a href=\"https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute\" rel=\"nofollow noreferrer\">3.2.3.1 The id attribute</a></em>:</p>\n<blockquote>\n<p>The value must not contain any space characters.</p>\n</blockquote>\n<p><code>id=&quot;a b&quot;</code> &lt;-- find the space character in that <em><strong>VaLuE</strong></em>.</p>\n<p>That said, you <em>can</em> style multiple IDs. But if you're following the specification, the answer is no.</p>\n" }, { "answer_id": 53072798, "author": "Samdom For Peace", "author_id": 8313078, "author_profile": "https://Stackoverflow.com/users/8313078", "pm_score": 2, "selected": false, "text": "<p>Any ID assigned to a div element is unique.\nHowever, you can assign multiple IDs &quot;under&quot;, and not &quot;to&quot; a div element.\nIn that case, you have to represent those IDs as <code>&lt;span&gt;&lt;/span&gt;</code> IDs.</p>\n<p>Say, you want two links in the same HTML page to point to the same div element in the page.</p>\n<h3>The two different links</h3>\n<pre><code>&lt;p&gt;&lt;a href=&quot;#exponentialEquationsCalculator&quot;&gt;Exponential Equations&lt;/a&gt;&lt;/p&gt;\n\n&lt;p&gt;&lt;a href=&quot;#logarithmicExpressionsCalculator&quot;&gt;&lt;Logarithmic Expressions&lt;/a&gt;&lt;/p&gt;\n</code></pre>\n<h3>Point to the same section of the page</h3>\n<pre><code>&lt;!-- Exponential / Logarithmic Equations Calculator --&gt;\n&lt;div class=&quot;w3-container w3-card white w3-margin-bottom&quot;&gt;\n &lt;span id=&quot;exponentialEquationsCalculator&quot;&gt;&lt;/span&gt;\n &lt;span id=&quot;logarithmicEquationsCalculator&quot;&gt;&lt;/span&gt;\n&lt;/div&gt;\n</code></pre>\n" }, { "answer_id": 59948170, "author": "Agboola Feyikemi", "author_id": 12046299, "author_profile": "https://Stackoverflow.com/users/12046299", "pm_score": 0, "selected": false, "text": "<p>ID's should be unique, so you should only use a particular ID once on a page. Classes may be used repeatedly.</p>\n<p>Check <em><a href=\"https://www.w3schools.com/html/html_id.asp\" rel=\"nofollow noreferrer\">HTML id Attribute</a></em> (W3Schools) for more details.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6349/" ]
I understand that an id must be unique within an HTML/XHTML page. For a given element, can I assign multiple ids to it? ``` <div id="nested_element_123 task_123"></div> ``` I realize I have an easy solution with simply using a class. I'm just curious about using ids in this manner.
No. From the [XHTML 1.0 Spec](http://www.w3.org/TR/xhtml1/#h-4.10) > > In XML, fragment identifiers are of > type ID, and there can only be a > single attribute of type ID per > element. Therefore, in XHTML 1.0 the > id attribute is defined to be of type > ID. In order to ensure that XHTML 1.0 > documents are well-structured XML > documents, XHTML 1.0 documents MUST > use the id attribute when defining > fragment identifiers on the elements > listed above. See the HTML > Compatibility Guidelines for > information on ensuring such anchors > are backward compatible when serving > XHTML documents as media type > text/html. > > >
192,073
<p>What are the differences between pipes in Windows and Linux?</p>
[ { "answer_id": 192187, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 6, "selected": true, "text": "<p>One difference that I know of, is that named pipes under Linux are actual entries in the filesystem (you'll see it in a directory listing, they have a special type), whereas on Windows they are stored in some magical repository somewhere (they are all accessed via the path \"\\\\.\\pipe\\\".</p>\n\n<p>Secondly, in Linux you can just write/read from pipes as if they were any other file, using standard file IO methods. Whereas on windows, you have to use the special 'Pipe' functions which are part of the Win32 API.</p>\n\n<p>I like linux's method better, because it lets me use pipes with any app I want. Eg:</p>\n\n<pre><code>mkfifo pipe.wav\ndecodeMP3 song.mp3 --out pipe.wav &amp;\nencodeAVI video.mpeg pipe.wav --out video.avi\n</code></pre>\n\n<p>This lets me pipe the output of the MP3 decoder directly into the video decoder, instead of having to first decode the entire MP3 into a WAV file on disk. It's handy if you have a dual-core CPU, because then you are running both operations at once, for a nice speedup.</p>\n" }, { "answer_id": 192728, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "<p>Under Linux (and *ix in general), \"everything is a file\". You can read/write/seek pipes and sockets and devices with no restrictions, insofar as those operations make sense.</p>\n\n<p>Whereas Windows has a far less unified architecture for these different types of objects. Though I couldn't tell you the details, I know that buffering of pipes is considerably different between Windows and Linux, so you may run into difficulties there.</p>\n\n<p>Also, one common Unix-y use of pipes is to <code>fork()</code> a subprocess and then communicate with it via a pipe (the parent opens one end, the child opens the other end). Under Windows, that kind of thing just isn't possible. IPC mechanisms are quite different.</p>\n" }, { "answer_id": 192785, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 2, "selected": false, "text": "<p>See also the previous thread:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/175579/what-are-named-pipes#176140\">What are named pipes?</a></p>\n\n<p>Which contains my take and several other peoples'</p>\n" }, { "answer_id": 38512452, "author": "lkreinitz", "author_id": 1738787, "author_profile": "https://Stackoverflow.com/users/1738787", "pm_score": 3, "selected": false, "text": "<p>Another important difference</p>\n\n<p>Under windows</p>\n\n<pre><code>A | B | C \n</code></pre>\n\n<p>Until A is done with it's output B does not start reading, The same for B output being read by C</p>\n\n<p>*nix hooks the input and output together so that C can read B's output and B can read A's output while A and B are still running </p>\n\n<p>The throughput is about the same but output shows up faster with *nix.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
What are the differences between pipes in Windows and Linux?
One difference that I know of, is that named pipes under Linux are actual entries in the filesystem (you'll see it in a directory listing, they have a special type), whereas on Windows they are stored in some magical repository somewhere (they are all accessed via the path "\\.\pipe\". Secondly, in Linux you can just write/read from pipes as if they were any other file, using standard file IO methods. Whereas on windows, you have to use the special 'Pipe' functions which are part of the Win32 API. I like linux's method better, because it lets me use pipes with any app I want. Eg: ``` mkfifo pipe.wav decodeMP3 song.mp3 --out pipe.wav & encodeAVI video.mpeg pipe.wav --out video.avi ``` This lets me pipe the output of the MP3 decoder directly into the video decoder, instead of having to first decode the entire MP3 into a WAV file on disk. It's handy if you have a dual-core CPU, because then you are running both operations at once, for a nice speedup.
192,077
<p>I created a simple class with a DependencyProperty. When setting the value, I observe that ValidateValueCallback is called before CoerceValueCallback.</p> <p>On <a href="http://wpftutorial.net/How+does+a+DependencyProperty+resolve+its+value.htm" rel="nofollow noreferrer">wpftutorial</a> and in other books, it is stated that coercion is called before validation.</p>
[ { "answer_id": 192187, "author": "davr", "author_id": 14569, "author_profile": "https://Stackoverflow.com/users/14569", "pm_score": 6, "selected": true, "text": "<p>One difference that I know of, is that named pipes under Linux are actual entries in the filesystem (you'll see it in a directory listing, they have a special type), whereas on Windows they are stored in some magical repository somewhere (they are all accessed via the path \"\\\\.\\pipe\\\".</p>\n\n<p>Secondly, in Linux you can just write/read from pipes as if they were any other file, using standard file IO methods. Whereas on windows, you have to use the special 'Pipe' functions which are part of the Win32 API.</p>\n\n<p>I like linux's method better, because it lets me use pipes with any app I want. Eg:</p>\n\n<pre><code>mkfifo pipe.wav\ndecodeMP3 song.mp3 --out pipe.wav &amp;\nencodeAVI video.mpeg pipe.wav --out video.avi\n</code></pre>\n\n<p>This lets me pipe the output of the MP3 decoder directly into the video decoder, instead of having to first decode the entire MP3 into a WAV file on disk. It's handy if you have a dual-core CPU, because then you are running both operations at once, for a nice speedup.</p>\n" }, { "answer_id": 192728, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "<p>Under Linux (and *ix in general), \"everything is a file\". You can read/write/seek pipes and sockets and devices with no restrictions, insofar as those operations make sense.</p>\n\n<p>Whereas Windows has a far less unified architecture for these different types of objects. Though I couldn't tell you the details, I know that buffering of pipes is considerably different between Windows and Linux, so you may run into difficulties there.</p>\n\n<p>Also, one common Unix-y use of pipes is to <code>fork()</code> a subprocess and then communicate with it via a pipe (the parent opens one end, the child opens the other end). Under Windows, that kind of thing just isn't possible. IPC mechanisms are quite different.</p>\n" }, { "answer_id": 192785, "author": "MarkR", "author_id": 13724, "author_profile": "https://Stackoverflow.com/users/13724", "pm_score": 2, "selected": false, "text": "<p>See also the previous thread:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/175579/what-are-named-pipes#176140\">What are named pipes?</a></p>\n\n<p>Which contains my take and several other peoples'</p>\n" }, { "answer_id": 38512452, "author": "lkreinitz", "author_id": 1738787, "author_profile": "https://Stackoverflow.com/users/1738787", "pm_score": 3, "selected": false, "text": "<p>Another important difference</p>\n\n<p>Under windows</p>\n\n<pre><code>A | B | C \n</code></pre>\n\n<p>Until A is done with it's output B does not start reading, The same for B output being read by C</p>\n\n<p>*nix hooks the input and output together so that C can read B's output and B can read A's output while A and B are still running </p>\n\n<p>The throughput is about the same but output shows up faster with *nix.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1624/" ]
I created a simple class with a DependencyProperty. When setting the value, I observe that ValidateValueCallback is called before CoerceValueCallback. On [wpftutorial](http://wpftutorial.net/How+does+a+DependencyProperty+resolve+its+value.htm) and in other books, it is stated that coercion is called before validation.
One difference that I know of, is that named pipes under Linux are actual entries in the filesystem (you'll see it in a directory listing, they have a special type), whereas on Windows they are stored in some magical repository somewhere (they are all accessed via the path "\\.\pipe\". Secondly, in Linux you can just write/read from pipes as if they were any other file, using standard file IO methods. Whereas on windows, you have to use the special 'Pipe' functions which are part of the Win32 API. I like linux's method better, because it lets me use pipes with any app I want. Eg: ``` mkfifo pipe.wav decodeMP3 song.mp3 --out pipe.wav & encodeAVI video.mpeg pipe.wav --out video.avi ``` This lets me pipe the output of the MP3 decoder directly into the video decoder, instead of having to first decode the entire MP3 into a WAV file on disk. It's handy if you have a dual-core CPU, because then you are running both operations at once, for a nice speedup.
192,078
<p>Shouldn't this be a pretty straightforward operation? However, I see there's neither a <code>size()</code> nor <code>length()</code> method.</p>
[ { "answer_id": 192094, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 7, "selected": false, "text": "<pre><code>ResultSet rs = ps.executeQuery();\nint rowcount = 0;\nif (rs.last()) {\n rowcount = rs.getRow();\n rs.beforeFirst(); // not rs.first() because the rs.next() below will move on, missing the first element\n}\nwhile (rs.next()) {\n // do your standard per row stuff\n}\n</code></pre>\n" }, { "answer_id": 192104, "author": "finnw", "author_id": 12048, "author_profile": "https://Stackoverflow.com/users/12048", "pm_score": 9, "selected": true, "text": "<p>Do a <code>SELECT COUNT(*) FROM ...</code> query instead.</p>\n\n<p>OR</p>\n\n<pre><code>int size =0;\nif (rs != null) \n{\n rs.last(); // moves cursor to the last row\n size = rs.getRow(); // get row id \n}\n</code></pre>\n\n<p>In either of the case, you won't have to loop over the entire data.</p>\n" }, { "answer_id": 12658004, "author": "CounterSpell", "author_id": 1398114, "author_profile": "https://Stackoverflow.com/users/1398114", "pm_score": 2, "selected": false, "text": "<p>It is a simple way to do rows-count. </p>\n\n<pre><code>ResultSet rs = job.getSearchedResult(stmt);\nint rsCount = 0;\n\n//but notice that you'll only get correct ResultSet size after end of the while loop\nwhile(rs.next())\n{\n //do your other per row stuff \n rsCount = rsCount + 1;\n}//end while\n</code></pre>\n" }, { "answer_id": 13598630, "author": "Dan", "author_id": 941711, "author_profile": "https://Stackoverflow.com/users/941711", "pm_score": 4, "selected": false, "text": "<p>I got an exception when using <code>rs.last()</code></p>\n\n<pre><code>if(rs.last()){\n rowCount = rs.getRow(); \n rs.beforeFirst();\n}\n</code></pre>\n\n<p>:</p>\n\n<pre><code>java.sql.SQLException: Invalid operation for forward only resultset\n</code></pre>\n\n<p>it's due to by default it is <code>ResultSet.TYPE_FORWARD_ONLY</code>, which means you can only use <code>rs.next()</code></p>\n\n<p><strong><em>the solution is:</em></strong></p>\n\n<pre><code>stmt=conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,\n ResultSet.CONCUR_READ_ONLY); \n</code></pre>\n" }, { "answer_id": 15389446, "author": "Ben", "author_id": 2166111, "author_profile": "https://Stackoverflow.com/users/2166111", "pm_score": 1, "selected": false, "text": "<pre><code>theStatement=theConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);\n\nResultSet theResult=theStatement.executeQuery(query); \n\n//Get the size of the data returned\ntheResult.last(); \nint size = theResult.getRow() * theResult.getMetaData().getColumnCount(); \ntheResult.beforeFirst();\n</code></pre>\n" }, { "answer_id": 15919915, "author": "Unai Vivi", "author_id": 1018783, "author_profile": "https://Stackoverflow.com/users/1018783", "pm_score": 4, "selected": false, "text": "<p>Well, if you have a <code>ResultSet</code> of type <code>ResultSet.TYPE_FORWARD_ONLY</code> you want to keep it that way (and <strong>not</strong> to switch to a <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code> or <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code> in order to be able to use <code>.last()</code>).</p>\n\n<p>I suggest a very nice and efficient hack, where you add a first bogus/phony row at the top containing the number of rows.</p>\n\n<p><em>Example</em></p>\n\n<p>Let's say your query is the following</p>\n\n<pre><code>select MYBOOL,MYINT,MYCHAR,MYSMALLINT,MYVARCHAR\nfrom MYTABLE\nwhere ...blahblah...\n</code></pre>\n\n<p>and your output looks like</p>\n\n<pre><code>true 65537 \"Hey\" -32768 \"The quick brown fox\"\nfalse 123456 \"Sup\" 300 \"The lazy dog\"\nfalse -123123 \"Yo\" 0 \"Go ahead and jump\"\nfalse 3 \"EVH\" 456 \"Might as well jump\"\n...\n[1000 total rows]\n</code></pre>\n\n<p>Simply refactor your code to something like this:</p>\n\n<pre><code>Statement s=myConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY,\n ResultSet.CONCUR_READ_ONLY);\nString from_where=\"FROM myTable WHERE ...blahblah... \";\n//h4x\nResultSet rs=s.executeQuery(\"select count(*)as RECORDCOUNT,\"\n + \"cast(null as boolean)as MYBOOL,\"\n + \"cast(null as int)as MYINT,\"\n + \"cast(null as char(1))as MYCHAR,\"\n + \"cast(null as smallint)as MYSMALLINT,\"\n + \"cast(null as varchar(1))as MYVARCHAR \"\n +from_where\n +\"UNION ALL \"//the \"ALL\" part prevents internal re-sorting to prevent duplicates (and we do not want that)\n +\"select cast(null as int)as RECORDCOUNT,\"\n + \"MYBOOL,MYINT,MYCHAR,MYSMALLINT,MYVARCHAR \"\n +from_where);\n</code></pre>\n\n<p>Your query output will now be something like</p>\n\n<pre><code>1000 null null null null null\nnull true 65537 \"Hey\" -32768 \"The quick brown fox\"\nnull false 123456 \"Sup\" 300 \"The lazy dog\"\nnull false -123123 \"Yo\" 0 \"Go ahead and jump\"\nnull false 3 \"EVH\" 456 \"Might as well jump\"\n...\n[1001 total rows]\n</code></pre>\n\n<p>So you just have to</p>\n\n<pre><code>if(rs.next())\n System.out.println(\"Recordcount: \"+rs.getInt(\"RECORDCOUNT\"));//hack: first record contains the record count\nwhile(rs.next())\n //do your stuff\n</code></pre>\n" }, { "answer_id": 16885165, "author": "clausavram", "author_id": 1820666, "author_profile": "https://Stackoverflow.com/users/1820666", "pm_score": 1, "selected": false, "text": "<p>I checked the runtime value of the <strong>ResultSet</strong> interface and found out it was pretty much a <strong>ResultSetImpl</strong> all the time. ResultSetImpl has a method called <code>getUpdateCount()</code> which returns the value you are looking for.</p>\n\n<p><em>This code sample should suffice:</em><br>\n<code>ResultSet resultSet = executeQuery(sqlQuery);</code><br>\n<code>double rowCount = ((ResultSetImpl)resultSet).getUpdateCount()</code></p>\n\n<p>I realize that downcasting is generally an unsafe procedure but this method hasn't yet failed me.</p>\n" }, { "answer_id": 18457100, "author": "Peter.Chu", "author_id": 2720180, "author_profile": "https://Stackoverflow.com/users/2720180", "pm_score": 2, "selected": false, "text": "<pre class=\"lang-java prettyprint-override\"><code>String sql = \"select count(*) from message\";\nps = cn.prepareStatement(sql);\n\nrs = ps.executeQuery();\nint rowCount = 0;\nwhile(rs.next()) {\n rowCount = Integer.parseInt(rs.getString(\"count(*)\"));\n System.out.println(Integer.parseInt(rs.getString(\"count(*)\")));\n}\nSystem.out.println(\"Count : \" + rowCount);\n</code></pre>\n" }, { "answer_id": 23157858, "author": "bhaskar", "author_id": 3549459, "author_profile": "https://Stackoverflow.com/users/3549459", "pm_score": 4, "selected": false, "text": "<pre><code>int i = 0;\nwhile(rs.next()) {\n i++;\n}\n</code></pre>\n" }, { "answer_id": 25543677, "author": "Anptk", "author_id": 3876141, "author_profile": "https://Stackoverflow.com/users/3876141", "pm_score": 2, "selected": false, "text": "<p>The way of getting size of ResultSet, No need of using ArrayList etc</p>\n\n<pre><code>int size =0; \nif (rs != null) \n{ \nrs.beforeFirst(); \n rs.last(); \nsize = rs.getRow();\n}\n</code></pre>\n\n<p>Now You will get size, And if you want print the ResultSet, before printing use following line of code too,</p>\n\n<pre><code>rs.beforeFirst(); \n</code></pre>\n" }, { "answer_id": 26782970, "author": "Israel Hernández", "author_id": 4223435, "author_profile": "https://Stackoverflow.com/users/4223435", "pm_score": 0, "selected": false, "text": "<p>I was having the same problem. Using <code>ResultSet.first()</code> in this way just after the execution solved it:</p>\n\n<pre><code>if(rs.first()){\n // Do your job\n} else {\n // No rows take some actions\n}\n</code></pre>\n\n<p>Documentation (<a href=\"http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html#first()\" rel=\"nofollow\">link</a>):</p>\n\n<blockquote>\n<pre><code>boolean first()\n throws SQLException\n</code></pre>\n \n <p>Moves the cursor to the first row in this <code>ResultSet</code> object. </p>\n \n <p><strong>Returns:</strong> </p>\n \n <p><code>true</code> if the cursor is on a valid\n row; <code>false</code> if there are no rows in the result set </p>\n \n <p><strong>Throws:</strong> </p>\n \n <p><a href=\"http://docs.oracle.com/javase/7/docs/api/java/sql/SQLException.html\" rel=\"nofollow\"><code>SQLException</code></a> - if a database access error occurs; this method is called on a closed result set or the result set type is <code>TYPE_FORWARD_ONLY</code></p>\n \n <p><a href=\"http://docs.oracle.com/javase/7/docs/api/java/sql/SQLFeatureNotSupportedException.html\" rel=\"nofollow\"><code>SQLFeatureNotSupportedException</code></a> - if the JDBC driver does not support\n this method </p>\n \n <p><strong>Since:</strong></p>\n \n <p>1.2</p>\n</blockquote>\n" }, { "answer_id": 30384597, "author": "Vit Bernatik", "author_id": 1093607, "author_profile": "https://Stackoverflow.com/users/1093607", "pm_score": 3, "selected": false, "text": "<p>[Speed consideration]</p>\n\n<p>Lot of ppl here suggests <code>ResultSet.last()</code> but for that you would need to open connection as a <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code> which for Derby embedded database is up to 10 times <strong>SLOWER</strong> than <code>ResultSet.TYPE_FORWARD_ONLY</code>.</p>\n\n<p>According to my micro-tests for embedded Derby and H2 databases it is significantly faster to call <code>SELECT COUNT(*)</code> before your SELECT. </p>\n\n<p><a href=\"https://stackoverflow.com/questions/30359737/how-to-run-2-sql-selects-atomically-or-any-other-better-way-to-get-number-of\">Here is in more detail my code and my benchmarks</a></p>\n" }, { "answer_id": 47134143, "author": "parksangdonews", "author_id": 7773143, "author_profile": "https://Stackoverflow.com/users/7773143", "pm_score": 1, "selected": false, "text": "<p>Today, I used this logic why I don't know getting the count of RS.</p>\n\n<pre><code>int chkSize = 0;\nif (rs.next()) {\n do { ..... blah blah\n enter code here for each rs.\n chkSize++;\n } while (rs.next());\n} else {\n enter code here for rs size = 0 \n}\n// good luck to u.\n</code></pre>\n" }, { "answer_id": 50299498, "author": "ReMaX", "author_id": 3835403, "author_profile": "https://Stackoverflow.com/users/3835403", "pm_score": -1, "selected": false, "text": "<p>Give column a name..</p>\n\n<pre><code>String query = \"SELECT COUNT(*) as count FROM\n</code></pre>\n\n<p>Reference that column from the ResultSet object into an int and do your logic from there..</p>\n\n<pre><code>PreparedStatement statement = connection.prepareStatement(query);\nstatement.setString(1, item.getProductId());\nResultSet resultSet = statement.executeQuery();\nwhile (resultSet.next()) {\n int count = resultSet.getInt(\"count\");\n if (count &gt;= 1) {\n System.out.println(\"Product ID already exists.\");\n } else {\n System.out.println(\"New Product ID.\");\n }\n}\n</code></pre>\n" }, { "answer_id": 58162602, "author": "user7120462", "author_id": 7120462, "author_profile": "https://Stackoverflow.com/users/7120462", "pm_score": 0, "selected": false, "text": "<p>Easiest approach, Run Count(*) query, do resultSet.next() to point to the first row and then just do resultSet.getString(1) to get the count. Code :</p>\n\n<pre><code>ResultSet rs = statement.executeQuery(\"Select Count(*) from your_db\");\nif(rs.next()) {\n int count = rs.getString(1).toInt()\n}\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10675/" ]
Shouldn't this be a pretty straightforward operation? However, I see there's neither a `size()` nor `length()` method.
Do a `SELECT COUNT(*) FROM ...` query instead. OR ``` int size =0; if (rs != null) { rs.last(); // moves cursor to the last row size = rs.getRow(); // get row id } ``` In either of the case, you won't have to loop over the entire data.
192,083
<p>We have PHP 5.2.6 deployed to c:\php and in that folder there is the php.ini file. On Windows, can a website override these settings similar to the way that apache has .htaccess? e.g.</p> <pre><code>DirectoryIndex index.php index.html &lt;IfModule mod_php5.c&gt; php_flag magic_quotes_gpc off php_flag register_globals off &lt;/IfModule&gt; &lt;IfModule mod_php4.c&gt; php_flag magic_quotes_gpc off php_flag register_globals off &lt;/IfModule&gt; </code></pre> <p><strong><em>Update:</em></strong> </p> <p>I was aware of ini_set() but wondered if there was a declarative way to do this in a configuration file in the website rather than in script.</p>
[ { "answer_id": 192093, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 3, "selected": true, "text": "<p>I would recommend doing all you can to avoid changing r<code>egister_globals</code> to on as it's a major security hole.</p>\n\n<p>But you can try using <code>init_set()</code> to change the settings within your PHP code, although some settings cannot be changed once PHP has started running. (These are somewhat server dependent I believe.)</p>\n" }, { "answer_id": 192361, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://ie.php.net/ini_set\" rel=\"nofollow noreferrer\">ini_set</a> should do what you're after - </p>\n\n<pre><code>$option = 'magic_quotes_gpc';\necho \"Value of $option =&gt; \", ini_get($option);\nini_set($option,0);\necho \"New value of $option =&gt; \", ini_get($option);\n</code></pre>\n\n<p>A caveat here is that just because you can set the value at run-time doesn't mean it will work as expected, e.g. setting <code>register_globals</code> at runtime will be of little use as that setting has already done it's job by the time your script starts.</p>\n" }, { "answer_id": 192425, "author": "flamingLogos", "author_id": 8161, "author_profile": "https://Stackoverflow.com/users/8161", "pm_score": 2, "selected": false, "text": "<p>You can override the directives in the php.ini file several ways, but not all directives can be changed by each method. See the <a href=\"http://www.php.net/manual/en/ini.php\" rel=\"nofollow noreferrer\">php.ini directives</a> page in the manual for a list of the directives and the methods that will work on each one.</p>\n\n<p>The last column in the table lists the methods that will work on that particular method. In increasing level of access:</p>\n\n<ul>\n<li><code>PHP_INI_USER</code> - Can be set in user\nscripts with <code>ini_set()</code> (or any higher method)</li>\n<li><code>PHP_INI_PERDIR</code> - Can be set using\nthe .htacess file with <code>php_value</code>\nfor string values or <code>php_flag</code> for\nbinary values (or any higher method)</li>\n<li><code>PHP_INI_SYSTEM</code> - Can\nbe set using php.ini or httpd.conf\nonly (both require access to the server's configuration files)</li>\n<li><code>PHP_INI_ALL</code> - Can be set using\nany of the above methods</li>\n</ul>\n" }, { "answer_id": 197129, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 0, "selected": false, "text": "<p>For cgi environments, there is a module called <a href=\"http://pecl.php.net/package/htscanner\" rel=\"nofollow noreferrer\">htscanner</a>. It basically fakes .htaccess behavior and allows per directory configurations. Unfortunately I have no experience with this on Windows, let alone with IIS6.</p>\n" }, { "answer_id": 259996, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>From <a href=\"http://us.php.net/configuration.changes\" rel=\"nofollow noreferrer\">http://us.php.net/configuration.changes</a>:</p>\n\n<p><strong>Changing PHP configuration via the Windows registry</strong></p>\n\n<p>When running PHP on Windows, the configuration values can be modified on a per-directory basis using the Windows registry. The configuration values are stored in the registry key HKLM\\SOFTWARE\\PHP\\Per Directory Values, in the sub-keys corresponding to the path names. For example, configuration values for the directory c:\\inetpub\\wwwroot would be stored in the key HKLM\\SOFTWARE\\PHP\\Per Directory Values\\c\\inetpub\\wwwroot. The settings for the directory would be active for any script running from this directory or any subdirectory of it. The values under the key should have the name of the PHP configuration directive and the string value. PHP constants in the values are not parsed. However, only configuration values changeable in PHP_INI_USER can be set this way, PHP_INI_PERDIR values can not.</p>\n\n<p>...Haven't actually tried this yet, so your mileage may vary.</p>\n" }, { "answer_id": 1037622, "author": "r_honey", "author_id": 172396, "author_profile": "https://Stackoverflow.com/users/172396", "pm_score": 1, "selected": false, "text": "<p>I just found a new way of doing this.\nFirst of all, I used phpinfo() to find the PHP.ini being used by my Hosting provider.</p>\n\n<p>Thereafter, I uploaded a file containing the following code to my Hosting space:</p>\n\n<pre><code> $fsrc = fopen($pathToIni,'r');\n $fdest = fopen($myHostingDir,'w+');\n $len = stream_copy_to_stream($fsrc,$fdest);\n fclose($fsrc);\n fclose($fdest);\n echo $len;\n</code></pre>\n\n<p>This effectively copied the php.ini to my Hosting space. Thereafter, I downloaded that php.ini, changed the register_globals to off (for which I did all this), and uploaded it to the root of my Hosting space. Bingo, there you go.</p>\n\n<p>I have relied on the fact that IIS uses the complete php.ini if available in a directory. You cannot override only specific settings like that using .htaccess on Apache.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/419/" ]
We have PHP 5.2.6 deployed to c:\php and in that folder there is the php.ini file. On Windows, can a website override these settings similar to the way that apache has .htaccess? e.g. ``` DirectoryIndex index.php index.html <IfModule mod_php5.c> php_flag magic_quotes_gpc off php_flag register_globals off </IfModule> <IfModule mod_php4.c> php_flag magic_quotes_gpc off php_flag register_globals off </IfModule> ``` ***Update:*** I was aware of ini\_set() but wondered if there was a declarative way to do this in a configuration file in the website rather than in script.
I would recommend doing all you can to avoid changing r`egister_globals` to on as it's a major security hole. But you can try using `init_set()` to change the settings within your PHP code, although some settings cannot be changed once PHP has started running. (These are somewhat server dependent I believe.)
192,085
<p>I am writing a diagnostic page for SiteScope and one area we need to test is if the connection to the file/media assets are accesible from the web server. One way I think I can do this is load the image via code behind and test to see if the IIS status message is 200. </p> <p>So basically I should be able to navigate to within the site to a folder like this: /media/1/image.jpg and see if it returns 200...if not throw exception.</p> <p>I am struggling to figure out how to write this code.</p> <p>Any help is greatly appreciated.</p> <p>Thanks</p>
[ { "answer_id": 192141, "author": "Greg Dean", "author_id": 1200558, "author_profile": "https://Stackoverflow.com/users/1200558", "pm_score": 7, "selected": true, "text": "<p>Just use HEAD. No need to download the entire image if you don't need it. Here some boilerplate code.</p>\n\n<pre><code>HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(\"url\");\nrequest.Method = \"HEAD\";\n\nbool exists;\ntry\n{\n request.GetResponse();\n exists = true;\n}\ncatch\n{\n exists = false;\n}\n</code></pre>\n" }, { "answer_id": 192158, "author": "user25519", "author_id": 25519, "author_profile": "https://Stackoverflow.com/users/25519", "pm_score": -1, "selected": false, "text": "<p>I'd look into an HttpWebRequest instead - I think the previous answer will actually download data, whereas you should be able to get the response without data from HttpWebRequest.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/456dfw4f.aspx\" rel=\"nofollow noreferrer\"><a href=\"http://msdn.microsoft.com/en-us/library/456dfw4f.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/456dfw4f.aspx</a></a> until step #4 should do the trick. There are other fields on HttpWebResponse for getting the numerical code if needs be...</p>\n\n<p>hth\nJack</p>\n" }, { "answer_id": 192161, "author": "beno", "author_id": 649, "author_profile": "https://Stackoverflow.com/users/649", "pm_score": 3, "selected": false, "text": "<p>I've used something like this before, but there's probably a better way:</p>\n\n<pre><code>try\n{\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(\"http://somewhere/picture.jpg\");\n request.Credentials = System.Net.CredentialCache.DefaultCredentials;\n HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n myImg.ImageUrl = \"http://somewhere/picture.jpg\";\n}\ncatch (Exception ex)\n{\n // image doesn't exist, set to default picture\n myImg.ImageUrl = \"http://somewhere/default.jpg\";\n}\n</code></pre>\n" }, { "answer_id": 192667, "author": "Anjisan", "author_id": 25304, "author_profile": "https://Stackoverflow.com/users/25304", "pm_score": 5, "selected": false, "text": "<p>You might want to also check that you got an OK status code (ie HTTP 200) and that the mime type from the response object matches what you're expecting. You could extend that along the lines of,</p>\n\n<pre><code>public bool doesImageExistRemotely(string uriToImage, string mimeType)\n{\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriToImage);\n request.Method = \"HEAD\";\n\n try\n {\n HttpWebResponse response = (HttpWebResponse)request.GetResponse();\n\n if (response.StatusCode == HttpStatusCode.OK &amp;&amp; response.ContentType == mimeType)\n {\n return true;\n }\n else\n {\n return false;\n } \n }\n catch\n {\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 236312, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>You have to dispose of the HTTPWebResponse object, otherwise you will have issues as I have had...</p>\n\n<pre><code> public bool DoesImageExistRemotely(string uriToImage)\n {\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriToImage);\n\n request.Method = \"HEAD\";\n\n try\n {\n using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n {\n\n if (response.StatusCode == HttpStatusCode.OK)\n {\n return true;\n }\n else\n {\n return false;\n }\n }\n }\n catch (WebException) { return false; }\n catch\n {\n return false;\n }\n }\n</code></pre>\n" }, { "answer_id": 7978922, "author": "jhamm", "author_id": 103927, "author_profile": "https://Stackoverflow.com/users/103927", "pm_score": 1, "selected": false, "text": "<p>If you are getting an exception during the request like \"The remote server returned an error: (401) Unauthorized.\",</p>\n\n<p>This can be resolved by adding the following line</p>\n\n<pre><code>request.Credentials = new NetworkCredential(username, password);\n</code></pre>\n\n<p>Question and answer added to this questions from <a href=\"https://stackoverflow.com/questions/7978318/check-if-image-exists-on-intranet\">check if image exists on intranet</a>.</p>\n" }, { "answer_id": 19228306, "author": "Paulos02", "author_id": 1625208, "author_profile": "https://Stackoverflow.com/users/1625208", "pm_score": 1, "selected": false, "text": "<p>If url exists like http:\\server.myImageSite.com the answer is false too\nonly if imageSize > 0 is true.</p>\n\n<pre><code> public static void GetPictureSize(string url, ref float width, ref float height, ref string err)\n {\n System.Net.HttpWebRequest wreq;\n System.Net.HttpWebResponse wresp;\n System.IO.Stream mystream;\n System.Drawing.Bitmap bmp;\n\n bmp = null;\n mystream = null;\n wresp = null;\n try\n {\n wreq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);\n wreq.AllowWriteStreamBuffering = true;\n\n wresp = (HttpWebResponse)wreq.GetResponse();\n\n if ((mystream = wresp.GetResponseStream()) != null)\n bmp = new System.Drawing.Bitmap(mystream);\n }\n catch (Exception er)\n {\n err = er.Message;\n return;\n }\n finally\n {\n if (mystream != null)\n mystream.Close();\n\n if (wresp != null)\n wresp.Close();\n }\n width = bmp.Width;\n height = bmp.Height;\n}\n\npublic static bool ImageUrlExists(string url)\n{\n\n float width = 0;\n float height = 0;\n string err = null;\n GetPictureSize(url, ref width, ref height, ref err);\n return width &gt; 0;\n}\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/648/" ]
I am writing a diagnostic page for SiteScope and one area we need to test is if the connection to the file/media assets are accesible from the web server. One way I think I can do this is load the image via code behind and test to see if the IIS status message is 200. So basically I should be able to navigate to within the site to a folder like this: /media/1/image.jpg and see if it returns 200...if not throw exception. I am struggling to figure out how to write this code. Any help is greatly appreciated. Thanks
Just use HEAD. No need to download the entire image if you don't need it. Here some boilerplate code. ``` HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("url"); request.Method = "HEAD"; bool exists; try { request.GetResponse(); exists = true; } catch { exists = false; } ```
192,092
<p>When calling php via cli, the current directory is NOT changed to the one of the script. All the scripts i have running in crontab run via the CLI, so this is an issue.</p> <p>I'm currently <em>fixing</em> the problem by doing a chdir() with the absolute path where the script is, but i REALLY dont like hardcoding paths into stuff like that.</p> <p>I'm looking for the most portable/reliable method for ensuring that the current working directory is the one where the script it is at.</p>
[ { "answer_id": 192112, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 2, "selected": false, "text": "<p>You can use <code>__FILE__</code> to get the full absolute path to the executing file itself:</p>\n\n<pre><code>&lt;?php\necho \"I'm here: \".__FILE__.\"\\n\";\n?&gt;\n</code></pre>\n\n<p>See <a href=\"http://fi.php.net/language.constants.predefined\" rel=\"nofollow noreferrer\">the documentation</a> for more info.</p>\n" }, { "answer_id": 192145, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 6, "selected": true, "text": "<pre><code>chdir(dirname(__FILE__));\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/314/" ]
When calling php via cli, the current directory is NOT changed to the one of the script. All the scripts i have running in crontab run via the CLI, so this is an issue. I'm currently *fixing* the problem by doing a chdir() with the absolute path where the script is, but i REALLY dont like hardcoding paths into stuff like that. I'm looking for the most portable/reliable method for ensuring that the current working directory is the one where the script it is at.
``` chdir(dirname(__FILE__)); ```
192,109
<p>So what I'm looking for here is something like PHP's <a href="http://us2.php.net/print_r" rel="noreferrer">print_r</a> function.</p> <p>This is so I can debug my scripts by seeing what's the state of the object in question.</p>
[ { "answer_id": 192116, "author": "Joe Skora", "author_id": 14057, "author_profile": "https://Stackoverflow.com/users/14057", "pm_score": 5, "selected": false, "text": "<p>You can use the \"dir()\" function to do this.</p>\n\n<pre><code>&gt;&gt;&gt; import sys\n&gt;&gt;&gt; dir(sys)\n['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdo\nt__', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder\n, 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dllhandle', 'exc_clear', 'exc_info'\n 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getcheckinterval', 'getdefault\nncoding', 'getfilesystemencoding', 'getrecursionlimit', 'getrefcount', 'getwindowsversion', 'he\nversion', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_\nache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setprofile', 'setrecursionlimit\n, 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoption\n', 'winver']\n&gt;&gt;&gt;\n</code></pre>\n\n<p>Another useful feature is help.</p>\n\n<pre><code>&gt;&gt;&gt; help(sys)\nHelp on built-in module sys:\n\nNAME\n sys\n\nFILE\n (built-in)\n\nMODULE DOCS\n http://www.python.org/doc/current/lib/module-sys.html\n\nDESCRIPTION\n This module provides access to some objects used or maintained by the\n interpreter and to functions that interact strongly with the interpreter.\n\n Dynamic objects:\n\n argv -- command line arguments; argv[0] is the script pathname if known\n</code></pre>\n" }, { "answer_id": 192184, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 8, "selected": false, "text": "<pre><code>def dump(obj):\n for attr in dir(obj):\n print(\"obj.%s = %r\" % (attr, getattr(obj, attr)))\n</code></pre>\n\n<p>There are many 3rd-party functions out there that add things like exception handling, national/special character printing, recursing into nested objects etc. according to their authors' preferences. But they all basically boil down to this.</p>\n" }, { "answer_id": 192207, "author": "eduffy", "author_id": 7536, "author_profile": "https://Stackoverflow.com/users/7536", "pm_score": 7, "selected": false, "text": "<p><code>dir</code> has been mentioned, but that'll only give you the attributes' names. If you want their values as well, try <code>__dict__</code>.</p>\n<pre><code>class O:\n def __init__ (self):\n self.value = 3\n\no = O()\n</code></pre>\n<p>Here is the output:</p>\n<pre><code>&gt;&gt;&gt; o.__dict__\n\n{'value': 3}\n</code></pre>\n" }, { "answer_id": 192365, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 11, "selected": true, "text": "<p>You are really mixing together two different things.</p>\n\n<p>Use <a href=\"https://docs.python.org/3/library/functions.html#dir\" rel=\"noreferrer\"><code>dir()</code></a>, <a href=\"https://docs.python.org/3/library/functions.html#vars\" rel=\"noreferrer\"><code>vars()</code></a> or the <a href=\"https://docs.python.org/3/library/inspect.html\" rel=\"noreferrer\"><code>inspect</code></a> module to get what you are interested in (I use <code>__builtins__</code> as an example; you can use any object instead).</p>\n\n<pre><code>&gt;&gt;&gt; l = dir(__builtins__)\n&gt;&gt;&gt; d = __builtins__.__dict__\n</code></pre>\n\n<p>Print that dictionary however fancy you like:</p>\n\n<pre><code>&gt;&gt;&gt; print l\n['ArithmeticError', 'AssertionError', 'AttributeError',...\n</code></pre>\n\n<p>or</p>\n\n<pre><code>&gt;&gt;&gt; from pprint import pprint\n&gt;&gt;&gt; pprint(l)\n['ArithmeticError',\n 'AssertionError',\n 'AttributeError',\n 'BaseException',\n 'DeprecationWarning',\n...\n\n&gt;&gt;&gt; pprint(d, indent=2)\n{ 'ArithmeticError': &lt;type 'exceptions.ArithmeticError'&gt;,\n 'AssertionError': &lt;type 'exceptions.AssertionError'&gt;,\n 'AttributeError': &lt;type 'exceptions.AttributeError'&gt;,\n...\n '_': [ 'ArithmeticError',\n 'AssertionError',\n 'AttributeError',\n 'BaseException',\n 'DeprecationWarning',\n...\n</code></pre>\n\n<p>Pretty printing is also available in the interactive debugger as a command:</p>\n\n<pre><code>(Pdb) pp vars()\n{'__builtins__': {'ArithmeticError': &lt;type 'exceptions.ArithmeticError'&gt;,\n 'AssertionError': &lt;type 'exceptions.AssertionError'&gt;,\n 'AttributeError': &lt;type 'exceptions.AttributeError'&gt;,\n 'BaseException': &lt;type 'exceptions.BaseException'&gt;,\n 'BufferError': &lt;type 'exceptions.BufferError'&gt;,\n ...\n 'zip': &lt;built-in function zip&gt;},\n '__file__': 'pass.py',\n '__name__': '__main__'}\n</code></pre>\n" }, { "answer_id": 193539, "author": "Jeremy Cantrell", "author_id": 18866, "author_profile": "https://Stackoverflow.com/users/18866", "pm_score": 10, "selected": false, "text": "<p>You want <code>vars()</code> mixed with <code>pprint()</code>:</p>\n\n<pre><code>from pprint import pprint\npprint(vars(your_object))\n</code></pre>\n" }, { "answer_id": 193808, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 5, "selected": false, "text": "<p>To print the current state of the object you might: </p>\n\n<pre><code>&gt;&gt;&gt; obj # in an interpreter\n</code></pre>\n\n<p>or </p>\n\n<pre><code>print repr(obj) # in a script\n</code></pre>\n\n<p>or</p>\n\n<pre><code>print obj\n</code></pre>\n\n<p>For your classes define <code>__str__</code> or <code>__repr__</code> methods. From the <a href=\"http://www.python.org/doc/2.5.2/ref/customization.html\" rel=\"noreferrer\">Python documentation</a>:</p>\n\n<blockquote>\n <p><code>__repr__(self)</code> Called by the <code>repr()</code> built-in function and by string\n conversions (reverse quotes) to\n compute the \"official\" string\n representation of an object. If at all\n possible, this should look like a\n valid Python expression that could be\n used to recreate an object with the\n same value (given an appropriate\n environment). If this is not possible,\n a string of the form \"&lt;...some useful\n description...>\" should be returned.\n The return value must be a string\n object. If a class defines <strong>repr</strong>()\n but not <code>__str__()</code>, then <code>__repr__()</code> is\n also used when an \"informal\" string\n representation of instances of that\n class is required. This is typically\n used for debugging, so it is important\n that the representation is\n information-rich and unambiguous.</p>\n \n <p><code>__str__(self)</code> Called by the <code>str()</code> built-in function and by the print\n statement to compute the \"informal\"\n string representation of an object.\n This differs from <code>__repr__()</code> in that\n it does not have to be a valid Python\n expression: a more convenient or\n concise representation may be used\n instead. The return value must be a\n string object.</p>\n</blockquote>\n" }, { "answer_id": 193827, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 3, "selected": false, "text": "<p>A metaprogramming example <a href=\"http://www.ibm.com/developerworks/linux/library/l-pymeta.html\" rel=\"noreferrer\">Dump object with magic</a>:</p>\n\n<pre>\n$ cat dump.py\n</pre>\n\n<pre><code>#!/usr/bin/python\nimport sys\nif len(sys.argv) &gt; 2:\n module, metaklass = sys.argv[1:3]\n m = __import__(module, globals(), locals(), [metaklass])\n __metaclass__ = getattr(m, metaklass)\n\nclass Data:\n def __init__(self):\n self.num = 38\n self.lst = ['a','b','c']\n self.str = 'spam'\n dumps = lambda self: repr(self)\n __str__ = lambda self: self.dumps()\n\ndata = Data()\nprint data\n</code></pre>\n\n<p>Without arguments:</p>\n\n<pre>\n$ python dump.py\n</pre>\n\n<pre><code>&lt;__main__.Data instance at 0x00A052D8&gt;\n</code></pre>\n\n<p>With <a href=\"http://www.gnosis.cx/download/Gnosis_Utils.More/\" rel=\"noreferrer\">Gnosis Utils</a>:</p>\n\n<pre>\n$ python dump.py gnosis.magic MetaXMLPickler\n</pre> \n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;!DOCTYPE PyObject SYSTEM \"PyObjects.dtd\"&gt;\n&lt;PyObject module=\"__main__\" class=\"Data\" id=\"11038416\"&gt;\n&lt;attr name=\"lst\" type=\"list\" id=\"11196136\" &gt;\n &lt;item type=\"string\" value=\"a\" /&gt;\n &lt;item type=\"string\" value=\"b\" /&gt;\n &lt;item type=\"string\" value=\"c\" /&gt;\n&lt;/attr&gt;\n&lt;attr name=\"num\" type=\"numeric\" value=\"38\" /&gt;\n&lt;attr name=\"str\" type=\"string\" value=\"spam\" /&gt;\n&lt;/PyObject&gt;\n</code></pre>\n\n<p>It is a bit outdated but still working.</p>\n" }, { "answer_id": 205037, "author": "William McVey", "author_id": 27642, "author_profile": "https://Stackoverflow.com/users/27642", "pm_score": 4, "selected": false, "text": "<p>In most cases, using <code>__dict__</code> or <code>dir()</code> will get you the info you're wanting. If you should happen to need more details, the standard library includes the <a href=\"https://docs.python.org/2/library/inspect.html\" rel=\"noreferrer\">inspect</a> module, which allows you to get some impressive amount of detail. Some of the real nuggests of info include:</p>\n\n<ul>\n<li>names of function and method parameters</li>\n<li>class hierarchies</li>\n<li>source code of the implementation of a functions/class objects</li>\n<li>local variables out of a frame object</li>\n</ul>\n\n<p>If you're just looking for \"what attribute values does my object have?\", then <code>dir()</code> and <code>__dict__</code> are probably sufficient. If you're really looking to dig into the current state of arbitrary objects (keeping in mind that in python almost everything is an object), then <code>inspect</code> is worthy of consideration.</p>\n" }, { "answer_id": 3697940, "author": "shahjapan", "author_id": 144408, "author_profile": "https://Stackoverflow.com/users/144408", "pm_score": 2, "selected": false, "text": "<p><a href=\"https://pymotw.com/3/pprint/index.html\" rel=\"nofollow noreferrer\">pprint</a> contains a “pretty printer” for producing aesthetically pleasing representations of your data structures. The formatter produces representations of data structures that can be parsed correctly by the interpreter, and are also easy for a human to read. The output is kept on a single line, if possible, and indented when split across multiple lines.</p>\n" }, { "answer_id": 13391460, "author": "Tel", "author_id": 1825630, "author_profile": "https://Stackoverflow.com/users/1825630", "pm_score": 4, "selected": false, "text": "<p>Might be worth checking out --</p>\n\n<p><a href=\"https://stackoverflow.com/questions/2540567/is-there-a-python-equivalent-to-perls-datadumper\">Is there a Python equivalent to Perl&#39;s Data::Dumper?</a></p>\n\n<p>My recommendation is this --</p>\n\n<p><a href=\"https://gist.github.com/1071857\" rel=\"noreferrer\">https://gist.github.com/1071857</a></p>\n\n<p>Note that perl has a module called Data::Dumper which translates object data back to perl source code (NB: it does NOT translate code back to source, and almost always you don't want to the object method functions in the output). This can be used for persistence, but the common purpose is for debugging.</p>\n\n<p>There are a number of things standard python pprint fails to achieve, in particular it just stops descending when it sees an instance of an object and gives you the internal hex pointer of the object (errr, that pointer is not a whole lot of use by the way). So in a nutshell, python is all about this great object oriented paradigm, but the tools you get out of the box are designed for working with something other than objects.</p>\n\n<p>The perl Data::Dumper allows you to control how deep you want to go, and also detects circular linked structures (that's really important). This process is fundamentally easier to achieve in perl because objects have no particular magic beyond their blessing (a universally well defined process).</p>\n" }, { "answer_id": 17105170, "author": "Michael Thamm", "author_id": 1964121, "author_profile": "https://Stackoverflow.com/users/1964121", "pm_score": 2, "selected": false, "text": "<p>Why not something simple:</p>\n\n<pre><code>for key,value in obj.__dict__.iteritems():\n print key,value\n</code></pre>\n" }, { "answer_id": 17372369, "author": "DaOneTwo", "author_id": 2063339, "author_profile": "https://Stackoverflow.com/users/2063339", "pm_score": 2, "selected": false, "text": "<p>I was needing to print DEBUG info in some logs and was unable to use pprint because it would break it. Instead I did this and got virtually the same thing.</p>\n\n<pre><code>DO = DemoObject()\n\nitemDir = DO.__dict__\n\nfor i in itemDir:\n print '{0} : {1}'.format(i, itemDir[i])\n</code></pre>\n" }, { "answer_id": 24435471, "author": "Clark", "author_id": 264391, "author_profile": "https://Stackoverflow.com/users/264391", "pm_score": 2, "selected": false, "text": "<p>To dump \"myObject\":</p>\n\n<pre><code>from bson import json_util\nimport json\n\nprint(json.dumps(myObject, default=json_util.default, sort_keys=True, indent=4, separators=(',', ': ')))\n</code></pre>\n\n<p>I tried vars() and dir(); both failed for what I was looking for. vars() didn't work because the object didn't have __dict__ (exceptions.TypeError: vars() argument must have __dict__ attribute). dir() wasn't what I was looking for: it's just a listing of field names, doesn't give the values or the object structure.</p>\n\n<p>I think json.dumps() would work for most objects without the default=json_util.default, but I had a datetime field in the object so the standard json serializer failed. See <a href=\"https://stackoverflow.com/questions/11875770/how-to-overcome-datetime-datetime-not-json-serializable-in-python\">How to overcome &quot;datetime.datetime not JSON serializable&quot; in python?</a></p>\n" }, { "answer_id": 24739571, "author": "32ndghost", "author_id": 3837425, "author_profile": "https://Stackoverflow.com/users/3837425", "pm_score": 3, "selected": false, "text": "<pre><code>from pprint import pprint\n\ndef print_r(the_object):\n print (\"CLASS: \", the_object.__class__.__name__, \" (BASE CLASS: \", the_object.__class__.__bases__,\")\")\n pprint(vars(the_object))\n</code></pre>\n" }, { "answer_id": 27094448, "author": "Adam Cath", "author_id": 1026601, "author_profile": "https://Stackoverflow.com/users/1026601", "pm_score": 4, "selected": false, "text": "<p>If you're using this for debugging, and you just want a recursive dump of everything, the accepted answer is unsatisfying because it requires that your classes have good <code>__str__</code> implementations already. If that's not the case, this works much better:</p>\n\n<pre><code>import json\nprint(json.dumps(YOUR_OBJECT, \n default=lambda obj: vars(obj),\n indent=1))\n</code></pre>\n" }, { "answer_id": 35804583, "author": "wisbucky", "author_id": 1081043, "author_profile": "https://Stackoverflow.com/users/1081043", "pm_score": 3, "selected": false, "text": "<p>This prints out all the object contents recursively in json or yaml indented format:</p>\n\n<pre><code>import jsonpickle # pip install jsonpickle\nimport json\nimport yaml # pip install pyyaml\n\nserialized = jsonpickle.encode(obj, max_depth=2) # max_depth is optional\nprint json.dumps(json.loads(serialized), indent=4)\nprint yaml.dump(yaml.load(serialized), indent=4)\n</code></pre>\n" }, { "answer_id": 35849201, "author": "Slipstream", "author_id": 1866389, "author_profile": "https://Stackoverflow.com/users/1866389", "pm_score": 0, "selected": false, "text": "<p>You can try the Flask Debug Toolbar.<br>\n<a href=\"https://pypi.python.org/pypi/Flask-DebugToolbar\" rel=\"nofollow\">https://pypi.python.org/pypi/Flask-DebugToolbar</a></p>\n\n<pre><code>from flask import Flask\nfrom flask_debugtoolbar import DebugToolbarExtension\n\napp = Flask(__name__)\n\n# the toolbar is only enabled in debug mode:\napp.debug = True\n\n# set a 'SECRET_KEY' to enable the Flask session cookies\napp.config['SECRET_KEY'] = '&lt;replace with a secret key&gt;'\n\ntoolbar = DebugToolbarExtension(app)\n</code></pre>\n" }, { "answer_id": 38629453, "author": "Symon", "author_id": 3973163, "author_profile": "https://Stackoverflow.com/users/3973163", "pm_score": 3, "selected": false, "text": "<p>Try <a href=\"https://github.com/symonsoft/ppretty\" rel=\"noreferrer\">ppretty</a></p>\n\n<pre><code>from ppretty import ppretty\n\n\nclass A(object):\n s = 5\n\n def __init__(self):\n self._p = 8\n\n @property\n def foo(self):\n return range(10)\n\n\nprint ppretty(A(), show_protected=True, show_static=True, show_properties=True)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>__main__.A(_p = 8, foo = [0, 1, ..., 8, 9], s = 5)\n</code></pre>\n" }, { "answer_id": 39535966, "author": "Anyany Pan", "author_id": 4683349, "author_profile": "https://Stackoverflow.com/users/4683349", "pm_score": 2, "selected": false, "text": "<p>Just try <a href=\"https://github.com/panyanyany/beeprint\" rel=\"nofollow noreferrer\">beeprint</a>.</p>\n\n<p>It will help you not only with printing object variables, but beautiful output as well, like this:</p>\n\n<pre><code>class(NormalClassNewStyle):\n dicts: {\n },\n lists: [],\n static_props: 1,\n tupl: (1, 2)\n</code></pre>\n" }, { "answer_id": 43783454, "author": "Evhz", "author_id": 5476782, "author_profile": "https://Stackoverflow.com/users/5476782", "pm_score": -1, "selected": false, "text": "<p>I like working with python object built-in types <a href=\"https://docs.python.org/2/library/stdtypes.html?highlight=keys#dict.keys\" rel=\"nofollow noreferrer\">keys</a> or <a href=\"https://docs.python.org/2/library/stdtypes.html?highlight=keys#dict.values\" rel=\"nofollow noreferrer\">values</a>. </p>\n\n<p>For attributes regardless they are methods or variables: </p>\n\n<pre><code>o.keys()\n</code></pre>\n\n<p>For values of those attributes:</p>\n\n<pre><code>o.values()\n</code></pre>\n" }, { "answer_id": 46095449, "author": "Robert Hönig", "author_id": 5723681, "author_profile": "https://Stackoverflow.com/users/5723681", "pm_score": 2, "selected": false, "text": "<p>For everybody struggling with </p>\n\n<ul>\n<li><code>vars()</code> not returning all attributes. </li>\n<li><code>dir()</code> not returning the attributes' values.</li>\n</ul>\n\n<p>The following code prints <strong>all</strong> attributes of <code>obj</code> with their values:</p>\n\n<pre><code>for attr in dir(obj):\n try:\n print(\"obj.{} = {}\".format(attr, getattr(obj, attr)))\n except AttributeError:\n print(\"obj.{} = ?\".format(attr))\n</code></pre>\n" }, { "answer_id": 46461051, "author": "Nagev", "author_id": 5362795, "author_profile": "https://Stackoverflow.com/users/5362795", "pm_score": 2, "selected": false, "text": "<p>If you want to see all the <em>values</em> in a complex data structure, then do something like:</p>\n<pre><code>from pprint import pprint\npprint(my_var)\n</code></pre>\n<p>Where <em>my_var</em> is your variable of interest. When I used <code>pprint(vars(my_var))</code> I got nothing, and other answers here didn't help or the method looked unnecessarily long. By the way, in my particular case, the code I was inspecting had a dictionary of dictionaries.</p>\n<p>Worth pointing out that with some custom classes you may just end up with an unhelpful <code>&lt;someobject.ExampleClass object at 0x7f739267f400&gt;</code> kind of output. In that case, you might have to implement a <code>__str__</code> method, or try some of the other solutions.</p>\n<p>I also found that in one instance where I got this <code>object</code> type of output, <code>vars()</code> showed me what I wanted. So a better solution to cover both cases would be to try both individually. But using <code>vars()</code> can sometimes throw an exception, for example, <code>TypeError: vars() argument must have __dict__ attribute</code>.</p>\n<p>I'd still like to find something simple that works in all scenarios, without third party libraries.</p>\n" }, { "answer_id": 53668012, "author": "prosti", "author_id": 5884955, "author_profile": "https://Stackoverflow.com/users/5884955", "pm_score": 4, "selected": false, "text": "<p>I recommend using <code>help(your_object)</code>.</p>\n\n<p><code>help(dir)</code></p>\n\n<blockquote>\n<pre><code> If called without an argument, return the names in the current scope.\n Else, return an alphabetized list of names comprising (some of) the attributes\n of the given object, and of attributes reachable from it.\n If the object supplies a method named __dir__, it will be used; otherwise\n the default dir() logic is used and returns:\n for a module object: the module's attributes.\n for a class object: its attributes, and recursively the attributes\n of its bases.\n for any other object: its attributes, its class's attributes, and\n recursively the attributes of its class's base classes.\n</code></pre>\n</blockquote>\n\n<p><code>help(vars)</code></p>\n\n<blockquote>\n<pre><code>Without arguments, equivalent to locals().\nWith an argument, equivalent to object.__dict__.\n</code></pre>\n</blockquote>\n" }, { "answer_id": 59128615, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 6, "selected": false, "text": "<blockquote>\n<h2>Is there a built-in function to print all the current properties and values of an object?</h2>\n</blockquote>\n<p>No. The most upvoted answer excludes some kinds of attributes, and the accepted answer shows how to get <em>all</em> attributes, including methods and parts of the non-public api. But there is no good complete <em>builtin</em> function for this.</p>\n<p>So the short corollary is that you can write your own, but it will calculate properties and other calculated data-descriptors that are part of the public API, and you might not want that:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from pprint import pprint\nfrom inspect import getmembers\nfrom types import FunctionType\n\ndef attributes(obj):\n disallowed_names = {\n name for name, value in getmembers(type(obj)) \n if isinstance(value, FunctionType)}\n return {\n name: getattr(obj, name) for name in dir(obj) \n if name[0] != '_' and name not in disallowed_names and hasattr(obj, name)}\n\ndef print_attributes(obj):\n pprint(attributes(obj))\n</code></pre>\n<h2>Problems with other answers</h2>\n<p>Observe the application of the currently top voted answer on a class with a lot of different kinds of data members:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from pprint import pprint\n\nclass Obj:\n __slots__ = 'foo', 'bar', '__dict__'\n def __init__(self, baz):\n self.foo = ''\n self.bar = 0\n self.baz = baz\n @property\n def quux(self):\n return self.foo * self.bar\n\nobj = Obj('baz')\npprint(vars(obj))\n</code></pre>\n<p>only prints:</p>\n<pre class=\"lang-py prettyprint-override\"><code>{'baz': 'baz'}\n</code></pre>\n<p>Because <code>vars</code> <em>only</em> returns the <code>__dict__</code> of an object, and it's not a copy, so if you modify the dict returned by vars, you're also modifying the <code>__dict__</code> of the object itself.</p>\n<pre class=\"lang-py prettyprint-override\"><code>vars(obj)['quux'] = 'WHAT?!'\nvars(obj)\n</code></pre>\n<p>returns:</p>\n<pre class=\"lang-py prettyprint-override\"><code>{'baz': 'baz', 'quux': 'WHAT?!'}\n</code></pre>\n<p>-- which is bad because quux is a property that we shouldn't be setting and shouldn't be in the namespace...</p>\n<p>Applying the advice in the currently accepted answer (and others) is not much better:</p>\n<pre><code>&gt;&gt;&gt; dir(obj)\n['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', 'bar', 'baz', 'foo', 'quux']\n</code></pre>\n<p>As we can see, <code>dir</code> only returns <em>all</em> (actually just most) of the names associated with an object.</p>\n<p><code>inspect.getmembers</code>, mentioned in the comments, is similarly flawed - it returns all names <em>and</em> values.</p>\n<h3>From class</h3>\n<p>When teaching I have my students create a function that provides the semantically public API of an object:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def api(obj):\n return [name for name in dir(obj) if name[0] != '_']\n</code></pre>\n<p>We can extend this to provide a <em>copy</em> of the semantic namespace of an object, but we need to exclude <code>__slots__</code> that aren't assigned, and if we're taking the request for &quot;current properties&quot; seriously, we need to exclude calculated properties (as they could become expensive, and could be interpreted as not &quot;current&quot;):</p>\n<pre class=\"lang-py prettyprint-override\"><code>from types import FunctionType\nfrom inspect import getmembers\n\ndef attrs(obj):\n disallowed_properties = {\n name for name, value in getmembers(type(obj)) \n if isinstance(value, (property, FunctionType))\n }\n return {\n name: getattr(obj, name) for name in api(obj) \n if name not in disallowed_properties and hasattr(obj, name)\n }\n\n</code></pre>\n<p>And now we do not calculate or show the property, quux:</p>\n<pre><code>&gt;&gt;&gt; attrs(obj)\n{'bar': 0, 'baz': 'baz', 'foo': ''}\n</code></pre>\n<h3>Caveats</h3>\n<p>But perhaps we do know our properties aren't expensive. We may want to alter the logic to include them as well. And perhaps we want to exclude <em>other</em> <strong>custom</strong> data descriptors instead.</p>\n<p>Then we need to further customize this function. And so it makes sense that we cannot have a built-in function that magically knows exactly what we want and provides it. This is functionality we need to create ourselves.</p>\n<h2>Conclusion</h2>\n<p>There is no built-in function that does this, and you should do what is most semantically appropriate for your situation.</p>\n" }, { "answer_id": 60033193, "author": "Carl Cheung", "author_id": 10860732, "author_profile": "https://Stackoverflow.com/users/10860732", "pm_score": 2, "selected": false, "text": "<p>This works no matter how your varibles are defined within a class, inside __init__ or outside.</p>\n\n<pre><code>your_obj = YourObj()\nattrs_with_value = {attr: getattr(your_obj, attr) for attr in dir(your_obj)}\n</code></pre>\n" }, { "answer_id": 68827085, "author": "Vishnu", "author_id": 1779027, "author_profile": "https://Stackoverflow.com/users/1779027", "pm_score": 0, "selected": false, "text": "<p>From the <a href=\"https://stackoverflow.com/a/59128615/1779027\">answer</a>, it can be slightly modified to get only 'Attributes' of an object as below:</p>\n<pre><code>def getAttributes(obj):\n from pprint import pprint\n from inspect import getmembers\n from types import FunctionType\n \n def attributes(obj):\n disallowed_names = {\n name for name, value in getmembers(type(obj)) \n if isinstance(value, FunctionType)}\n return {\n name for name in dir(obj) \n if name[0] != '_' and name not in disallowed_names and hasattr(obj, name)}\n pprint(attributes(obj))\n</code></pre>\n<p>It is helpful when adding this function temporary and can be removed without many changes in existing source code</p>\n" }, { "answer_id": 69186290, "author": "MichaelMoser", "author_id": 3034482, "author_profile": "https://Stackoverflow.com/users/3034482", "pm_score": 0, "selected": false, "text": "<p>This project modifies pprint to show all object field values, it ignores he objects <code>__repr__</code> member function, it also recurses into nested objects. It works with python3, see <a href=\"https://github.com/MoserMichael/pprintex\" rel=\"nofollow noreferrer\">https://github.com/MoserMichael/pprintex</a>\nYou can install it via pip: <code>pip install printex</code></p>\n" }, { "answer_id": 69432736, "author": "Allohvk", "author_id": 14642180, "author_profile": "https://Stackoverflow.com/users/14642180", "pm_score": 2, "selected": false, "text": "<p>While there are many good answers, here is a 1-liner that can give the attributes AS WELL AS values:</p>\n<pre><code>(str(vars(config)).split(&quot;,&quot;)[1:])\n</code></pre>\n<p>where 'config' is the object in question. I am listing this as a separate answer because I just wanted to simply print the relevant values of the object (excl the __main etc) without using loops or pretty print and didn't find a convenient answer.</p>\n" }, { "answer_id": 70403363, "author": "yrnr", "author_id": 10272780, "author_profile": "https://Stackoverflow.com/users/10272780", "pm_score": 1, "selected": false, "text": "<p>vars() seems to show the attributes of this object, but dir() seems to show attributes of parent class(es) as well. You don't usually need to see inherited attributes such as <strong>str</strong>, <strong>doc</strong>. <strong>dict</strong> etc.</p>\n<pre><code>In [1]: class Aaa():\n...: def __init__(self, name, age):\n...: self.name = name\n...: self.age = age\n...:\nIn [2]: class Bbb(Aaa):\n...: def __init__(self, name, age, job):\n...: super().__init__(name, age)\n...: self.job = job\n...:\nIn [3]: a = Aaa('Pullayya',42)\n\nIn [4]: b = Bbb('Yellayya',41,'Cop')\n\nIn [5]: vars(a)\nOut[5]: {'name': 'Pullayya', 'age': 42}\n\nIn [6]: vars(b)\nOut[6]: {'name': 'Yellayya', 'age': 41, 'job': 'Cop'}\n\nIn [7]: dir(a)\nOut[7]:\n['__class__',\n '__delattr__',\n '__dict__',\n '__dir__',\n '__doc__',\n '__eq__',\n ...\n ...\n '__subclasshook__',\n '__weakref__',\n 'age',\n 'name']\n</code></pre>\n" }, { "answer_id": 74031715, "author": "Timothy C. Quinn", "author_id": 286807, "author_profile": "https://Stackoverflow.com/users/286807", "pm_score": 0, "selected": false, "text": "<p>I have not tested performance, but I believe this is the fastest method to enumerate just the properties / attributes / keys of any object in Python as a list.</p>\n<pre><code># If core==False, ignore __k__ entries\ndef obj_props(obj, core=False) -&gt; list:\n assert not obj is None, f&quot;obj must not be null (None)&quot;\n _props = []\n _use_dir=False\n def _add(p):\n if not core and p.find('__') == 0: return\n _props.append(p)\n if hasattr(obj, '__dict__'): \n for p in obj.__dict__.keys(): _add(p)\n elif hasattr(obj, '__slots__'):\n for p in obj.__slots__: _add(p)\n elif hasattr(obj, 'keys'):\n try:\n for p in obj.keys(): _add(p)\n except Exception as ex:\n _props = []\n _use_dir = True\n else:\n _use_dir = True\n if _use_dir:\n # fall back to slow and steady\n for p in dir(obj):\n if not core and p.find('__') == 0: continue\n v = getattr(obj, p)\n v_t = type(v).__name__\n if v_t in ('function', 'method', 'builtin_function_or_method', 'method-wrapper'): continue\n _props.append(p)\n\n return _props\n</code></pre>\n<p>The above should work with regular python objects (with <code>__dict__</code>), objects using slots (<code>__slots__</code>) and even work with dictionary like objects.</p>\n<p>Most other examples utilize <code>dir(obj)</code> which will enumerate all methods and properties of an object which will take a performance hit if you only need its properties.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
So what I'm looking for here is something like PHP's [print\_r](http://us2.php.net/print_r) function. This is so I can debug my scripts by seeing what's the state of the object in question.
You are really mixing together two different things. Use [`dir()`](https://docs.python.org/3/library/functions.html#dir), [`vars()`](https://docs.python.org/3/library/functions.html#vars) or the [`inspect`](https://docs.python.org/3/library/inspect.html) module to get what you are interested in (I use `__builtins__` as an example; you can use any object instead). ``` >>> l = dir(__builtins__) >>> d = __builtins__.__dict__ ``` Print that dictionary however fancy you like: ``` >>> print l ['ArithmeticError', 'AssertionError', 'AttributeError',... ``` or ``` >>> from pprint import pprint >>> pprint(l) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'DeprecationWarning', ... >>> pprint(d, indent=2) { 'ArithmeticError': <type 'exceptions.ArithmeticError'>, 'AssertionError': <type 'exceptions.AssertionError'>, 'AttributeError': <type 'exceptions.AttributeError'>, ... '_': [ 'ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'DeprecationWarning', ... ``` Pretty printing is also available in the interactive debugger as a command: ``` (Pdb) pp vars() {'__builtins__': {'ArithmeticError': <type 'exceptions.ArithmeticError'>, 'AssertionError': <type 'exceptions.AssertionError'>, 'AttributeError': <type 'exceptions.AttributeError'>, 'BaseException': <type 'exceptions.BaseException'>, 'BufferError': <type 'exceptions.BufferError'>, ... 'zip': <built-in function zip>}, '__file__': 'pass.py', '__name__': '__main__'} ```
192,111
<p>In PHP, I am able to use a normal function as a variable without problem, but I haven't figured out how to use a static method. Am I just missing the right syntax, or is this not possible?</p> <p>(EDIT: the first suggested answer does not seem to work. I've extended my example to show the errors returned.)</p> <pre><code>function foo1($a,$b) { return $a/$b; } class Bar { static function foo2($a,$b) { return $a/$b; } public function UseReferences() { // WORKS FINE: $fn = foo1; print $fn(1,1); // WORKS FINE: print self::foo2(2,1); print Bar::foo2(3,1); // DOES NOT WORK ... error: Undefined class constant 'foo2' //$fn = self::foo2; //print $fn(4,1); // DOES NOT WORK ... error: Call to undefined function self::foo2() //$fn = 'self::foo2'; //print $fn(5,1); // DOES NOT WORK ... error: Call to undefined function Bar::foo2() //$fn = 'Bar::foo2'; //print $fn(5,1); } } $x = new Bar(); $x-&gt;UseReferences(); </code></pre> <p>(I am using PHP v5.2.6 -- does the answer change depending on version too?)</p>
[ { "answer_id": 192123, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 6, "selected": true, "text": "<p>PHP handles callbacks as strings, not function pointers. The reason your first test works is because the PHP interpreter assumes <strong>foo1</strong> as a string. If you have E_NOTICE level error enabled, you should see proof of that.</p>\n\n<p>\"Use of undefined constant foo1 - assumed 'foo1'\"</p>\n\n<p>You can't call static methods this way, unfortunately. The scope (class) is relevant so you need to use call_user_func instead.</p>\n\n<pre><code>&lt;?php\n\nfunction foo1($a,$b) { return $a/$b; }\n\nclass Bar\n{\n public static function foo2($a,$b) { return $a/$b; }\n\n public function UseReferences()\n {\n $fn = 'foo1';\n echo $fn(6,3);\n\n $fn = array( 'self', 'foo2' );\n print call_user_func( $fn, 6, 2 );\n }\n}\n\n$b = new Bar;\n$b-&gt;UseReferences();\n</code></pre>\n" }, { "answer_id": 192234, "author": "Joe", "author_id": 9284, "author_profile": "https://Stackoverflow.com/users/9284", "pm_score": -1, "selected": false, "text": "<p>\"A member or method declared with static can not be accessed with a variable that is an instance of the object and cannot be re-defined in an extending class\"</p>\n\n<p>(<a href=\"http://theserverpages.com/php/manual/en/language.oop5.static.php\" rel=\"nofollow noreferrer\">http://theserverpages.com/php/manual/en/language.oop5.static.php</a>)</p>\n" }, { "answer_id": 192569, "author": "rewbs", "author_id": 6095, "author_profile": "https://Stackoverflow.com/users/6095", "pm_score": 3, "selected": false, "text": "<p>In php 5.2, you can use a variable as the method name in a static call, but to use a variable as the class name, you'll have to use callbacks as described by BaileyP.</p>\n\n<p>However, from php 5.3, you <strong>can</strong> use a variable as the class name in a static call. So:\n \n\n<pre><code>class Bar\n{\n public static function foo2($a,$b) { return $a/$b; }\n\n public function UseReferences()\n {\n $method = 'foo2';\n print Bar::$method(6,2); // works in php 5.2.6\n\n $class = 'Bar';\n print $class::$method(6,2); // works in php 5.3\n }\n}\n\n$b = new Bar;\n$b-&gt;UseReferences();\n?&gt;\n</code></pre>\n" }, { "answer_id": 193888, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>This seems to work for me:</p>\n\n<pre><code>&lt;?php\n\nclass Foo{\n static function Calc($x,$y){\n return $x + $y;\n }\n\n public function Test(){\n $z = self::Calc(3,4);\n\n echo(\"z = \".$z);\n }\n}\n\n$foo = new Foo();\n$foo-&gt;Test();\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 3528322, "author": "dwallace", "author_id": 425995, "author_profile": "https://Stackoverflow.com/users/425995", "pm_score": 1, "selected": false, "text": "<p>In PHP 5.3.0, you could also do the following:</p>\n\n<pre><code>&lt;?php\n\nclass Foo {\n static function Bar($a, $b) {\n if ($a == $b)\n return 0;\n\n return ($a &lt; $b) ? -1 : 1;\n }\n function RBar($a, $b) {\n if ($a == $b)\n return 0;\n\n return ($a &lt; $b) ? 1 : -1;\n }\n}\n\n$vals = array(3,2,6,4,1);\n$cmpFunc = array('Foo', 'Bar');\nusort($vals, $cmpFunc);\n\n// This would also work:\n$fooInstance = new Foo();\n$cmpFunc = array('fooInstance', 'RBar');\n// Or\n// $cmpFunc = array('fooInstance', 'Bar');\nusort($vals, $cmpFunc);\n\n?&gt;\n</code></pre>\n" }, { "answer_id": 11114157, "author": "Jiangge Zhang", "author_id": 718453, "author_profile": "https://Stackoverflow.com/users/718453", "pm_score": 3, "selected": false, "text": "<p>You could use the full name of static method, including the namespace.</p>\n\n<pre><code>&lt;?php\n function foo($method)\n {\n return $method('argument');\n }\n\n foo('YourClass::staticMethod');\n foo('Namespace\\YourClass::staticMethod');\n</code></pre>\n\n<p>The name array <code>array('YourClass', 'staticMethod')</code> is equal to it. But I think the string may be more clear for reading.</p>\n" }, { "answer_id": 14208014, "author": "hek2mgl", "author_id": 171318, "author_profile": "https://Stackoverflow.com/users/171318", "pm_score": 0, "selected": false, "text": "<p>In addition to what was said you can also use PHP's reflection capabilities:</p>\n\n<pre><code>class Bar {\n\n public static function foo($foo, $bar) {\n return $foo . ' ' . $bar;\n }\n\n\n public function useReferences () {\n $method = new ReflectionMethod($this, 'foo');\n // Note NULL as the first argument for a static call\n $result = $method-&gt;invoke(NULL, '123', 'xyz');\n }\n\n}\n</code></pre>\n" }, { "answer_id": 20649422, "author": "Camilo Martin", "author_id": 124119, "author_profile": "https://Stackoverflow.com/users/124119", "pm_score": 1, "selected": false, "text": "<p>Coming from a javascript background and being spoiled by it, I just coded this:</p>\n\n<pre><code>function staticFunctionReference($name)\n{\n return function() use ($name)\n {\n $className = strstr($name, '::', true);\n if (class_exists(__NAMESPACE__.\"\\\\$className\")) $name = __NAMESPACE__.\"\\\\$name\";\n return call_user_func_array($name, func_get_args());\n };\n}\n</code></pre>\n\n<p>To use it:</p>\n\n<pre><code>$foo = staticFunctionReference('Foo::bar');\n$foo('some', 'parameters');\n</code></pre>\n\n<p>It's a function that returns a function that calls the function you wanted to call. Sounds fancy but as you can see in practice it's piece of cake.</p>\n\n<p>Works with namespaces and the returned function should work just like the static method - parameters work the same.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4540/" ]
In PHP, I am able to use a normal function as a variable without problem, but I haven't figured out how to use a static method. Am I just missing the right syntax, or is this not possible? (EDIT: the first suggested answer does not seem to work. I've extended my example to show the errors returned.) ``` function foo1($a,$b) { return $a/$b; } class Bar { static function foo2($a,$b) { return $a/$b; } public function UseReferences() { // WORKS FINE: $fn = foo1; print $fn(1,1); // WORKS FINE: print self::foo2(2,1); print Bar::foo2(3,1); // DOES NOT WORK ... error: Undefined class constant 'foo2' //$fn = self::foo2; //print $fn(4,1); // DOES NOT WORK ... error: Call to undefined function self::foo2() //$fn = 'self::foo2'; //print $fn(5,1); // DOES NOT WORK ... error: Call to undefined function Bar::foo2() //$fn = 'Bar::foo2'; //print $fn(5,1); } } $x = new Bar(); $x->UseReferences(); ``` (I am using PHP v5.2.6 -- does the answer change depending on version too?)
PHP handles callbacks as strings, not function pointers. The reason your first test works is because the PHP interpreter assumes **foo1** as a string. If you have E\_NOTICE level error enabled, you should see proof of that. "Use of undefined constant foo1 - assumed 'foo1'" You can't call static methods this way, unfortunately. The scope (class) is relevant so you need to use call\_user\_func instead. ``` <?php function foo1($a,$b) { return $a/$b; } class Bar { public static function foo2($a,$b) { return $a/$b; } public function UseReferences() { $fn = 'foo1'; echo $fn(6,3); $fn = array( 'self', 'foo2' ); print call_user_func( $fn, 6, 2 ); } } $b = new Bar; $b->UseReferences(); ```
192,121
<p>I want to use the DateTime.TryParse method to get the datetime value of a string into a Nullable. But when I try this:</p> <pre><code>DateTime? d; bool success = DateTime.TryParse("some date text", out (DateTime)d); </code></pre> <p>the compiler tells me </p> <blockquote> <p>'out' argument is not classified as a variable</p> </blockquote> <p>Not sure what I need to do here. I've also tried: </p> <pre><code>out (DateTime)d.Value </code></pre> <p>and that doesn't work either. Any ideas?</p>
[ { "answer_id": 192146, "author": "Jason Kealey", "author_id": 20893, "author_profile": "https://Stackoverflow.com/users/20893", "pm_score": 8, "selected": true, "text": "<pre><code>DateTime? d=null;\nDateTime d2;\nbool success = DateTime.TryParse(\"some date text\", out d2);\nif (success) d=d2;\n</code></pre>\n\n<p>(There might be more elegant solutions, but why don't you simply do something as above?)</p>\n" }, { "answer_id": 192178, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": false, "text": "<p>As Jason says, you can create a variable of the right type and pass that. You might want to encapsulate it in your own method:</p>\n\n<pre><code>public static DateTime? TryParse(string text)\n{\n DateTime date;\n if (DateTime.TryParse(text, out date))\n {\n return date;\n }\n else\n {\n return null;\n }\n}\n</code></pre>\n\n<p>... or if you like the conditional operator:</p>\n\n<pre><code>public static DateTime? TryParse(string text)\n{\n DateTime date;\n return DateTime.TryParse(text, out date) ? date : (DateTime?) null;\n}\n</code></pre>\n\n<p>Or in C# 7:</p>\n\n<pre><code>public static DateTime? TryParse(string text) =&gt;\n DateTime.TryParse(text, out var date) ? date : (DateTime?) null;\n</code></pre>\n" }, { "answer_id": 192214, "author": "Binary Worrier", "author_id": 18797, "author_profile": "https://Stackoverflow.com/users/18797", "pm_score": 4, "selected": false, "text": "<p>You can't because <code>Nullable&lt;DateTime&gt;</code> is a different type to <code>DateTime</code>.\nYou need to write your own function to do it, </p>\n\n<pre><code>public bool TryParse(string text, out Nullable&lt;DateTime&gt; nDate)\n{\n DateTime date;\n bool isParsed = DateTime.TryParse(text, out date);\n if (isParsed)\n nDate = new Nullable&lt;DateTime&gt;(date);\n else\n nDate = new Nullable&lt;DateTime&gt;();\n return isParsed;\n}\n</code></pre>\n\n<p>Hope this helps :)</p>\n\n<p><strong>EDIT:</strong>\nRemoved the (obviously) improperly tested extension method, because (as Pointed out by some bad hoor) extension methods that attempt to change the \"this\" parameter will not work with Value Types.</p>\n\n<p>P.S. The Bad Hoor in question is an old friend :)</p>\n" }, { "answer_id": 255045, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>Here is a slightly concised edition of what Jason suggested:</p>\n\n<pre><code>DateTime? d; DateTime dt;\nd = DateTime.TryParse(DateTime.Now.ToString(), out dt)? dt : (DateTime?)null;\n</code></pre>\n" }, { "answer_id": 1556090, "author": "JStrahl", "author_id": 139271, "author_profile": "https://Stackoverflow.com/users/139271", "pm_score": 1, "selected": false, "text": "<p>I don't see why Microsoft didn't handle this. A smart little utility method to deal with this (I had the issue with int, but replacing int with DateTime will be the same effect, could be.....</p>\n\n<pre><code> public static bool NullableValueTryParse(string text, out int? nInt)\n {\n int value;\n if (int.TryParse(text, out value))\n {\n nInt = value;\n return true;\n }\n else\n {\n nInt = null;\n return false;\n }\n }\n</code></pre>\n" }, { "answer_id": 11181584, "author": "user2687864", "author_id": 2687864, "author_profile": "https://Stackoverflow.com/users/2687864", "pm_score": 2, "selected": false, "text": "<p>What about creating an extension method?</p>\n\n<pre><code>public static class NullableExtensions\n{\n public static bool TryParse(this DateTime? dateTime, string dateString, out DateTime? result)\n {\n DateTime tempDate;\n if(! DateTime.TryParse(dateString,out tempDate))\n {\n result = null;\n return false;\n }\n\n result = tempDate;\n return true;\n\n }\n}\n</code></pre>\n" }, { "answer_id": 51734376, "author": "monsieurgutix", "author_id": 8548824, "author_profile": "https://Stackoverflow.com/users/8548824", "pm_score": -1, "selected": false, "text": "<p>Alternatively, if you are not concerned with the possible exception raised, you could change TryParse for Parse:</p>\n\n<pre><code>DateTime? d = DateTime.Parse(\"some valid text\");\n</code></pre>\n\n<p>Although there won't be a boolean indicating success either, it could be practical in some situations where you know that the input text will always be valid.</p>\n" }, { "answer_id": 58456514, "author": "cpcolella", "author_id": 7724517, "author_profile": "https://Stackoverflow.com/users/7724517", "pm_score": 3, "selected": false, "text": "<p>This is the one liner you're looking for:</p>\n<pre><code>DateTime? d = DateTime.TryParse(&quot;some date text&quot;, out DateTime dt) ? dt : null;\n</code></pre>\n<p>If you want to make it a proper TryParse pseudo-extension method, you can do this:</p>\n<pre><code>public static bool TryParse(string text, out DateTime? dt)\n{\n if (DateTime.TryParse(text, out DateTime date))\n {\n dt = date;\n return true;\n }\n else\n {\n dt = null;\n return false;\n }\n}\n</code></pre>\n" }, { "answer_id": 60289544, "author": "user1267054", "author_id": 1267054, "author_profile": "https://Stackoverflow.com/users/1267054", "pm_score": 1, "selected": false, "text": "<p>Here's a single line solution:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>DateTime? d = DateTime.TryParse(\"text\", out DateTime parseDate) ? parseDate : (DateTime?)null;\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/767/" ]
I want to use the DateTime.TryParse method to get the datetime value of a string into a Nullable. But when I try this: ``` DateTime? d; bool success = DateTime.TryParse("some date text", out (DateTime)d); ``` the compiler tells me > > 'out' argument is not classified as a variable > > > Not sure what I need to do here. I've also tried: ``` out (DateTime)d.Value ``` and that doesn't work either. Any ideas?
``` DateTime? d=null; DateTime d2; bool success = DateTime.TryParse("some date text", out d2); if (success) d=d2; ``` (There might be more elegant solutions, but why don't you simply do something as above?)
192,122
<p>This may seem a bit trivial, but I have not been able to figure it out. I am opening up a SPSite and then trying to open up a SPWeb under that SPSite. This is working fine on the VPC, which has the same Site Collection/Site hierarchy, but on production, I get an exception telling me that the URL is invalid when I try the SPSite.OpenWeb(webUrl);. I have verified that the URL’s are correct.</p> <p>The Code:</p> <pre><code> try { SPSite scheduleSiteCol = new SPSite(branchScheduleURL); lblError.Text += Environment.NewLine + "Site Collection URL: " + scheduleSiteCol.Url; SPWeb scheduleWeb = scheduleSiteCol.OpenWeb(branchScheduleURL.Replace(scheduleSiteCol.Url, "")); //&lt;--- Throws error on this line SPList scheduleList = scheduleWeb.GetList(branchScheduleURL + "/lists/" + SPContext.Current.List.Title); return scheduleList.GetItemById(int.Parse(testID)); } catch (System.Exception ex) { lblError.Text += Environment.NewLine + ex.ToString(); return null; } </code></pre> <p>Note:<br> branchScheduleURL is actually the whole URL that includes the URL of the Web as well.</p> <p>The output + exception:</p> <blockquote> <p>Site Collection URL: <a href="https://ourSite.com/mocc" rel="nofollow noreferrer">https://ourSite.com/mocc</a> <br>System.ArgumentException: Invalid URL: /internal/scheduletool. at Microsoft.SharePoint.SPSite.OpenWeb(String strUrl, Boolean requireExactUrl) at Microsoft.SharePoint.SPSite.OpenWeb(String strUrl) at MOCCBranchScheduleListWeb.MOCCBranchScheduleListV3.GetConflictListItem(String branchScheduleURL, String testID)System.NullReferenceException: Object reference not set to an instance of an object. at MOCCBranchScheduleListWeb.MOCCBranchScheduleListV3.CheckForConflicts(String[] cfcFlags1, DateTime startTime, DateTime endTime, String[] cfcFlags2)</p> </blockquote> <p>Note:<br><a href="https://ourSite.com/mocc/internal/scheduletool" rel="nofollow noreferrer">https://ourSite.com/mocc/internal/scheduletool</a> is the SPWeb I am trying to open.</p> <p>Am I missing something obvious? Any help would be greatly appreciated.</p> <p>Thanks.</p>
[ { "answer_id": 192611, "author": "Eugene Katz", "author_id": 1533, "author_profile": "https://Stackoverflow.com/users/1533", "pm_score": 3, "selected": true, "text": "<p>Looks at the examples table at the bottom of <a href=\"http://msdn.microsoft.com/en-us/library/ms955307.aspx\" rel=\"nofollow noreferrer\">this page</a>.</p>\n\n<p>Try not sending any parameters into the OpenWeb() method (2nd row).</p>\n" }, { "answer_id": 194002, "author": "ashwnacharya", "author_id": 1909, "author_profile": "https://Stackoverflow.com/users/1909", "pm_score": 1, "selected": false, "text": "<p>Try getting the SPWeb object for \"Internal\" first. then get the SubWeb SPWebCollection for that and object. From that, try to get the SPWeb object for \"ScheduleTool\" using the GetSubwebsForCurrentUser() Method.</p>\n" }, { "answer_id": 198885, "author": "Peter Seale", "author_id": 25911, "author_profile": "https://Stackoverflow.com/users/25911", "pm_score": 0, "selected": false, "text": "<p>It says your Site Collection URL is /mocc, thus your SPWeb underneath would be something like /mocc/internal/scheduletool. So do something like</p>\n\n<p><code>string webServerRelativeUrl = site.ServerRelativeUrl + \"/internal/scheduletool\"</code></p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22426/" ]
This may seem a bit trivial, but I have not been able to figure it out. I am opening up a SPSite and then trying to open up a SPWeb under that SPSite. This is working fine on the VPC, which has the same Site Collection/Site hierarchy, but on production, I get an exception telling me that the URL is invalid when I try the SPSite.OpenWeb(webUrl);. I have verified that the URL’s are correct. The Code: ``` try { SPSite scheduleSiteCol = new SPSite(branchScheduleURL); lblError.Text += Environment.NewLine + "Site Collection URL: " + scheduleSiteCol.Url; SPWeb scheduleWeb = scheduleSiteCol.OpenWeb(branchScheduleURL.Replace(scheduleSiteCol.Url, "")); //<--- Throws error on this line SPList scheduleList = scheduleWeb.GetList(branchScheduleURL + "/lists/" + SPContext.Current.List.Title); return scheduleList.GetItemById(int.Parse(testID)); } catch (System.Exception ex) { lblError.Text += Environment.NewLine + ex.ToString(); return null; } ``` Note: branchScheduleURL is actually the whole URL that includes the URL of the Web as well. The output + exception: > > Site Collection URL: <https://ourSite.com/mocc> > > System.ArgumentException: Invalid URL: /internal/scheduletool. at Microsoft.SharePoint.SPSite.OpenWeb(String strUrl, Boolean requireExactUrl) at Microsoft.SharePoint.SPSite.OpenWeb(String strUrl) at MOCCBranchScheduleListWeb.MOCCBranchScheduleListV3.GetConflictListItem(String branchScheduleURL, String testID)System.NullReferenceException: Object reference not set to an instance of an object. at MOCCBranchScheduleListWeb.MOCCBranchScheduleListV3.CheckForConflicts(String[] cfcFlags1, DateTime startTime, DateTime endTime, String[] cfcFlags2) > > > Note: <https://ourSite.com/mocc/internal/scheduletool> is the SPWeb I am trying to open. Am I missing something obvious? Any help would be greatly appreciated. Thanks.
Looks at the examples table at the bottom of [this page](http://msdn.microsoft.com/en-us/library/ms955307.aspx). Try not sending any parameters into the OpenWeb() method (2nd row).
192,124
<p>I need specifically to load a JPG image that was saved as a blob. GDI+ makes it very easy to retrieve images from files but not from databases...</p>
[ { "answer_id": 192139, "author": "Jason Kealey", "author_id": 20893, "author_profile": "https://Stackoverflow.com/users/20893", "pm_score": 0, "selected": false, "text": "<p>First fetch your blog into a byte array then use something like this:</p>\n\n<pre><code>public static Image CreateImage(byte[] pict)\n{\n System.Drawing.Image img = null;\n using (System.IO.MemoryStream stream = new System.IO.MemoryStream(pict)) {\n img = System.Drawing.Image.FromStream(stream);\n }\n return img;\n}\n</code></pre>\n" }, { "answer_id": 192568, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 3, "selected": true, "text": "<p>Take a look at <a href=\"http://msdn.microsoft.com/en-us/library/ms535410(VS.85).aspx\" rel=\"nofollow noreferrer\">Image::Image(IStream *, BOOL)</a>. This takes a pointer to a COM object implementing the IStream interface. You can get one of these by allocating some global memory with <a href=\"http://msdn.microsoft.com/en-us/library/aa366574(VS.85).aspx\" rel=\"nofollow noreferrer\">GlobalAlloc</a> and then calling <a href=\"http://msdn.microsoft.com/en-us/library/aa378980(VS.85).aspx\" rel=\"nofollow noreferrer\">CreateStreamOnHGlobal</a> on the returned handle. It'll look something like this:</p>\n\n<pre><code>shared_ptr&lt;Image&gt; CreateImage(BYTE *blob, size_t blobSize)\n{\n HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE,blobSize);\n BYTE *pImage = (BYTE*)::GlobalLock(hMem);\n\n for (size_t iBlob = 0; iBlob &lt; blobSize; ++iBlob)\n pImage[iBlob] = blob[iBlob];\n\n ::GlobalUnlock(hMem);\n\n CComPtr&lt;IStream&gt; spStream;\n HRESULT hr = ::CreateStreamOnHGlobal(hMem,TRUE,&amp;spStream);\n\n shared_ptr&lt;Image&gt; image = new Image(spStream); \n return image;\n}\n</code></pre>\n\n<p>But with error checking and such (omitted here to make things clearer)</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4880/" ]
I need specifically to load a JPG image that was saved as a blob. GDI+ makes it very easy to retrieve images from files but not from databases...
Take a look at [Image::Image(IStream \*, BOOL)](http://msdn.microsoft.com/en-us/library/ms535410(VS.85).aspx). This takes a pointer to a COM object implementing the IStream interface. You can get one of these by allocating some global memory with [GlobalAlloc](http://msdn.microsoft.com/en-us/library/aa366574(VS.85).aspx) and then calling [CreateStreamOnHGlobal](http://msdn.microsoft.com/en-us/library/aa378980(VS.85).aspx) on the returned handle. It'll look something like this: ``` shared_ptr<Image> CreateImage(BYTE *blob, size_t blobSize) { HGLOBAL hMem = ::GlobalAlloc(GMEM_MOVEABLE,blobSize); BYTE *pImage = (BYTE*)::GlobalLock(hMem); for (size_t iBlob = 0; iBlob < blobSize; ++iBlob) pImage[iBlob] = blob[iBlob]; ::GlobalUnlock(hMem); CComPtr<IStream> spStream; HRESULT hr = ::CreateStreamOnHGlobal(hMem,TRUE,&spStream); shared_ptr<Image> image = new Image(spStream); return image; } ``` But with error checking and such (omitted here to make things clearer)
192,126
<p>I have a method that needs to accept an array of country names, and return a list of records that match one of those country names. I'm trying this</p> <pre><code>Public Shared Function GetConcessions(ByVal Countries As String()) As IEnumerable Dim CountryList As String = Utility.JoinArray(Countries) ' turns string array into comma-separated string Return (From t In New Db().Concessions _ Where CountryList Like t.Country _ Select t.ConcessionID, t.Title, t.Country) End Function </code></pre> <p>but I get this error</p> <pre><code> *Only arguments that can be evaluated on the client are supported for the LIKE method </code></pre> <p>In plain SQL, this would be simple:</p> <pre><code> Select ConcessionID,Title from Concessions c where @CountryList like '%' + c.Country + '%' </code></pre> <p>How can I achieve this result in Linq to SQL?</p> <h3>Edit (clarification)</h3> <p>I get the same message with string.Contains. It would be fine with</p> <pre><code>t.Country.contains(CountryList) </code></pre> <p>but I need</p> <pre><code>CountryList.contains(t.Country) </code></pre> <p>and that throws the same error I listed above.</p>
[ { "answer_id": 192167, "author": "sepang", "author_id": 25930, "author_profile": "https://Stackoverflow.com/users/25930", "pm_score": 3, "selected": false, "text": "<p>You can use SqlMethods.Like </p>\n\n<p>e.g. </p>\n\n<pre><code>Where SqlMethods.Like(t.country, \"%Sweden%\")\n</code></pre>\n" }, { "answer_id": 192172, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "<p>I think what you want to do is construct a List from Countries and use</p>\n\n<pre><code>List&lt;string&gt; ListOfCountries = new List(Countries)\n\n...ListOfCountries.Contains(t.Country)\n</code></pre>\n\n<p>This would translate into</p>\n\n<pre><code>t.Country IN ('yyy','zzz',...)\n</code></pre>\n\n<p>Please excuse my C#-ishness..</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
I have a method that needs to accept an array of country names, and return a list of records that match one of those country names. I'm trying this ``` Public Shared Function GetConcessions(ByVal Countries As String()) As IEnumerable Dim CountryList As String = Utility.JoinArray(Countries) ' turns string array into comma-separated string Return (From t In New Db().Concessions _ Where CountryList Like t.Country _ Select t.ConcessionID, t.Title, t.Country) End Function ``` but I get this error ``` *Only arguments that can be evaluated on the client are supported for the LIKE method ``` In plain SQL, this would be simple: ``` Select ConcessionID,Title from Concessions c where @CountryList like '%' + c.Country + '%' ``` How can I achieve this result in Linq to SQL? ### Edit (clarification) I get the same message with string.Contains. It would be fine with ``` t.Country.contains(CountryList) ``` but I need ``` CountryList.contains(t.Country) ``` and that throws the same error I listed above.
I think what you want to do is construct a List from Countries and use ``` List<string> ListOfCountries = new List(Countries) ...ListOfCountries.Contains(t.Country) ``` This would translate into ``` t.Country IN ('yyy','zzz',...) ``` Please excuse my C#-ishness..
192,128
<p>I am working on an Actionscript 2 project - trying to use the XML object to find a url which is returned as a 302 redirect. Is there a way to do this in actionscript 2?</p> <p>code:</p> <pre><code>var urlone:XML = new XML(); urlone.load("http://mydomain.com/file.py"); urlone.onLoad = function (success) { trace("I want to print the 302 redirect url here, how do I access it?"); }; </code></pre>
[ { "answer_id": 192167, "author": "sepang", "author_id": 25930, "author_profile": "https://Stackoverflow.com/users/25930", "pm_score": 3, "selected": false, "text": "<p>You can use SqlMethods.Like </p>\n\n<p>e.g. </p>\n\n<pre><code>Where SqlMethods.Like(t.country, \"%Sweden%\")\n</code></pre>\n" }, { "answer_id": 192172, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": true, "text": "<p>I think what you want to do is construct a List from Countries and use</p>\n\n<pre><code>List&lt;string&gt; ListOfCountries = new List(Countries)\n\n...ListOfCountries.Contains(t.Country)\n</code></pre>\n\n<p>This would translate into</p>\n\n<pre><code>t.Country IN ('yyy','zzz',...)\n</code></pre>\n\n<p>Please excuse my C#-ishness..</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26888/" ]
I am working on an Actionscript 2 project - trying to use the XML object to find a url which is returned as a 302 redirect. Is there a way to do this in actionscript 2? code: ``` var urlone:XML = new XML(); urlone.load("http://mydomain.com/file.py"); urlone.onLoad = function (success) { trace("I want to print the 302 redirect url here, how do I access it?"); }; ```
I think what you want to do is construct a List from Countries and use ``` List<string> ListOfCountries = new List(Countries) ...ListOfCountries.Contains(t.Country) ``` This would translate into ``` t.Country IN ('yyy','zzz',...) ``` Please excuse my C#-ishness..
192,134
<p>I have to check some code and run it. I have the URL:</p> <pre><code>svn+ssh://[email protected]/home/svn/project/trunk </code></pre> <p>I have a file with their private key. What do I do to get this code?</p>
[ { "answer_id": 192186, "author": "Swaroop C H", "author_id": 4869, "author_profile": "https://Stackoverflow.com/users/4869", "pm_score": 1, "selected": false, "text": "<p>Add the private key to your <code>~/.ssh/</code> folder and then run <code>ssh-agent $SHELL; ssh-add;</code>, and then the <code>svn co</code> of that URL should work.</p>\n" }, { "answer_id": 192221, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": true, "text": "<p>The private key goes on the client machine, often named as <code>~/.ssh/id_rsa</code>, <code>~/.ssh/id_dsa</code>, or <code>~/.ssh/identity</code> depending on the SSH version and the type of key. However, you can just use <code>ssh -i path/to/private.key</code>.</p>\n\n<p>This is presuming that the corresponding public key exists on the server in <code>~/.ssh/authorized_keys</code>, and that your local machine is running the OpenSSH client. If you are using PuTTY on Windows, simply open up the Pageant program, and import the key via the GUI.</p>\n" }, { "answer_id": 4455449, "author": "David", "author_id": 136832, "author_profile": "https://Stackoverflow.com/users/136832", "pm_score": 6, "selected": false, "text": "<p>If you need to use a custom key just for svn, the following will work:</p>\n\n<p><code>SVN_SSH=\"ssh -i /path/to/key_name\"</code></p>\n\n<p><code>export SVN_SSH</code></p>\n\n<p><code>svn commands</code></p>\n\n<p><a href=\"http://labs.kortina.net/2010/01/30/svn-checkout-with-private-key-over-ssh/\">http://labs.kortina.net/2010/01/30/svn-checkout-with-private-key-over-ssh/</a></p>\n" }, { "answer_id": 5204421, "author": "Zied", "author_id": 455229, "author_profile": "https://Stackoverflow.com/users/455229", "pm_score": 4, "selected": false, "text": "<p>Add this entry to your <strong>~/.ssh/config</strong> file:</p>\n\n<pre class=\"lang-config prettyprint-override\"><code>Host YOUR_SERVER\nIdentityFile YOUR_PRIVATE_KEY_PATH # (ex: ~/.ssh/rsa)\nUser USER_NAME\n</code></pre>\n\n<p>For more options, <a href=\"http://linux.die.net/man/5/ssh_config\" rel=\"nofollow noreferrer\">see the ssh_config man page</a>.</p>\n" }, { "answer_id": 7084825, "author": "ryatkins", "author_id": 823676, "author_profile": "https://Stackoverflow.com/users/823676", "pm_score": 1, "selected": false, "text": "<p>Here are the steps that I used to connect from the Mac OS X command line to my server via svn+ssh:</p>\n\n<p>On server:</p>\n\n<pre><code>ssh-keygen -b 1024 -t dsa -f mykey (creates mykey and mkey.pub files)\n</code></pre>\n\n<p>Copy contents of <strong>mykey.pub</strong> to ~/.ssh/authorized_keys (create authorized_keys file if it doesn't exist)</p>\n\n<p>Download <strong>mkey</strong> to your local machine and run:</p>\n\n<pre><code>chmod 600 mkey (the next step won't run otherwise)\nsvn-add mkey (enter your passphrase)\n</code></pre>\n\n<p>checkout from your svn server with ssh:</p>\n\n<pre><code>svn co svn+ssh://[email protected]/repos/path\n</code></pre>\n\n<p>Delete mkey and mkey.pub from your server</p>\n" }, { "answer_id": 12223656, "author": "kay am see", "author_id": 567345, "author_profile": "https://Stackoverflow.com/users/567345", "pm_score": 3, "selected": false, "text": "<p>just use ssh-add command (it will ask your for your password, this is the password you used when you created this public private key pair ).</p>\n\n<pre><code>ssh-add PATH_TO_YOUR_PRIVATE_JEY\ne.g. ssh-add ~/.ssh/myPrivateKey.key\n</code></pre>\n\n<p>verify that you added the key correctly by doing this</p>\n\n<pre><code>ssh-add -l\n</code></pre>\n\n<p>That will list all identity files it is using.</p>\n" }, { "answer_id": 21159261, "author": "uı6ʎɹnɯ ꞁəıuɐp", "author_id": 113252, "author_profile": "https://Stackoverflow.com/users/113252", "pm_score": 2, "selected": false, "text": "<p>In addition to the answers two screen shots from Eclipse 3.7 with Subversive. </p>\n\n<hr>\n\n<p><img src=\"https://i.stack.imgur.com/zrqXC.png\" alt=\"General settings\"><br>\n<strong>Enter the user name!</strong> (I have forgotten this before taking the screen shot). Do <strong>not</strong> enter a password.</p>\n\n<hr>\n\n<p><img src=\"https://i.stack.imgur.com/LuJZx.png\" alt=\"SSH Settings\">\nEnter the key passphrase if you private key is passphrase protected.</p>\n\n<hr>\n\n<p><em>A picture is worth a thousand words.</em></p>\n" }, { "answer_id": 55861200, "author": "Legolas Bloom", "author_id": 5204664, "author_profile": "https://Stackoverflow.com/users/5204664", "pm_score": 0, "selected": false, "text": "<pre><code>SVN_SSH=\"ssh -i /xxx/xxx/id_rsa\" svn checkout svn+ssh://[email protected]/data\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577/" ]
I have to check some code and run it. I have the URL: ``` svn+ssh://[email protected]/home/svn/project/trunk ``` I have a file with their private key. What do I do to get this code?
The private key goes on the client machine, often named as `~/.ssh/id_rsa`, `~/.ssh/id_dsa`, or `~/.ssh/identity` depending on the SSH version and the type of key. However, you can just use `ssh -i path/to/private.key`. This is presuming that the corresponding public key exists on the server in `~/.ssh/authorized_keys`, and that your local machine is running the OpenSSH client. If you are using PuTTY on Windows, simply open up the Pageant program, and import the key via the GUI.
192,153
<p>I would like to access the Rails session secret programmatically (I am using it to generate a sign-on token).</p> <p>Here's what I've come up with:</p> <pre><code>ActionController::Base.session.first[:secret] </code></pre> <p>This returns the session secret. However, every time you call ActionController::Base.session it adds another entry to an array so you end up with something like this:</p> <pre><code>[{:session_key=&gt;"_new_app_session", :secret=&gt;"totally-secret-you-guys"}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}] </code></pre> <p>This strikes me as being no good.</p> <p>Is there a better way to access the session secret?</p>
[ { "answer_id": 192270, "author": "whoisjake", "author_id": 2609, "author_profile": "https://Stackoverflow.com/users/2609", "pm_score": 3, "selected": true, "text": "<pre><code>ActionController::Base.session_options_for(request,params[:action])[:secret]\n</code></pre>\n" }, { "answer_id": 192298, "author": "Luke Francl", "author_id": 17965, "author_profile": "https://Stackoverflow.com/users/17965", "pm_score": 2, "selected": false, "text": "<p>Thanks, Jake.</p>\n\n<p>Since the secret doesn't change based on the request or the action, this also works:</p>\n\n<pre><code>ActionController::Base.session_options_for(nil,nil)[:secret]\n</code></pre>\n" }, { "answer_id": 578732, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>For Rails 2.3, I've used:</p>\n\n<pre><code>ActionController::Base.session_options[:secret]\n</code></pre>\n" }, { "answer_id": 4859245, "author": "choonkeat", "author_id": 136558, "author_profile": "https://Stackoverflow.com/users/136558", "pm_score": 4, "selected": false, "text": "<p>For Rails4</p>\n\n<pre><code>Rails.configuration.secret_token\nRails.configuration.secret_key_base\n</code></pre>\n\n<p>For Rails3</p>\n\n<pre><code>Rails.configuration.secret_token\n</code></pre>\n\n<p>But if for Rails2.x, like Don Parish mentioned</p>\n\n<pre><code>ActionController::Base.session_options[:secret]\n</code></pre>\n" }, { "answer_id": 4859368, "author": "James Chen", "author_id": 188145, "author_profile": "https://Stackoverflow.com/users/188145", "pm_score": 0, "selected": false, "text": "<p>For Rails 3, Rails.configuration is same to Rails.application.config, so Rails.configuration.secret_token acts just as what choonkeat provided.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192153", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17965/" ]
I would like to access the Rails session secret programmatically (I am using it to generate a sign-on token). Here's what I've come up with: ``` ActionController::Base.session.first[:secret] ``` This returns the session secret. However, every time you call ActionController::Base.session it adds another entry to an array so you end up with something like this: ``` [{:session_key=>"_new_app_session", :secret=>"totally-secret-you-guys"}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}] ``` This strikes me as being no good. Is there a better way to access the session secret?
``` ActionController::Base.session_options_for(request,params[:action])[:secret] ```
192,200
<p>I have to do a cross site POST (with a redirection, so not using a XMLHTTPRequest), and the base platform is ASP.NET. I don't want to POST all of the controls in the ASP.NET FORM to this other site, so I was considering dynamicly creating a new form element using javascript and just posting that.</p> <p>Has anyone tried this trick? Is there any caveats?</p>
[ { "answer_id": 192212, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>I do this all the time. Works really well. You will have to look through the Request's parameters manually, though, unless you get creative with what you pass as the parameters won't map onto controls on that page. You could also do this in a REST way by passing the parameters in the query string, but I prefer the forms approach to keep my URLs clean. Note that ASP.NET ignores all forms but it's own on postback so I don't bother removing them.</p>\n\n<p>Example from a GridView template field for below code:</p>\n\n<pre><code> &lt;asp:TemplateField HeaderText=\"Station\" SortExpression=\"Name\"&gt;\n &lt;ItemTemplate&gt;\n &lt;a href=\"javascript:void(0);\" onclick='Redirector.redirect_with_id(\"StationDetail.aspx\", &lt;%# Eval(\"StationID\") != null ? Eval(\"StationID\") : \"-1\" %&gt;);return false;'&gt;\n &lt;asp:Label ID=\"nameLabel\" runat=\"server\" Text='&lt;%# Bind(\"Name\") %&gt;' /&gt;&lt;/a&gt;\n &lt;/ItemTemplate&gt;\n &lt;/asp:TemplateField&gt;\n</code></pre>\n\n<p>Code below -- requires Prototype:</p>\n\n<pre><code> // JScript File\n\n var Redirector = Class.create();\n\n Redirector.prototype = {\n initialize: function(url,target) {\n this.url = url;\n this.parameters = new Hash();\n this.target = target;\n }, \n\n addParameter: function(id,value) {\n this.parameters.set(id, value);\n },\n\n redirect: function() {\n var form = document.createElement('form');\n document.body.appendChild(form);\n form.action = this.url;\n form.method = \"post\";\n if (this.target) {\n form.target = this.target;\n }\n this.parameters.each( function(pair) {\n var input = document.createElement('input');\n input.id = pair.key;\n input.name = pair.key;\n input.value = pair.value;\n input.style.display = 'none';\n form.appendChild(input);\n });\n form.submit();\n }\n};\n\nRedirector.redirect_with_id = function(url,id,target) {\n var redirector = new Redirector( url, target );\n redirector.addParameter( 'ID', id );\n redirector.redirect();\n};\n\nRedirector.redirect_with_tag = function(url,tag_name,tag,target) {\n var redirector = new Redirector( url, target );\n redirector.addParameter( tag_name, tag );\n redirector.redirect();\n};\n\nRedirector.redirect_with_tags = function(url,tag_names_comma_separated,tag_values_comma_separated,target) {\n var redirector = new Redirector( url, target );\n var tags = tag_names_comma_separated.split( \",\" );\n var values = tag_values_comma_separated.split( \",\");\n for( var i = 0; i&lt; tags.length; i++ )\n {\n redirector.addParameter( tags[i], values[i] );\n }\n redirector.redirect();\n};\n</code></pre>\n" }, { "answer_id": 192286, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 0, "selected": false, "text": "<p>One caveat: you cannot add a FORM tag to the document using innerHTML. You must add it by creating a new DOM element. You can add fields using innerHTML, but not the form itself.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I have to do a cross site POST (with a redirection, so not using a XMLHTTPRequest), and the base platform is ASP.NET. I don't want to POST all of the controls in the ASP.NET FORM to this other site, so I was considering dynamicly creating a new form element using javascript and just posting that. Has anyone tried this trick? Is there any caveats?
I do this all the time. Works really well. You will have to look through the Request's parameters manually, though, unless you get creative with what you pass as the parameters won't map onto controls on that page. You could also do this in a REST way by passing the parameters in the query string, but I prefer the forms approach to keep my URLs clean. Note that ASP.NET ignores all forms but it's own on postback so I don't bother removing them. Example from a GridView template field for below code: ``` <asp:TemplateField HeaderText="Station" SortExpression="Name"> <ItemTemplate> <a href="javascript:void(0);" onclick='Redirector.redirect_with_id("StationDetail.aspx", <%# Eval("StationID") != null ? Eval("StationID") : "-1" %>);return false;'> <asp:Label ID="nameLabel" runat="server" Text='<%# Bind("Name") %>' /></a> </ItemTemplate> </asp:TemplateField> ``` Code below -- requires Prototype: ``` // JScript File var Redirector = Class.create(); Redirector.prototype = { initialize: function(url,target) { this.url = url; this.parameters = new Hash(); this.target = target; }, addParameter: function(id,value) { this.parameters.set(id, value); }, redirect: function() { var form = document.createElement('form'); document.body.appendChild(form); form.action = this.url; form.method = "post"; if (this.target) { form.target = this.target; } this.parameters.each( function(pair) { var input = document.createElement('input'); input.id = pair.key; input.name = pair.key; input.value = pair.value; input.style.display = 'none'; form.appendChild(input); }); form.submit(); } }; Redirector.redirect_with_id = function(url,id,target) { var redirector = new Redirector( url, target ); redirector.addParameter( 'ID', id ); redirector.redirect(); }; Redirector.redirect_with_tag = function(url,tag_name,tag,target) { var redirector = new Redirector( url, target ); redirector.addParameter( tag_name, tag ); redirector.redirect(); }; Redirector.redirect_with_tags = function(url,tag_names_comma_separated,tag_values_comma_separated,target) { var redirector = new Redirector( url, target ); var tags = tag_names_comma_separated.split( "," ); var values = tag_values_comma_separated.split( ","); for( var i = 0; i< tags.length; i++ ) { redirector.addParameter( tags[i], values[i] ); } redirector.redirect(); }; ```
192,203
<p>How do I do this</p> <pre><code>Select top 10 Foo from MyTable </code></pre> <p>in Linq to SQL?</p>
[ { "answer_id": 192209, "author": "David Alpert", "author_id": 8997, "author_profile": "https://Stackoverflow.com/users/8997", "pm_score": 8, "selected": true, "text": "<p>In VB:</p>\n\n<pre><code>from m in MyTable\ntake 10\nselect m.Foo\n</code></pre>\n\n<p>This assumes that MyTable implements IQueryable. You may have to access that through a DataContext or some other provider.</p>\n\n<p>It also assumes that Foo is a column in MyTable that gets mapped to a property name.</p>\n\n<p>See <a href=\"http://blogs.msdn.com/vbteam/archive/2008/01/08/converting-sql-to-linq-part-7-union-top-subqueries-bill-horst.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/vbteam/archive/2008/01/08/converting-sql-to-linq-part-7-union-top-subqueries-bill-horst.aspx</a> for more detail.</p>\n" }, { "answer_id": 192218, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "<p>You would use the Take(N) method.</p>\n" }, { "answer_id": 192222, "author": "Adam Lassek", "author_id": 1249, "author_profile": "https://Stackoverflow.com/users/1249", "pm_score": 8, "selected": false, "text": "<p>Use the <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.take\" rel=\"noreferrer\">Take method</a>:</p>\n\n<pre><code>var foo = (from t in MyTable\n select t.Foo).Take(10);\n</code></pre>\n\n<p>In VB LINQ has a take expression:</p>\n\n<pre><code>Dim foo = From t in MyTable _\n Take 10 _\n Select t.Foo\n</code></pre>\n\n<p>From the documentation:</p>\n\n<blockquote>\n <p><code>Take&lt;TSource&gt;</code> enumerates <code>source</code> and yields elements until <code>count</code> elements have been yielded or <code>source</code> contains no more elements. If <code>count</code> exceeds the number of elements in <code>source</code>, all elements of <code>source</code> are returned.</p>\n</blockquote>\n" }, { "answer_id": 192224, "author": "amcoder", "author_id": 26898, "author_profile": "https://Stackoverflow.com/users/26898", "pm_score": 5, "selected": false, "text": "<p>Use the <code>Take(int n)</code> method:</p>\n\n<pre><code>var q = query.Take(10);\n</code></pre>\n" }, { "answer_id": 2022116, "author": "spdrcr911", "author_id": 245727, "author_profile": "https://Stackoverflow.com/users/245727", "pm_score": 3, "selected": false, "text": "<p>This works well in C#</p>\n\n<pre><code>var q = from m in MyTable.Take(10)\n select m.Foo\n</code></pre>\n" }, { "answer_id": 2140235, "author": "Janei Vieira", "author_id": 259315, "author_profile": "https://Stackoverflow.com/users/259315", "pm_score": 2, "selected": false, "text": "<p>I do like this:</p>\n\n<pre><code> var dados = from d in dc.tbl_News.Take(4) \n orderby d.idNews descending\n\n select new \n {\n d.idNews,\n d.titleNews,\n d.textNews,\n d.dateNews,\n d.imgNewsThumb\n };\n</code></pre>\n" }, { "answer_id": 2972243, "author": "Anton", "author_id": 199691, "author_profile": "https://Stackoverflow.com/users/199691", "pm_score": 2, "selected": false, "text": "<p>Taking data of DataBase without sorting is the same as random take</p>\n" }, { "answer_id": 3462817, "author": "Yann", "author_id": 417714, "author_profile": "https://Stackoverflow.com/users/417714", "pm_score": 4, "selected": false, "text": "<p>@Janei: my first comment here is about your sample ;)</p>\n\n<p>I think if you do like this, you want to take 4, then applying the sort on these 4.<br/></p>\n\n<pre><code>var dados = from d in dc.tbl_News.Take(4) \n orderby d.idNews descending\n select new \n {\n d.idNews,\n d.titleNews,\n d.textNews,\n d.dateNews,\n d.imgNewsThumb\n };\n</code></pre>\n\n<p>Different than sorting whole tbl_News by idNews descending and then taking 4<br/></p>\n\n<blockquote>\n<pre><code>var dados = (from d in dc.tbl_News\n orderby d.idNews descending\n select new \n {\n d.idNews,\n d.titleNews,\n d.textNews,\n d.dateNews,\n d.imgNewsThumb\n }).Take(4);\n</code></pre>\n</blockquote>\n\n<p>no ? results may be different.</p>\n" }, { "answer_id": 8224883, "author": "user124368", "author_id": 124368, "author_profile": "https://Stackoverflow.com/users/124368", "pm_score": 3, "selected": false, "text": "<p>Whether the take happens on the client or in the db depends on where you apply the take operator. If you apply it before you enumerate the query (i.e. before you use it in a foreach or convert it to a collection) the take will result in the \"top n\" SQL operator being sent to the db. You can see this if you run SQL profiler. If you apply the take after enumerating the query it will happen on the client, as LINQ will have had to retrieve the data from the database for you to enumerate through it</p>\n" }, { "answer_id": 15425617, "author": "minhnguyen", "author_id": 2138384, "author_profile": "https://Stackoverflow.com/users/2138384", "pm_score": 2, "selected": false, "text": "<pre><code>Array oList = ((from m in dc.Reviews\n join n in dc.Users on m.authorID equals n.userID\n orderby m.createdDate descending\n where m.foodID == _id \n select new\n {\n authorID = m.authorID,\n createdDate = m.createdDate,\n review = m.review1,\n author = n.username,\n profileImgUrl = n.profileImgUrl\n }).Take(2)).ToArray();\n</code></pre>\n" }, { "answer_id": 16465885, "author": "apollosoftware.org", "author_id": 937222, "author_profile": "https://Stackoverflow.com/users/937222", "pm_score": 0, "selected": false, "text": "<p>I had to use Take(n) method, then transform to list, Worked like a charm:</p>\n\n<pre><code> var listTest = (from x in table1\n join y in table2\n on x.field1 equals y.field1\n orderby x.id descending\n select new tempList()\n {\n field1 = y.field1,\n active = x.active\n }).Take(10).ToList();\n</code></pre>\n" }, { "answer_id": 33175323, "author": "Inc33", "author_id": 986419, "author_profile": "https://Stackoverflow.com/users/986419", "pm_score": 5, "selected": false, "text": "<p>The OP actually mentioned offset as well, so for ex. if you'd like to get the items from 30 to 60, you would do: </p>\n\n<pre><code>var foo = (From t In MyTable\n Select t.Foo).Skip(30).Take(30);\n</code></pre>\n\n<p>Use the \"Skip\" method for offset.<br>\nUse the \"Take\" method for limit.</p>\n" }, { "answer_id": 46514591, "author": "Gladson Reis", "author_id": 2304714, "author_profile": "https://Stackoverflow.com/users/2304714", "pm_score": 0, "selected": false, "text": "<p>This way it worked for me:</p>\n\n<pre><code>var noticias = from n in db.Noticias.Take(6)\n where n.Atv == 1\n orderby n.DatHorLan descending\n select n;\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
How do I do this ``` Select top 10 Foo from MyTable ``` in Linq to SQL?
In VB: ``` from m in MyTable take 10 select m.Foo ``` This assumes that MyTable implements IQueryable. You may have to access that through a DataContext or some other provider. It also assumes that Foo is a column in MyTable that gets mapped to a property name. See <http://blogs.msdn.com/vbteam/archive/2008/01/08/converting-sql-to-linq-part-7-union-top-subqueries-bill-horst.aspx> for more detail.
192,213
<p>This is the SQL that I want to accomplish:</p> <pre><code>WHERE domain_nm + '\' + group_nm in ('DOMAINNAME\USERNAME1','DOMAINNAME2\USERNAME2') </code></pre> <p>I can't for the life of me find an appropriate Expression for this. And I don't think I can use two expressions as the domain name and the group name need to be concatenated.</p> <p>Thanks!</p>
[ { "answer_id": 214260, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 2, "selected": false, "text": "<p>Can you not use two Expressions?</p>\n\n<pre><code>criteria\n .Add(Expression.In(\"DomainName\", new string[] { \"DOMAINNAME\", \"DOMAINNAME2\" }))\n .Add(Expression.In(\"GroupName\", new string[] { \"USERNAME1\", \"USERNAME2\" })\n</code></pre>\n\n<p>The other option is to use Expression.Sql.</p>\n" }, { "answer_id": 218596, "author": "Ahoapap", "author_id": 26896, "author_profile": "https://Stackoverflow.com/users/26896", "pm_score": 0, "selected": false, "text": "<p>I would just like to point out that two expressions will NOT work as I need a single expression.</p>\n\n<p>DomainName and GroupName need to be concatenated before the in occurs. Think user names on a domain account. The DomainName and GroupName together are unique, not each separately.</p>\n" }, { "answer_id": 219082, "author": "Ahoapap", "author_id": 26896, "author_profile": "https://Stackoverflow.com/users/26896", "pm_score": 2, "selected": false, "text": "<p>The Expression.Sql is as follows:</p>\n\n<pre><code>.Add(Expression.Sql(String.Format(\"{{alias}}.domain_nm + '\\' + {{alias}}.group_nm in ({0})\", getSqlInString(userGroups))))\n</code></pre>\n" }, { "answer_id": 33300297, "author": "Ross Jones", "author_id": 1298331, "author_profile": "https://Stackoverflow.com/users/1298331", "pm_score": 0, "selected": false, "text": "<p>You could add a readonly formula field in your map. You will be able to query it that way. It would look like this using fluent nhibernate</p>\n\n<pre><code>Map(x =&gt; x.FullName).Formula(\"[domain_nm] + '\\' + [group_nm]\")\n</code></pre>\n\n<p>The query would then look like this</p>\n\n<pre><code>criteria.Add(Expression.In(\"FullName\", new string[] { \"DOMAINNAME\\USERNAME1\", \"DOMAINNAME2\\USERNAME2\" }))\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26896/" ]
This is the SQL that I want to accomplish: ``` WHERE domain_nm + '\' + group_nm in ('DOMAINNAME\USERNAME1','DOMAINNAME2\USERNAME2') ``` I can't for the life of me find an appropriate Expression for this. And I don't think I can use two expressions as the domain name and the group name need to be concatenated. Thanks!
Can you not use two Expressions? ``` criteria .Add(Expression.In("DomainName", new string[] { "DOMAINNAME", "DOMAINNAME2" })) .Add(Expression.In("GroupName", new string[] { "USERNAME1", "USERNAME2" }) ``` The other option is to use Expression.Sql.
192,220
<p>Assume you have a flat table that stores an ordered tree hierarchy:</p> <pre><code>Id Name ParentId Order 1 'Node 1' 0 10 2 'Node 1.1' 1 10 3 'Node 2' 0 20 4 'Node 1.1.1' 2 10 5 'Node 2.1' 3 10 6 'Node 1.2' 1 20 </code></pre> <p>Here's a diagram, where we have <code>[id] Name</code>. Root node 0 is fictional.</p> <pre> [0] ROOT / \ [1] Node 1 [3] Node 2 / \ \ [2] Node 1.1 [6] Node 1.2 [5] Node 2.1 / [4] Node 1.1.1 </pre> <p>What minimalistic approach would you use to output that to HTML (or text, for that matter) as a correctly ordered, correctly indented tree? </p> <p>Assume further you only have basic data structures (arrays and hashmaps), no fancy objects with parent/children references, no ORM, no framework, just your two hands. The table is represented as a result set, which can be accessed randomly. </p> <p>Pseudo code or plain English is okay, this is purely a conceptional question.</p> <p>Bonus question: Is there a fundamentally better way to store a tree structure like this in a RDBMS?</p> <hr> <p><strong>EDITS AND ADDITIONS</strong></p> <p>To answer one commenter's (<a href="https://stackoverflow.com/users/17826/mark-bessey">Mark Bessey</a>'s) question: A root node is not necessary, because it is never going to be displayed anyway. ParentId = 0 is the convention to express "these are top level". The Order column defines how nodes with the same parent are going to be sorted.</p> <p>The "result set" I spoke of can be pictured as an array of hashmaps (to stay in that terminology). For my example was meant to be already there. Some answers go the extra mile and construct it first, but thats okay.</p> <p>The tree can be arbitrarily deep. Each node can have N children. I did not exactly have a "millions of entries" tree in mind, though.</p> <p>Don't mistake my choice of node naming ('Node 1.1.1') for something to rely on. The nodes could equally well be called 'Frank' or 'Bob', no naming structure is implied, this was merely to make it readable.</p> <p><em>I have posted my own solution so you guys can pull it to pieces.</em></p>
[ { "answer_id": 192252, "author": "wcm", "author_id": 2173, "author_profile": "https://Stackoverflow.com/users/2173", "pm_score": 2, "selected": false, "text": "<p>Assuming that you know that the root elements are zero, here's the pseudocode to output to text:</p>\n\n<pre><code>function PrintLevel (int curr, int level)\n //print the indents\n for (i=1; i&lt;=level; i++)\n print a tab\n print curr \\n;\n for each child in the table with a parent of curr\n PrintLevel (child, level+1)\n\n\nfor each elementID where the parentid is zero\n PrintLevel(elementID, 0)\n</code></pre>\n" }, { "answer_id": 192263, "author": "tchen", "author_id": 18417, "author_profile": "https://Stackoverflow.com/users/18417", "pm_score": 1, "selected": false, "text": "<p>If nested hash maps or arrays can be created, then I can simply go down the table from the beginning and add each item to the nested array. I must trace each line to the root node in order to know which level in the nested array to insert into. I can employ memoization so that I do not need to look up the same parent over and over again.</p>\n\n<p>Edit: I would read the entire table into an array first, so it will not query the DB repeatedly. Of course this won't be practical if your table is very large.</p>\n\n<p>After the structure is built, I must do a depth first traverse through it and print out the HTML.</p>\n\n<p>There's no better fundamental way to store this information using one table (I could be wrong though ;), and would love to see a better solution ). However, if you create a scheme to employ dynamically created db tables, then you opened up a whole new world at the sacrifice of simplicity, and the risk of SQL hell ;).</p>\n" }, { "answer_id": 192348, "author": "Mark Bessey", "author_id": 17826, "author_profile": "https://Stackoverflow.com/users/17826", "pm_score": 2, "selected": false, "text": "<p>You can emulate any other data structure with a hashmap, so that's not a terrible limitation. Scanning from the top to the bottom, you create a hashmap for each row of the database, with an entry for each column. Add each of these hashmaps to a \"master\" hashmap, keyed on the id. If any node has a \"parent\" that you haven't seen yet, create an placeholder entry for it in the master hashmap, and fill it in when you see the actual node.</p>\n\n<p>To print it out, do a simple depth-first pass through the data, keeping track of indent level along the way. You can make this easier by keeping a \"children\" entry for each row, and populating it as you scan the data.</p>\n\n<p>As for whether there's a \"better\" way to store a tree in a database, that depends on how you're going to use the data. I've seen systems that had a known maximum depth that used a different table for each level in the hierarchy. That makes a lot of sense if the levels in the tree aren't quite equivalent after all (top level categories being different than the leaves).</p>\n" }, { "answer_id": 192394, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 3, "selected": false, "text": "<p>Well given the choice, I'd be using objects. I'd create an object for each record where each object has a <code>children</code> collection and store them all in an assoc array (/hashtable) where the Id is the key. And blitz through the collection once, adding the children to the relevant children fields. <strong>Simple.</strong></p>\n\n<p>But because you're being no fun by restricting use of some good OOP, I'd probably iterate based on:</p>\n\n<pre><code>function PrintLine(int pID, int level)\n foreach record where ParentID == pID\n print level*tabs + record-data\n PrintLine(record.ID, level + 1)\n\nPrintLine(0, 0)\n</code></pre>\n\n<p>Edit: this is similar to a couple of other entries, but I think it's slightly cleaner. One thing I'll add: this is extremely SQL-intensive. It's <em>nasty</em>. <strong>If you have the choice, go the OOP route.</strong></p>\n" }, { "answer_id": 192462, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 10, "selected": true, "text": "<p>Now that <a href=\"https://dev.mysql.com/doc/refman/8.0/en/with.html\" rel=\"nofollow noreferrer\">MySQL 8.0 supports recursive queries</a>, we can say that <a href=\"https://stackoverflow.com/questions/324935/mysql-with-clause/325243#325243\">all popular SQL databases support recursive queries</a> in standard syntax.</p>\n<pre><code>WITH RECURSIVE MyTree AS (\n SELECT * FROM MyTable WHERE ParentId IS NULL\n UNION ALL\n SELECT m.* FROM MyTABLE AS m JOIN MyTree AS t ON m.ParentId = t.Id\n)\nSELECT * FROM MyTree;\n</code></pre>\n<p>I tested recursive queries in MySQL 8.0 in my presentation <a href=\"https://www.slideshare.net/billkarwin/recursive-query-throwdown\" rel=\"nofollow noreferrer\">Recursive Query Throwdown</a> in 2017.</p>\n<p>Below is my original answer from 2008:</p>\n<hr />\n<p>There are several ways to store tree-structured data in a relational database. What you show in your example uses two methods:</p>\n<ul>\n<li><strong>Adjacency List</strong> (the &quot;parent&quot; column) and</li>\n<li><strong>Path Enumeration</strong> (the dotted-numbers in your name column).</li>\n</ul>\n<p>Another solution is called <strong>Nested Sets</strong>, and it can be stored in the same table too. Read &quot;<a href=\"https://rads.stackoverflow.com/amzn/click/com/1558609202\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Trees and Hierarchies in SQL for Smarties</a>&quot; by Joe Celko for a lot more information on these designs.</p>\n<p>I usually prefer a design called <strong>Closure Table</strong> (aka &quot;Adjacency Relation&quot;) for storing tree-structured data. It requires another table, but then querying trees is pretty easy.</p>\n<p>I cover Closure Table in my presentation <a href=\"http://www.slideshare.net/billkarwin/models-for-hierarchical-data\" rel=\"nofollow noreferrer\">Models for Hierarchical Data with SQL and PHP</a> and in my book <a href=\"https://pragprog.com/titles/bksap1/sql-antipatterns-volume-1/\" rel=\"nofollow noreferrer\">SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming</a>.</p>\n<pre><code>CREATE TABLE ClosureTable (\n ancestor_id INT NOT NULL REFERENCES FlatTable(id),\n descendant_id INT NOT NULL REFERENCES FlatTable(id),\n PRIMARY KEY (ancestor_id, descendant_id)\n);\n</code></pre>\n<p>Store all paths in the Closure Table, where there is a direct ancestry from one node to another. Include a row for each node to reference itself. For example, using the data set you showed in your question:</p>\n<pre><code>INSERT INTO ClosureTable (ancestor_id, descendant_id) VALUES\n (1,1), (1,2), (1,4), (1,6),\n (2,2), (2,4),\n (3,3), (3,5),\n (4,4),\n (5,5),\n (6,6);\n</code></pre>\n<p>Now you can get a tree starting at node 1 like this:</p>\n<pre><code>SELECT f.* \nFROM FlatTable f \n JOIN ClosureTable a ON (f.id = a.descendant_id)\nWHERE a.ancestor_id = 1;\n</code></pre>\n<p>The output (in MySQL client) looks like the following:</p>\n<pre><code>+----+\n| id |\n+----+\n| 1 | \n| 2 | \n| 4 | \n| 6 | \n+----+\n</code></pre>\n<p>In other words, nodes 3 and 5 are excluded, because they're part of a separate hierarchy, not descending from node 1.</p>\n<hr />\n<p>Re: comment from e-satis about immediate children (or immediate parent). You can add a &quot;<code>path_length</code>&quot; column to the <code>ClosureTable</code> to make it easier to query specifically for an immediate child or parent (or any other distance).</p>\n<pre><code>INSERT INTO ClosureTable (ancestor_id, descendant_id, path_length) VALUES\n (1,1,0), (1,2,1), (1,4,2), (1,6,1),\n (2,2,0), (2,4,1),\n (3,3,0), (3,5,1),\n (4,4,0),\n (5,5,0),\n (6,6,0);\n</code></pre>\n<p>Then you can add a term in your search for querying the immediate children of a given node. These are descendants whose <code>path_length</code> is 1.</p>\n<pre><code>SELECT f.* \nFROM FlatTable f \n JOIN ClosureTable a ON (f.id = a.descendant_id)\nWHERE a.ancestor_id = 1\n AND path_length = 1;\n\n+----+\n| id |\n+----+\n| 2 | \n| 6 | \n+----+\n</code></pre>\n<hr />\n<p>Re comment from @ashraf: &quot;How about sorting the whole tree [by name]?&quot;</p>\n<p>Here's an example query to return all nodes that are descendants of node 1, join them to the FlatTable that contains other node attributes such as <code>name</code>, and sort by the name.</p>\n<pre><code>SELECT f.name\nFROM FlatTable f \nJOIN ClosureTable a ON (f.id = a.descendant_id)\nWHERE a.ancestor_id = 1\nORDER BY f.name;\n</code></pre>\n<hr />\n<p>Re comment from @Nate:</p>\n<pre><code>SELECT f.name, GROUP_CONCAT(b.ancestor_id order by b.path_length desc) AS breadcrumbs\nFROM FlatTable f \nJOIN ClosureTable a ON (f.id = a.descendant_id) \nJOIN ClosureTable b ON (b.descendant_id = a.descendant_id) \nWHERE a.ancestor_id = 1 \nGROUP BY a.descendant_id \nORDER BY f.name\n\n+------------+-------------+\n| name | breadcrumbs |\n+------------+-------------+\n| Node 1 | 1 |\n| Node 1.1 | 1,2 |\n| Node 1.1.1 | 1,2,4 |\n| Node 1.2 | 1,6 |\n+------------+-------------+\n</code></pre>\n<hr />\n<p>A user suggested an edit today. SO moderators approved the edit, but I am reversing it.</p>\n<p>The edit suggested that the ORDER BY in the last query above should be <code>ORDER BY b.path_length, f.name</code>, presumably to make sure the ordering matches the hierarchy. But this doesn't work, because it would order &quot;Node 1.1.1&quot; after &quot;Node 1.2&quot;.</p>\n<p>If you want the ordering to match the hierarchy in a sensible way, that is possible, but not simply by ordering by the path length. For example, see my answer to <a href=\"https://stackoverflow.com/questions/8252323/mysql-closure-table-hierarchical-database-how-to-pull-information-out-in-the-c\">MySQL Closure Table hierarchical database - How to pull information out in the correct order</a>.</p>\n" }, { "answer_id": 192550, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 3, "selected": false, "text": "<p>This was written quickly, and is neither pretty nor efficient (plus it autoboxes alot, converting between <code>int</code> and <code>Integer</code> is annoying!), but it works.</p>\n\n<p>It probably breaks the rules since I'm creating my own objects but hey I'm doing this as a diversion from real work :)</p>\n\n<p>This also assumes that the resultSet/table is completely read into some sort of structure before you start building Nodes, which wouldn't be the best solution if you have hundreds of thousands of rows.</p>\n\n<pre><code>public class Node {\n\n private Node parent = null;\n\n private List&lt;Node&gt; children;\n\n private String name;\n\n private int id = -1;\n\n public Node(Node parent, int id, String name) {\n this.parent = parent;\n this.children = new ArrayList&lt;Node&gt;();\n this.name = name;\n this.id = id;\n }\n\n public int getId() {\n return this.id;\n }\n\n public String getName() {\n return this.name;\n }\n\n public void addChild(Node child) {\n children.add(child);\n }\n\n public List&lt;Node&gt; getChildren() {\n return children;\n }\n\n public boolean isRoot() {\n return (this.parent == null);\n }\n\n @Override\n public String toString() {\n return \"id=\" + id + \", name=\" + name + \", parent=\" + parent;\n }\n}\n\npublic class NodeBuilder {\n\n public static Node build(List&lt;Map&lt;String, String&gt;&gt; input) {\n\n // maps id of a node to it's Node object\n Map&lt;Integer, Node&gt; nodeMap = new HashMap&lt;Integer, Node&gt;();\n\n // maps id of a node to the id of it's parent\n Map&lt;Integer, Integer&gt; childParentMap = new HashMap&lt;Integer, Integer&gt;();\n\n // create special 'root' Node with id=0\n Node root = new Node(null, 0, \"root\");\n nodeMap.put(root.getId(), root);\n\n // iterate thru the input\n for (Map&lt;String, String&gt; map : input) {\n\n // expect each Map to have keys for \"id\", \"name\", \"parent\" ... a\n // real implementation would read from a SQL object or resultset\n int id = Integer.parseInt(map.get(\"id\"));\n String name = map.get(\"name\");\n int parent = Integer.parseInt(map.get(\"parent\"));\n\n Node node = new Node(null, id, name);\n nodeMap.put(id, node);\n\n childParentMap.put(id, parent);\n }\n\n // now that each Node is created, setup the child-parent relationships\n for (Map.Entry&lt;Integer, Integer&gt; entry : childParentMap.entrySet()) {\n int nodeId = entry.getKey();\n int parentId = entry.getValue();\n\n Node child = nodeMap.get(nodeId);\n Node parent = nodeMap.get(parentId);\n parent.addChild(child);\n }\n\n return root;\n }\n}\n\npublic class NodePrinter {\n\n static void printRootNode(Node root) {\n printNodes(root, 0);\n }\n\n static void printNodes(Node node, int indentLevel) {\n\n printNode(node, indentLevel);\n // recurse\n for (Node child : node.getChildren()) {\n printNodes(child, indentLevel + 1);\n }\n }\n\n static void printNode(Node node, int indentLevel) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i &lt; indentLevel; i++) {\n sb.append(\"\\t\");\n }\n sb.append(node);\n\n System.out.println(sb.toString());\n }\n\n public static void main(String[] args) {\n\n // setup dummy data\n List&lt;Map&lt;String, String&gt;&gt; resultSet = new ArrayList&lt;Map&lt;String, String&gt;&gt;();\n resultSet.add(newMap(\"1\", \"Node 1\", \"0\"));\n resultSet.add(newMap(\"2\", \"Node 1.1\", \"1\"));\n resultSet.add(newMap(\"3\", \"Node 2\", \"0\"));\n resultSet.add(newMap(\"4\", \"Node 1.1.1\", \"2\"));\n resultSet.add(newMap(\"5\", \"Node 2.1\", \"3\"));\n resultSet.add(newMap(\"6\", \"Node 1.2\", \"1\"));\n\n Node root = NodeBuilder.build(resultSet);\n printRootNode(root);\n\n }\n\n //convenience method for creating our dummy data\n private static Map&lt;String, String&gt; newMap(String id, String name, String parentId) {\n Map&lt;String, String&gt; row = new HashMap&lt;String, String&gt;();\n row.put(\"id\", id);\n row.put(\"name\", name);\n row.put(\"parent\", parentId);\n return row;\n }\n}\n</code></pre>\n" }, { "answer_id": 192603, "author": "Newtopian", "author_id": 25812, "author_profile": "https://Stackoverflow.com/users/25812", "pm_score": 1, "selected": false, "text": "<p>To Extend Bill's SQL solution you can basically do the same using a flat array. Further more if your strings all have the same lenght and your maximum number of children are known (say in a binary tree) you can do it using a single string (character array). If you have arbitrary number of children this complicates things a bit... I would have to check my old notes to see what can be done.</p>\n\n<p>Then, sacrificing a bit of memory, especially if your tree is sparse and/or unballanced, you can, with a bit of index math, access all the strings randomly by storing your tree, width first in the array like so (for a binary tree):</p>\n\n<pre><code>String[] nodeArray = [L0root, L1child1, L1child2, L2Child1, L2Child2, L2Child3, L2Child4] ...\n</code></pre>\n\n<p>yo know your string length, you know it\n\n<p>I'm at work now so cannot spend much time on it but with interest I can fetch a bit of code to do this. </p>\n\n<p>We use to do it to search in binary trees made of DNA codons, a process built the tree, then we flattened it to search text patterns and when found, though index math (revers from above) we get the node back... very fast and efficient, tough our tree rarely had empty nodes, but we could searh gigabytes of data in a jiffy.</p>\n" }, { "answer_id": 192874, "author": "Eric Weilnau", "author_id": 13342, "author_profile": "https://Stackoverflow.com/users/13342", "pm_score": 4, "selected": false, "text": "<p>As of Oracle 9i, you can use CONNECT BY.</p>\n\n<pre><code>SELECT LPAD(' ', (LEVEL - 1) * 4) || \"Name\" AS \"Name\"\nFROM (SELECT * FROM TMP_NODE ORDER BY \"Order\")\nCONNECT BY PRIOR \"Id\" = \"ParentId\"\nSTART WITH \"Id\" IN (SELECT \"Id\" FROM TMP_NODE WHERE \"ParentId\" = 0)\n</code></pre>\n\n<p>As of SQL Server 2005, you can use a recursive common table expression (CTE).</p>\n\n<pre><code>WITH [NodeList] (\n [Id]\n , [ParentId]\n , [Level]\n , [Order]\n) AS (\n SELECT [Node].[Id]\n , [Node].[ParentId]\n , 0 AS [Level]\n , CONVERT([varchar](MAX), [Node].[Order]) AS [Order]\n FROM [Node]\n WHERE [Node].[ParentId] = 0\n UNION ALL\n SELECT [Node].[Id]\n , [Node].[ParentId]\n , [NodeList].[Level] + 1 AS [Level]\n , [NodeList].[Order] + '|'\n + CONVERT([varchar](MAX), [Node].[Order]) AS [Order]\n FROM [Node]\n INNER JOIN [NodeList] ON [NodeList].[Id] = [Node].[ParentId]\n) SELECT REPLICATE(' ', [NodeList].[Level] * 4) + [Node].[Name] AS [Name]\nFROM [Node]\n INNER JOIN [NodeList] ON [NodeList].[Id] = [Node].[Id]\nORDER BY [NodeList].[Order]\n</code></pre>\n\n<p>Both will output the following results.</p>\n\n<pre>\nName\n'Node 1'\n' Node 1.1'\n' Node 1.1.1'\n' Node 1.2'\n'Node 2'\n' Node 2.1'\n</pre>\n" }, { "answer_id": 193140, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 0, "selected": false, "text": "<p>If elements are in tree order, as shown in your example, you can use something like the following Python example:</p>\n\n<pre><code>delimiter = '.'\nstack = []\nfor item in items:\n while stack and not item.startswith(stack[-1]+delimiter):\n print \"&lt;/div&gt;\"\n stack.pop()\n print \"&lt;div&gt;\"\n print item\n stack.append(item)\n</code></pre>\n\n<p>What this does is maintain a stack representing the current position in the tree. For each element in the table, it pops stack elements (closing the matching divs) until it finds the parent of the current item. Then it outputs the start of that node and pushes it to the stack.</p>\n\n<p>If you want to output the tree using indenting rather than nested elements, you can simply skip the print statements to print the divs, and print a number of spaces equal to some multiple of the size of the stack before each item. For example, in Python:</p>\n\n<pre><code>print \" \" * len(stack)\n</code></pre>\n\n<p>You could also easily use this method to construct a set of nested lists or dictionaries.</p>\n\n<p>Edit: I see from your clarification that the names were not intended to be node paths. That suggests an alternate approach:</p>\n\n<pre><code>idx = {}\nidx[0] = []\nfor node in results:\n child_list = []\n idx[node.Id] = child_list\n idx[node.ParentId].append((node, child_list))\n</code></pre>\n\n<p>This constructs a tree of arrays of tuples(!). idx[0] represents the root(s) of the tree. Each element in an array is a 2-tuple consisting of the node itself and a list of all its children. Once constructed, you can hold on to idx[0] and discard idx, unless you want to access nodes by their ID.</p>\n" }, { "answer_id": 194031, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 6, "selected": false, "text": "<p>If you use nested sets (sometimes referred to as Modified Pre-order Tree Traversal) you can extract the entire tree structure or any subtree within it in tree order with a single query, at the cost of inserts being more expensive, as you need to manage columns which describe an in-order path through thee tree structure.</p>\n\n<p>For <a href=\"http://code.google.com/p/django-mptt/\" rel=\"noreferrer\">django-mptt</a>, I used a structure like this:</p>\n\n<pre>\nid parent_id tree_id level lft rght\n-- --------- ------- ----- --- ----\n 1 null 1 0 1 14\n 2 1 1 1 2 7\n 3 2 1 2 3 4\n 4 2 1 2 5 6\n 5 1 1 1 8 13\n 6 5 1 2 9 10\n 7 5 1 2 11 12\n</pre>\n\n<p>Which describes a tree which looks like this (with <code>id</code> representing each item):</p>\n\n<pre>\n 1\n +-- 2\n | +-- 3\n | +-- 4\n |\n +-- 5\n +-- 6\n +-- 7\n</pre>\n\n<p>Or, as a nested set diagram which makes it more obvious how the <code>lft</code> and <code>rght</code> values work:</p>\n\n<pre>\n __________________________________________________________________________\n| Root 1 |\n| ________________________________ ________________________________ |\n| | Child 1.1 | | Child 1.2 | |\n| | ___________ ___________ | | ___________ ___________ | |\n| | | C 1.1.1 | | C 1.1.2 | | | | C 1.2.1 | | C 1.2.2 | | |\n1 2 3___________4 5___________6 7 8 9___________10 11__________12 13 14\n| |________________________________| |________________________________| |\n|__________________________________________________________________________|\n</pre>\n\n<p>As you can see, to get the entire subtree for a given node, in tree order, you simply have to select all rows which have <code>lft</code> and <code>rght</code> values between its <code>lft</code> and <code>rght</code> values. It's also simple to retrieve the tree of ancestors for a given node.</p>\n\n<p>The <code>level</code> column is a bit of denormalisation for convenience more than anything and the <code>tree_id</code> column allows you to restart the <code>lft</code> and <code>rght</code> numbering for each top-level node, which reduces the number of columns affected by inserts, moves and deletions, as the <code>lft</code> and <code>rght</code> columns have to be adjusted accordingly when these operations take place in order to create or close gaps. I made some <a href=\"http://code.google.com/p/django-mptt/source/browse/trunk/NOTES\" rel=\"noreferrer\">development notes</a> at the time when I was trying to wrap my head around the queries required for each operation.</p>\n\n<p>In terms of actually working with this data to display a tree, I created a <a href=\"http://code.google.com/p/django-mptt/source/browse/trunk/mptt/utils.py#29\" rel=\"noreferrer\"><code>tree_item_iterator</code></a> utility function which, for each node, should give you sufficient information to generate whatever kind of display you want.</p>\n\n<p>More info about MPTT:</p>\n\n<ul>\n<li><a href=\"http://www.intelligententerprise.com/001020/celko.jhtml\" rel=\"noreferrer\">Trees in SQL</a></li>\n<li><a href=\"http://www.sitepoint.com/print/hierarchical-data-database\" rel=\"noreferrer\">Storing Hierarchical Data in a Database</a></li>\n<li><a href=\"http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/\" rel=\"noreferrer\">Managing Hierarchical Data in MySQL</a></li>\n</ul>\n" }, { "answer_id": 4506178, "author": "bobobobo", "author_id": 111307, "author_profile": "https://Stackoverflow.com/users/111307", "pm_score": 3, "selected": false, "text": "<p>Bill's answer is pretty gosh-darned good, this answer adds some things to it which makes me wish SO supported threaded answers.</p>\n\n<p>Anyway I wanted to support the tree structure and the Order property. I included a single property in each Node called <code>leftSibling</code> that does the same thing <code>Order</code> is meant to do in the original question (maintain left-to-right order).</p>\n\n<pre>\nmysql> desc nodes ;\n+-------------+--------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+-------------+--------------+------+-----+---------+----------------+\n| id | int(11) | NO | PRI | NULL | auto_increment |\n| name | varchar(255) | YES | | NULL | |\n| leftSibling | int(11) | NO | | 0 | |\n+-------------+--------------+------+-----+---------+----------------+\n3 rows in set (0.00 sec)\n\nmysql> desc adjacencies;\n+------------+---------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+------------+---------+------+-----+---------+----------------+\n| relationId | int(11) | NO | PRI | NULL | auto_increment |\n| parent | int(11) | NO | | NULL | |\n| child | int(11) | NO | | NULL | |\n| pathLen | int(11) | NO | | NULL | |\n+------------+---------+------+-----+---------+----------------+\n4 rows in set (0.00 sec)\n</pre>\n\n<p><a href=\"http://bobobobo.wordpress.com/2010/12/22/closure-table-part-deux-nodes-and-adjacencies-a-tree-in-mysql/\" rel=\"noreferrer\">More detail and SQL code on my blog</a>.</p>\n\n<p>Thanks Bill your answer was helpful in getting started!</p>\n" }, { "answer_id": 13568284, "author": "sreenivasulu kandakuru", "author_id": 1745584, "author_profile": "https://Stackoverflow.com/users/1745584", "pm_score": 0, "selected": false, "text": "<p>Think about using nosql tools like neo4j for hierarchial structures. \ne.g a networked application like linkedin uses couchbase (another nosql solution)</p>\n\n<p>But use nosql only for data-mart level queries and not to store / maintain transactions</p>\n" }, { "answer_id": 22376973, "author": "Michał Kołodziejski", "author_id": 3350927, "author_profile": "https://Stackoverflow.com/users/3350927", "pm_score": 5, "selected": false, "text": "<p>It's a quite old question, but as it's got many views I think it's worth to present an alternative, and in my opinion very elegant, solution.</p>\n<p>In order to read a tree structure you can use <strong>recursive Common Table Expressions</strong> (CTEs). It gives a possibility to fetch whole tree structure at once, have the information about the level of the node, its parent node and order within children of the parent node.</p>\n<p>Let me show you how this would work in PostgreSQL 9.1.</p>\n<ol>\n<li><p>Create a structure</p>\n<pre><code>CREATE TABLE tree (\n id int NOT NULL,\n name varchar(32) NOT NULL,\n parent_id int NULL,\n node_order int NOT NULL,\n CONSTRAINT tree_pk PRIMARY KEY (id),\n CONSTRAINT tree_tree_fk FOREIGN KEY (parent_id) \n REFERENCES tree (id) NOT DEFERRABLE\n);\n\n\ninsert into tree values\n (0, 'ROOT', NULL, 0),\n (1, 'Node 1', 0, 10),\n (2, 'Node 1.1', 1, 10),\n (3, 'Node 2', 0, 20),\n (4, 'Node 1.1.1', 2, 10),\n (5, 'Node 2.1', 3, 10),\n (6, 'Node 1.2', 1, 20);\n</code></pre>\n</li>\n<li><p>Write a query</p>\n<pre><code>WITH RECURSIVE \ntree_search (id, name, level, parent_id, node_order) AS (\n SELECT \n id, \n name,\n 0,\n parent_id, \n 1 \n FROM tree\n WHERE parent_id is NULL\n\n UNION ALL \n SELECT \n t.id, \n t.name,\n ts.level + 1, \n ts.id, \n t.node_order \n FROM tree t, tree_search ts \n WHERE t.parent_id = ts.id \n) \nSELECT * FROM tree_search \nWHERE level &gt; 0 \nORDER BY level, parent_id, node_order;\n</code></pre>\n</li>\n</ol>\n<p>Here are the results:</p>\n<pre><code> id | name | level | parent_id | node_order \n ----+------------+-------+-----------+------------\n 1 | Node 1 | 1 | 0 | 10\n 3 | Node 2 | 1 | 0 | 20\n 2 | Node 1.1 | 2 | 1 | 10\n 6 | Node 1.2 | 2 | 1 | 20\n 5 | Node 2.1 | 2 | 3 | 10\n 4 | Node 1.1.1 | 3 | 2 | 10\n (6 rows)\n</code></pre>\n<p>The tree nodes are ordered by a level of depth. In the final output we would present them in the subsequent lines.</p>\n<p>For each level, they are ordered by parent_id and node_order within the parent. This tells us how to present them in the output - link node to the parent in this order.</p>\n<p>Having such a structure it wouldn't be difficult to make a really nice presentation in HTML.</p>\n<p>Recursive CTEs are available in <strong>PostgreSQL, IBM DB2, MS SQL Server, Oracle and SQLite</strong>.</p>\n<p>If you'd like to read more on recursive SQL queries, you can either check the documentation of your favourite DBMS or read my two articles covering this topic:</p>\n<ul>\n<li><a href=\"http://www.vertabelo.com/blog/do-it-in-sql-recursive-tree-traversal\" rel=\"nofollow noreferrer\">Do It In SQL: Recursive Tree Traversal </a></li>\n<li><a href=\"http://www.vertabelo.com/blog/sql-recursive-queries\" rel=\"nofollow noreferrer\">Get to know the power of SQL recursive queries</a></li>\n</ul>\n" }, { "answer_id": 42781302, "author": "Konchog", "author_id": 5678653, "author_profile": "https://Stackoverflow.com/users/5678653", "pm_score": 3, "selected": false, "text": "<p>There are really good solutions which exploit the internal btree representation of sql indices. This is based on some great research done back around 1998.</p>\n<p>Here is an example table (in mysql).</p>\n<pre><code>CREATE TABLE `node` (\n `id` int(10) unsigned NOT NULL AUTO_INCREMENT,\n `name` varchar(255) NOT NULL,\n `tw` int(10) unsigned NOT NULL,\n `pa` int(10) unsigned DEFAULT NULL,\n `sz` int(10) unsigned DEFAULT NULL,\n `nc` int(11) GENERATED ALWAYS AS (tw+sz) STORED,\n PRIMARY KEY (`id`),\n KEY `node_tw_index` (`tw`),\n KEY `node_pa_index` (`pa`),\n KEY `node_nc_index` (`nc`),\n CONSTRAINT `node_pa_fk` FOREIGN KEY (`pa`) REFERENCES `node` (`tw`) ON DELETE CASCADE\n)\n</code></pre>\n<p>The only fields necessary for the tree representation are:</p>\n<ul>\n<li>tw: The Left to Right DFS Pre-order index, where root = 1.</li>\n<li>pa: The reference (using tw) to the parent node, root has null.</li>\n<li>sz: The size of the node's branch including itself.</li>\n<li>nc: is used as syntactic sugar. it is tw+sz and represents the tw of the node's &quot;next child&quot;.</li>\n</ul>\n<p>Here is an example 24 node population, ordered by tw:</p>\n<pre><code>+-----+---------+----+------+------+------+\n| id | name | tw | pa | sz | nc |\n+-----+---------+----+------+------+------+\n| 1 | Root | 1 | NULL | 24 | 25 |\n| 2 | A | 2 | 1 | 14 | 16 |\n| 3 | AA | 3 | 2 | 1 | 4 |\n| 4 | AB | 4 | 2 | 7 | 11 |\n| 5 | ABA | 5 | 4 | 1 | 6 |\n| 6 | ABB | 6 | 4 | 3 | 9 |\n| 7 | ABBA | 7 | 6 | 1 | 8 |\n| 8 | ABBB | 8 | 6 | 1 | 9 |\n| 9 | ABC | 9 | 4 | 2 | 11 |\n| 10 | ABCD | 10 | 9 | 1 | 11 |\n| 11 | AC | 11 | 2 | 4 | 15 |\n| 12 | ACA | 12 | 11 | 2 | 14 |\n| 13 | ACAA | 13 | 12 | 1 | 14 |\n| 14 | ACB | 14 | 11 | 1 | 15 |\n| 15 | AD | 15 | 2 | 1 | 16 |\n| 16 | B | 16 | 1 | 1 | 17 |\n| 17 | C | 17 | 1 | 6 | 23 |\n| 359 | C0 | 18 | 17 | 5 | 23 |\n| 360 | C1 | 19 | 18 | 4 | 23 |\n| 361 | C2(res) | 20 | 19 | 3 | 23 |\n| 362 | C3 | 21 | 20 | 2 | 23 |\n| 363 | C4 | 22 | 21 | 1 | 23 |\n| 18 | D | 23 | 1 | 1 | 24 |\n| 19 | E | 24 | 1 | 1 | 25 |\n+-----+---------+----+------+------+------+\n</code></pre>\n<p>Every tree result can be done non-recursively.\nFor instance, to get a list of ancestors of node at tw='22'</p>\n<p><strong>Ancestors</strong></p>\n<pre><code>select anc.* from node me,node anc \nwhere me.tw=22 and anc.nc &gt;= me.tw and anc.tw &lt;= me.tw \norder by anc.tw;\n+-----+---------+----+------+------+------+\n| id | name | tw | pa | sz | nc |\n+-----+---------+----+------+------+------+\n| 1 | Root | 1 | NULL | 24 | 25 |\n| 17 | C | 17 | 1 | 6 | 23 |\n| 359 | C0 | 18 | 17 | 5 | 23 |\n| 360 | C1 | 19 | 18 | 4 | 23 |\n| 361 | C2(res) | 20 | 19 | 3 | 23 |\n| 362 | C3 | 21 | 20 | 2 | 23 |\n| 363 | C4 | 22 | 21 | 1 | 23 |\n+-----+---------+----+------+------+------+\n</code></pre>\n<p>Siblings and children are trivial - just use pa field ordering by tw.</p>\n<p><strong>Descendants</strong></p>\n<p>For example the set (branch) of nodes that are rooted at tw = 17.</p>\n<pre><code>select des.* from node me,node des \nwhere me.tw=17 and des.tw &lt; me.nc and des.tw &gt;= me.tw \norder by des.tw;\n+-----+---------+----+------+------+------+\n| id | name | tw | pa | sz | nc |\n+-----+---------+----+------+------+------+\n| 17 | C | 17 | 1 | 6 | 23 |\n| 359 | C0 | 18 | 17 | 5 | 23 |\n| 360 | C1 | 19 | 18 | 4 | 23 |\n| 361 | C2(res) | 20 | 19 | 3 | 23 |\n| 362 | C3 | 21 | 20 | 2 | 23 |\n| 363 | C4 | 22 | 21 | 1 | 23 |\n+-----+---------+----+------+------+------+\n</code></pre>\n<p><strong>Additional Notes</strong></p>\n<p>This methodology is extremely useful for when there are a far greater number of reads than there are inserts or updates.</p>\n<p>Because the insertion, movement, or updating of a node in the tree requires the tree to be adjusted, it is necessary to lock the table before commencing with the action.</p>\n<p>The insertion/deletion cost is high because the tw index and sz (branch size) values will need to be updated on all the nodes after the insertion point, and for all ancestors respectively.</p>\n<p>Branch moving involves moving the tw value of the branch out of range, so it is also necessary to disable foreign key constraints when moving a branch. There are, essentially four queries required to move a branch:</p>\n<ul>\n<li>Move the branch out of range.</li>\n<li>Close the gap that it left. (the remaining tree is now normalised).</li>\n<li>Open the gap where it will go to.</li>\n<li>Move the branch into it's new position.</li>\n</ul>\n<p><strong>Adjust Tree Queries</strong></p>\n<p>The opening/closing of gaps in the tree is an important sub-function used by create/update/delete methods, so I include it here.</p>\n<p>We need two parameters - a flag representing whether or not we are downsizing or upsizing, and the node's tw index. So, for example tw=18 (which has a branch size of 5). Let's assume that we are downsizing (removing tw) - this means that we are using '-' instead of '+' in the updates of the following example.</p>\n<p>We first use a (slightly altered) ancestor function to update the sz value.</p>\n<pre><code>update node me, node anc set anc.sz = anc.sz - me.sz from \nnode me, node anc where me.tw=18 \nand ((anc.nc &gt;= me.tw and anc.tw &lt; me.pa) or (anc.tw=me.pa));\n</code></pre>\n<p>Then we need to adjust the tw for those whose tw is higher than the branch to be removed.</p>\n<pre><code>update node me, node anc set anc.tw = anc.tw - me.sz from \nnode me, node anc where me.tw=18 and anc.tw &gt;= me.tw;\n</code></pre>\n<p>Then we need to adjust the parent for those whose pa's tw is higher than the branch to be removed.</p>\n<pre><code>update node me, node anc set anc.pa = anc.pa - me.sz from \nnode me, node anc where me.tw=18 and anc.pa &gt;= me.tw;\n</code></pre>\n" }, { "answer_id": 73741684, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 1, "selected": false, "text": "<p><strong>Pre-order transversal with on-the-fly path enumeration on adjacency representation</strong></p>\n<p>Nested sets from:</p>\n<ul>\n<li>Konchog <a href=\"https://stackoverflow.com/a/42781302/895245\">https://stackoverflow.com/a/42781302/895245</a></li>\n<li>Jonny Buchanan <a href=\"https://stackoverflow.com/a/194031/895245\">https://stackoverflow.com/a/194031/895245</a></li>\n</ul>\n<p>is the only efficient way I've seen of traversing, at the cost of slower updates. That's likely what most people will want for pre-order.</p>\n<p>Closure table from <a href=\"https://stackoverflow.com/a/192462/895245\">https://stackoverflow.com/a/192462/895245</a> is interesting, but I don't see how to enforce pre-order there: <a href=\"https://stackoverflow.com/questions/8252323/mysql-closure-table-hierarchical-database-how-to-pull-information-out-in-the-c\">MySQL Closure Table hierarchical database - How to pull information out in the correct order</a></p>\n<p>Mostly for fun, here's a method that recursively calculates the 1.3.2.5. prefixes on the fly and sorts by them at the end, based only on the parent ID/child index representation.</p>\n<p>Upsides:</p>\n<ul>\n<li>updates only need to update the indexes of each sibling</li>\n</ul>\n<p>Downsides:</p>\n<ul>\n<li>n^2 memory usage worst case for a super deep tree. This could be quite serious, which is why I say this method is likely mostly for fun only. But maybe there is some ultra high update case where someone would want to use it? Who knows</li>\n<li>recursive queries, so reads are going to be less efficient than nested sets</li>\n</ul>\n<p>Create and populate table:</p>\n<pre><code>CREATE TABLE &quot;ParentIndexTree&quot; (\n &quot;id&quot; INTEGER PRIMARY KEY,\n &quot;parentId&quot; INTEGER,\n &quot;childIndex&quot; INTEGER NOT NULL,\n &quot;value&quot; INTEGER NOT NULL,\n &quot;name&quot; TEXT NOT NULL,\n FOREIGN KEY (&quot;parentId&quot;) REFERENCES &quot;ParentIndexTree&quot;(id)\n)\n;\nINSERT INTO &quot;ParentIndexTree&quot; VALUES\n (0, NULL, 0, 1, 'one' ),\n (1, 0, 0, 2, 'two' ),\n (2, 0, 1, 3, 'three'),\n (3, 1, 0, 4, 'four' ),\n (4, 1, 1, 5, 'five' )\n;\n</code></pre>\n<p>Represented tree:</p>\n<pre><code> 1\n / \\\n 2 3\n / \\\n4 5\n</code></pre>\n<p>Then for a DBMS with arrays like PostgreSQL](<a href=\"https://www.postgresql.org/docs/14/arrays.html\" rel=\"nofollow noreferrer\">https://www.postgresql.org/docs/14/arrays.html</a>):</p>\n<pre><code>WITH RECURSIVE &quot;TreeSearch&quot; (\n &quot;id&quot;,\n &quot;parentId&quot;,\n &quot;childIndex&quot;,\n &quot;value&quot;,\n &quot;name&quot;,\n &quot;prefix&quot;\n) AS (\n SELECT\n &quot;id&quot;,\n &quot;parentId&quot;,\n &quot;childIndex&quot;,\n &quot;value&quot;,\n &quot;name&quot;,\n array[0]\n FROM &quot;ParentIndexTree&quot;\n WHERE &quot;parentId&quot; IS NULL\n\n UNION ALL\n\n SELECT\n &quot;child&quot;.&quot;id&quot;,\n &quot;child&quot;.&quot;parentId&quot;,\n &quot;child&quot;.&quot;childIndex&quot;,\n &quot;child&quot;.&quot;value&quot;,\n &quot;child&quot;.&quot;name&quot;,\n array_append(&quot;parent&quot;.&quot;prefix&quot;, &quot;child&quot;.&quot;childIndex&quot;)\n FROM &quot;ParentIndexTree&quot; AS &quot;child&quot;\n JOIN &quot;TreeSearch&quot; AS &quot;parent&quot;\n ON &quot;child&quot;.&quot;parentId&quot; = &quot;parent&quot;.&quot;id&quot;\n)\nSELECT * FROM &quot;TreeSearch&quot;\nORDER BY &quot;prefix&quot;\n;\n</code></pre>\n<p>This creates on the fly prefixes of form:</p>\n<pre><code>1 -&gt; 0\n2 -&gt; 0, 0\n3 -&gt; 0, 1\n4 -&gt; 0, 0, 0\n5 -&gt; 0, 0, 1\n</code></pre>\n<p>and then PostgreSQL then sorts by the arrays alphabetically as:</p>\n<pre><code>1 -&gt; 0\n2 -&gt; 0, 0\n4 -&gt; 0, 0, 0\n5 -&gt; 0, 0, 1\n3 -&gt; 0, 1\n</code></pre>\n<p>which is the pre-order result that we want.</p>\n<p>For a DBMS without arrays like SQLite, you can hack by encoding the prefix with a string of fixed width integers. Binary would be ideal, but I couldn't find out how, so hex would work. This of course means you will have to select a maximum depth that will fit in the number of bytes selected, e.g. below I choose 6 allowing for a maximum of 16^6 children per node.</p>\n<pre><code>WITH RECURSIVE &quot;TreeSearch&quot; (\n &quot;id&quot;,\n &quot;parentId&quot;,\n &quot;childIndex&quot;,\n &quot;value&quot;,\n &quot;name&quot;,\n &quot;prefix&quot;\n) AS (\n SELECT\n &quot;id&quot;,\n &quot;parentId&quot;,\n &quot;childIndex&quot;,\n &quot;value&quot;,\n &quot;name&quot;,\n '000000'\n FROM &quot;ParentIndexTree&quot;\n WHERE &quot;parentId&quot; IS NULL\n\n UNION ALL\n\n SELECT\n &quot;child&quot;.&quot;id&quot;,\n &quot;child&quot;.&quot;parentId&quot;,\n &quot;child&quot;.&quot;childIndex&quot;,\n &quot;child&quot;.&quot;value&quot;,\n &quot;child&quot;.&quot;name&quot;,\n &quot;parent&quot;.&quot;prefix&quot; || printf('%06x', &quot;child&quot;.&quot;childIndex&quot;)\n FROM &quot;ParentIndexTree&quot; AS &quot;child&quot;\n JOIN &quot;TreeSearch&quot; AS &quot;parent&quot;\n ON &quot;child&quot;.&quot;parentId&quot; = &quot;parent&quot;.&quot;id&quot;\n)\nSELECT * FROM &quot;TreeSearch&quot;\nORDER BY &quot;prefix&quot;\n;\n</code></pre>\n<p><strong>Some nested set notes</strong></p>\n<p>Here are a few points which confused me a bit after looking at the other nested set answers.</p>\n<p>Jonny Buchanan shows his nested set setup as:</p>\n<pre><code>__________________________________________________________________________\n| Root 1 |\n| ________________________________ ________________________________ |\n| | Child 1.1 | | Child 1.2 | |\n| | ___________ ___________ | | ___________ ___________ | |\n| | | C 1.1.1 | | C 1.1.2 | | | | C 1.2.1 | | C 1.2.2 | | |\n1 2 3___________4 5___________6 7 8 9___________10 11__________12 13 14\n| |________________________________| |________________________________| |\n|__________________________________________________________________________|\n</code></pre>\n<p>which made me wonder why not just use the simpler looking:</p>\n<pre><code>__________________________________________________________________________\n| Root 1 |\n| ________________________________ _______________________________ |\n| | Child 1.1 | | Child 1.2 | |\n| | ___________ ___________ | | ___________ ___________ | |\n| | | C 1.1.1 | | C 1.1.2 | | | | C 1.2.1 | | C 1.2.2 | | |\n1 2 3___________| 4___________| | 5 6___________| 7___________| | | \n| |________________________________| |_______________________________| |\n|_________________________________________________________________________|\n</code></pre>\n<p>which does not have an extra number for each endpoint.</p>\n<p>But then when I actually tried to implement it, I noticed that it was hard/impossible to implement the update queries like that, unless I had parent information as used by Konchog. The problem is that it was hard/impossible to distinguish between a sibling and a parent in one case while the tree was being moved around, and I needed that to decide if I was going to reduce the right hand side or not while closing a gap.</p>\n<p>Left/size vs left/right: you could store it either way in the database, but I think left/right can be more efficient as you can index the DB with a multicolumn index (left, right) which can then be used to speed up ancestor queries, which are of type:</p>\n<pre><code>left &lt; curLeft AND right &gt; curLeft\n</code></pre>\n<p>Tested on Ubuntu 22.04, PostgreSQL 14.5, SQLite 3.34.0.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192220", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18771/" ]
Assume you have a flat table that stores an ordered tree hierarchy: ``` Id Name ParentId Order 1 'Node 1' 0 10 2 'Node 1.1' 1 10 3 'Node 2' 0 20 4 'Node 1.1.1' 2 10 5 'Node 2.1' 3 10 6 'Node 1.2' 1 20 ``` Here's a diagram, where we have `[id] Name`. Root node 0 is fictional. ``` [0] ROOT / \ [1] Node 1 [3] Node 2 / \ \ [2] Node 1.1 [6] Node 1.2 [5] Node 2.1 / [4] Node 1.1.1 ``` What minimalistic approach would you use to output that to HTML (or text, for that matter) as a correctly ordered, correctly indented tree? Assume further you only have basic data structures (arrays and hashmaps), no fancy objects with parent/children references, no ORM, no framework, just your two hands. The table is represented as a result set, which can be accessed randomly. Pseudo code or plain English is okay, this is purely a conceptional question. Bonus question: Is there a fundamentally better way to store a tree structure like this in a RDBMS? --- **EDITS AND ADDITIONS** To answer one commenter's ([Mark Bessey](https://stackoverflow.com/users/17826/mark-bessey)'s) question: A root node is not necessary, because it is never going to be displayed anyway. ParentId = 0 is the convention to express "these are top level". The Order column defines how nodes with the same parent are going to be sorted. The "result set" I spoke of can be pictured as an array of hashmaps (to stay in that terminology). For my example was meant to be already there. Some answers go the extra mile and construct it first, but thats okay. The tree can be arbitrarily deep. Each node can have N children. I did not exactly have a "millions of entries" tree in mind, though. Don't mistake my choice of node naming ('Node 1.1.1') for something to rely on. The nodes could equally well be called 'Frank' or 'Bob', no naming structure is implied, this was merely to make it readable. *I have posted my own solution so you guys can pull it to pieces.*
Now that [MySQL 8.0 supports recursive queries](https://dev.mysql.com/doc/refman/8.0/en/with.html), we can say that [all popular SQL databases support recursive queries](https://stackoverflow.com/questions/324935/mysql-with-clause/325243#325243) in standard syntax. ``` WITH RECURSIVE MyTree AS ( SELECT * FROM MyTable WHERE ParentId IS NULL UNION ALL SELECT m.* FROM MyTABLE AS m JOIN MyTree AS t ON m.ParentId = t.Id ) SELECT * FROM MyTree; ``` I tested recursive queries in MySQL 8.0 in my presentation [Recursive Query Throwdown](https://www.slideshare.net/billkarwin/recursive-query-throwdown) in 2017. Below is my original answer from 2008: --- There are several ways to store tree-structured data in a relational database. What you show in your example uses two methods: * **Adjacency List** (the "parent" column) and * **Path Enumeration** (the dotted-numbers in your name column). Another solution is called **Nested Sets**, and it can be stored in the same table too. Read "[Trees and Hierarchies in SQL for Smarties](https://rads.stackoverflow.com/amzn/click/com/1558609202)" by Joe Celko for a lot more information on these designs. I usually prefer a design called **Closure Table** (aka "Adjacency Relation") for storing tree-structured data. It requires another table, but then querying trees is pretty easy. I cover Closure Table in my presentation [Models for Hierarchical Data with SQL and PHP](http://www.slideshare.net/billkarwin/models-for-hierarchical-data) and in my book [SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming](https://pragprog.com/titles/bksap1/sql-antipatterns-volume-1/). ``` CREATE TABLE ClosureTable ( ancestor_id INT NOT NULL REFERENCES FlatTable(id), descendant_id INT NOT NULL REFERENCES FlatTable(id), PRIMARY KEY (ancestor_id, descendant_id) ); ``` Store all paths in the Closure Table, where there is a direct ancestry from one node to another. Include a row for each node to reference itself. For example, using the data set you showed in your question: ``` INSERT INTO ClosureTable (ancestor_id, descendant_id) VALUES (1,1), (1,2), (1,4), (1,6), (2,2), (2,4), (3,3), (3,5), (4,4), (5,5), (6,6); ``` Now you can get a tree starting at node 1 like this: ``` SELECT f.* FROM FlatTable f JOIN ClosureTable a ON (f.id = a.descendant_id) WHERE a.ancestor_id = 1; ``` The output (in MySQL client) looks like the following: ``` +----+ | id | +----+ | 1 | | 2 | | 4 | | 6 | +----+ ``` In other words, nodes 3 and 5 are excluded, because they're part of a separate hierarchy, not descending from node 1. --- Re: comment from e-satis about immediate children (or immediate parent). You can add a "`path_length`" column to the `ClosureTable` to make it easier to query specifically for an immediate child or parent (or any other distance). ``` INSERT INTO ClosureTable (ancestor_id, descendant_id, path_length) VALUES (1,1,0), (1,2,1), (1,4,2), (1,6,1), (2,2,0), (2,4,1), (3,3,0), (3,5,1), (4,4,0), (5,5,0), (6,6,0); ``` Then you can add a term in your search for querying the immediate children of a given node. These are descendants whose `path_length` is 1. ``` SELECT f.* FROM FlatTable f JOIN ClosureTable a ON (f.id = a.descendant_id) WHERE a.ancestor_id = 1 AND path_length = 1; +----+ | id | +----+ | 2 | | 6 | +----+ ``` --- Re comment from @ashraf: "How about sorting the whole tree [by name]?" Here's an example query to return all nodes that are descendants of node 1, join them to the FlatTable that contains other node attributes such as `name`, and sort by the name. ``` SELECT f.name FROM FlatTable f JOIN ClosureTable a ON (f.id = a.descendant_id) WHERE a.ancestor_id = 1 ORDER BY f.name; ``` --- Re comment from @Nate: ``` SELECT f.name, GROUP_CONCAT(b.ancestor_id order by b.path_length desc) AS breadcrumbs FROM FlatTable f JOIN ClosureTable a ON (f.id = a.descendant_id) JOIN ClosureTable b ON (b.descendant_id = a.descendant_id) WHERE a.ancestor_id = 1 GROUP BY a.descendant_id ORDER BY f.name +------------+-------------+ | name | breadcrumbs | +------------+-------------+ | Node 1 | 1 | | Node 1.1 | 1,2 | | Node 1.1.1 | 1,2,4 | | Node 1.2 | 1,6 | +------------+-------------+ ``` --- A user suggested an edit today. SO moderators approved the edit, but I am reversing it. The edit suggested that the ORDER BY in the last query above should be `ORDER BY b.path_length, f.name`, presumably to make sure the ordering matches the hierarchy. But this doesn't work, because it would order "Node 1.1.1" after "Node 1.2". If you want the ordering to match the hierarchy in a sensible way, that is possible, but not simply by ordering by the path length. For example, see my answer to [MySQL Closure Table hierarchical database - How to pull information out in the correct order](https://stackoverflow.com/questions/8252323/mysql-closure-table-hierarchical-database-how-to-pull-information-out-in-the-c).
192,228
<p>I'm not much of a coder, but I need to write a simple <em>preg_replace</em> statement in PHP that will help me with a WordPress plugin. Basically, I need some code that will search for a string, pull out the video ID, and return the embed code with the video id inserted into it. </p> <p>In other words, I'm searching for this: </p> <pre><code>[youtube=http://www.youtube.com/watch?v=VIDEO_ID_HERE&amp;hl=en&amp;fs=1] </code></pre> <p>And want to replace it with this (keeping the video id the same): </p> <pre><code>param name="movie" value="http://www.youtube.com/v/VIDEO_ID_HERE&amp;hl=en&amp;fs=1&amp;rel=0 </code></pre> <p>If possible, I'd be forever grateful if you could explain how you've used the various slashes, carets, and Kleene stars in the search pattern, i.e. translate it from grep to English so I can learn. :-)</p> <p>Thanks!<br> Mike</p>
[ { "answer_id": 192239, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "<pre><code>$str = preg_replace('/\\[youtube=.*?v=([a-z0-9_-]+?)&amp;.*?\\]/i', 'param name=\"movie\" value=\"http://www.youtube.com/v/$1&amp;hl=en&amp;fs=1&amp;rel=0', $str);\n\n / - Start of RE\n \\[ - A literal [ ([ is a special character so it needs escaping)\n youtube= - Make sure we've got the right tag\n .*? - Any old rubbish, but don't be greedy; stop when we reach...\n v= - ...this text\n ([a-z0-9_-]+?) - Take some more text (just z-a 0-9 _ and -), and don't be greedy. Capture it using (). This will get put in $1\n &amp;.*?\\] - the junk up to the ending ]\n /i - end the RE and make it case-insensitive for the hell of it\n</code></pre>\n" }, { "answer_id": 192255, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 0, "selected": false, "text": "<pre><code>$embedString = 'youtube=http://www.youtube.com/watch?v=VIDEO_ID_HERE&amp;hl=en&amp;fs=1';\npreg_match('/v=([^&amp;]*)/',$embedstring,$matches);\necho 'param name=\"movie\" value=\"http://www.youtube.com/v/'.$matches[1].'&amp;hl=en&amp;fs=1&amp;rel=0';\n</code></pre>\n\n<p>Try that.</p>\n\n<p>The regex <code>/v=([^&amp;]*)/</code> works this way:</p>\n\n<ul>\n<li>it searches for <code>v=</code></li>\n<li>it then saves the match to the pattern inside the parentheses to <code>$matches</code></li>\n<li><code>[^&amp;]</code> tells it to match any character <em>except</em> the ampersand ('&amp;')</li>\n<li><code>*</code> tells it we want anywhere from 0 to any number of those characters in the match</li>\n</ul>\n" }, { "answer_id": 192279, "author": "Markus Jarderot", "author_id": 22364, "author_profile": "https://Stackoverflow.com/users/22364", "pm_score": 0, "selected": false, "text": "<p>A warning. If the text after <code>.*?</code> isn't found immediately, the regex engine will continue to search over the whole line, possibly jumping to the next <code>[youtube...]</code> tag. It is often better to use <code>[^\\]]*?</code> to limit the search inside the brackets.</p>\n\n<p>Based on RoBorgs answer:</p>\n\n<pre><code>$str = preg_replace('/\\[youtube=[^\\]]*?v=([^\\]]*?)&amp;[^\\]]*?\\]/i', ...)\n</code></pre>\n\n<p><code>[^\\]]</code> will match any character except <code>']'</code>.</p>\n" }, { "answer_id": 192309, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 3, "selected": false, "text": "<p>BE CAREFUL! If this is a BBCode-style system with user input, these other two solutions would leave you vulnerable to XSS attacks. </p>\n\n<p>You have several ways to protect yourself against this. Have the regex explicitly disallow the characters that could get you in trouble (or, allow only those valid for a youtube video id), or actually sanitize the input and use preg_match instead, which I will illustrate below going off of RoBorg's regex.</p>\n\n<pre><code>&lt;?php\n\n$input = \"[youtube=http://www.youtube.com/watch?v=VIDEO_ID_HERE&amp;hl=en&amp;fs=1]\";\n\nif ( preg_match('/\\[youtube=.*?v=(.*?)&amp;.*?\\]/i', $input, $matches ) )\n{\n $sanitizedVideoId = urlencode( strip_tags( $matches[1] ) );\n echo 'param name=\"movie\" value=\"http://www.youtube.com/v/' . $sanitizedVideoId . '&amp;hl=en&amp;fs=1&amp;rel=0';\n} else {\n // Not valid input\n}\n</code></pre>\n\n<p>Here's an example of this type of attack in action</p>\n\n<pre><code>&lt;?php\n\n$input = \"[youtube=http://www.youtube.com/watch?v=\\\"&gt;&lt;script src=\\\"http://example.com/xss.js\\\"&gt;&lt;/script&gt;&amp;hl=en&amp;fs=1]\";\n\n// Is vulnerable to XSS\necho preg_replace('/\\[youtube=.*?v=(.*?)&amp;.*?\\]/i', 'param name=\"movie\" value=\"http://www.youtube.com/v/$1&amp;hl=en&amp;fs=1&amp;rel=0', $input );\necho \"\\n\";\n\n// Prevents XSS\nif ( preg_match('/\\[youtube=.*?v=(.*?)&amp;.*?\\]/i', $input, $matches ) )\n{\n $sanitizedVideoId = urlencode( strip_tags( $matches[1] ) );\n echo 'param name=\"movie\" value=\"http://www.youtube.com/v/' . $sanitizedVideoId . '&amp;hl=en&amp;fs=1&amp;rel=0';\n} else {\n // Not valid input\n}\n</code></pre>\n" }, { "answer_id": 196364, "author": "Kris", "author_id": 18565, "author_profile": "https://Stackoverflow.com/users/18565", "pm_score": 1, "selected": false, "text": "<p>I would avoind regular expressions in this case if at all possible, because: who guarantees that the querystring in the first url will always be in that format?</p>\n\n<p>i'd use <code>parse_url($originalURL, PHP-URL-QUERY);</code> and then loop through the returned array finding the correct 'name=value' pair for the v part of the query string:\nsomething like:</p>\n\n<pre><code>$originalURL = 'http://www.youtube.com/watch?v=VIDEO_ID_HERE&amp;hl=en&amp;fs=1';\n\nforeach( parse_url( $originalURL, PHP_URL_QUERY) as $keyvalue )\n{\n if ( strlen( $keyvalue ) &gt; 2 &amp;&amp; substr( $keyvalue, 0, 2 ) == 'v=' )\n {\n $videoId = substr( $keyvalue, 2 );\n break;\n }\n}\n\n$newURL = sprintf( 'http://www.youtube.com/v/%s/whatever/else', url_encode( $videoId ) );\n</code></pre>\n\n<p>p.s. written in the SO textbox, untested.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm not much of a coder, but I need to write a simple *preg\_replace* statement in PHP that will help me with a WordPress plugin. Basically, I need some code that will search for a string, pull out the video ID, and return the embed code with the video id inserted into it. In other words, I'm searching for this: ``` [youtube=http://www.youtube.com/watch?v=VIDEO_ID_HERE&hl=en&fs=1] ``` And want to replace it with this (keeping the video id the same): ``` param name="movie" value="http://www.youtube.com/v/VIDEO_ID_HERE&hl=en&fs=1&rel=0 ``` If possible, I'd be forever grateful if you could explain how you've used the various slashes, carets, and Kleene stars in the search pattern, i.e. translate it from grep to English so I can learn. :-) Thanks! Mike
BE CAREFUL! If this is a BBCode-style system with user input, these other two solutions would leave you vulnerable to XSS attacks. You have several ways to protect yourself against this. Have the regex explicitly disallow the characters that could get you in trouble (or, allow only those valid for a youtube video id), or actually sanitize the input and use preg\_match instead, which I will illustrate below going off of RoBorg's regex. ``` <?php $input = "[youtube=http://www.youtube.com/watch?v=VIDEO_ID_HERE&hl=en&fs=1]"; if ( preg_match('/\[youtube=.*?v=(.*?)&.*?\]/i', $input, $matches ) ) { $sanitizedVideoId = urlencode( strip_tags( $matches[1] ) ); echo 'param name="movie" value="http://www.youtube.com/v/' . $sanitizedVideoId . '&hl=en&fs=1&rel=0'; } else { // Not valid input } ``` Here's an example of this type of attack in action ``` <?php $input = "[youtube=http://www.youtube.com/watch?v=\"><script src=\"http://example.com/xss.js\"></script>&hl=en&fs=1]"; // Is vulnerable to XSS echo preg_replace('/\[youtube=.*?v=(.*?)&.*?\]/i', 'param name="movie" value="http://www.youtube.com/v/$1&hl=en&fs=1&rel=0', $input ); echo "\n"; // Prevents XSS if ( preg_match('/\[youtube=.*?v=(.*?)&.*?\]/i', $input, $matches ) ) { $sanitizedVideoId = urlencode( strip_tags( $matches[1] ) ); echo 'param name="movie" value="http://www.youtube.com/v/' . $sanitizedVideoId . '&hl=en&fs=1&rel=0'; } else { // Not valid input } ```
192,241
<p>Good morning everyone, </p> <p>I'm running into an issue using a SharePoint workflow project (C#, VS 2008) and connecting to a database. Here is my database connection string:</p> <pre><code>Data Source=DBSERVER;Initial Catalog=DBNAME;Integrated Security=True; </code></pre> <p>When I attempt to run the following code I get the following error ... </p> <pre><code>SqlConnection dbEngine = new SqlConnection(Constants.DBCONNECTION_STRING); dbEngine.Open(); </code></pre> <p><strong>"Login failed for user 'DOMAIN\MACHINE_NAME$'"</strong> </p> <p>What I need it to do is pass through the logged in user's credentials. I've got impersonation turned on but it doesn't seem to be passing through. Any suggestions would be very much appreciated. </p> <p>Thank you in advance for any advice,</p> <p>Scott Vercuski</p>
[ { "answer_id": 193964, "author": "Nico", "author_id": 22970, "author_profile": "https://Stackoverflow.com/users/22970", "pm_score": 1, "selected": false, "text": "<p>Are the web front end and the SQL server on the same box ?</p>\n\n<p>If not, you'll have to set up Kerberos to allow credentials propagation.</p>\n" }, { "answer_id": 292214, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You cannot do that - the workflow does not run in the context of a user. Workflows are executed asynchronuously. Only (HTTP) WebPage-Requests run in the context of the user (if you turn on impersonation). You cannot flow the impersonation to the workflow. To restore impersonation in the workflow (which you should not do) would require username AND password OR protocol transition (process would need to run under system then).</p>\n\n<p>Additionally, your application has a serious design issue if you try to access the db from an impersonated user context. That messes up connection pooling and will seriously hurt performance. That is generally a no-go. </p>\n\n<p>This is <em>not</em> a kerberos issue. The process tries to access the db as the machine account, which tells you the process is running as either network service or (win 2008 and later) system. </p>\n" }, { "answer_id": 605019, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": true, "text": "<p>Any DB access should run as a Windows Service account for security and connection pooling reasons.</p>\n\n<p>Regarding the Workflow Security Context, see: </p>\n\n<p>SharePoint, Workflows and Security\n<a href=\"http://cglessner.blogspot.com/2008/09/sharepoint-workflows-and-security.html\" rel=\"nofollow noreferrer\">http://cglessner.blogspot.com/2008/09/sharepoint-workflows-and-security.html</a></p>\n\n<p>Declarative Workflows and User Context <a href=\"http://blogs.msdn.com/sharepointdesigner/archive/2008/09/28/declarative-workflows-and-user-context.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/sharepointdesigner/archive/2008/09/28/declarative-workflows-and-user-context.aspx</a></p>\n\n<p>Security and Application Development in SharePoint: First Steps\nWorkflow\n<a href=\"http://www.microsoft.com/technet/community/columns/secmvp/sv0408.mspx#EACAC\" rel=\"nofollow noreferrer\">http://www.microsoft.com/technet/community/columns/secmvp/sv0408.mspx#EACAC</a></p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192241", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Good morning everyone, I'm running into an issue using a SharePoint workflow project (C#, VS 2008) and connecting to a database. Here is my database connection string: ``` Data Source=DBSERVER;Initial Catalog=DBNAME;Integrated Security=True; ``` When I attempt to run the following code I get the following error ... ``` SqlConnection dbEngine = new SqlConnection(Constants.DBCONNECTION_STRING); dbEngine.Open(); ``` **"Login failed for user 'DOMAIN\MACHINE\_NAME$'"** What I need it to do is pass through the logged in user's credentials. I've got impersonation turned on but it doesn't seem to be passing through. Any suggestions would be very much appreciated. Thank you in advance for any advice, Scott Vercuski
Any DB access should run as a Windows Service account for security and connection pooling reasons. Regarding the Workflow Security Context, see: SharePoint, Workflows and Security <http://cglessner.blogspot.com/2008/09/sharepoint-workflows-and-security.html> Declarative Workflows and User Context <http://blogs.msdn.com/sharepointdesigner/archive/2008/09/28/declarative-workflows-and-user-context.aspx> Security and Application Development in SharePoint: First Steps Workflow <http://www.microsoft.com/technet/community/columns/secmvp/sv0408.mspx#EACAC>
192,249
<p>Say, I have a script that gets called with this line:</p> <pre><code>./myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile </code></pre> <p>or this one:</p> <pre><code>./myscript -v -f -d -o /fizz/someOtherFile ./foo/bar/someFile </code></pre> <p>What's the accepted way of parsing this such that in each case (or some combination of the two) <code>$v</code>, <code>$f</code>, and <code>$d</code> will all be set to <code>true</code> and <code>$outFile</code> will be equal to <code>/fizz/someOtherFile</code>?</p>
[ { "answer_id": 192266, "author": "Matt J", "author_id": 18528, "author_profile": "https://Stackoverflow.com/users/18528", "pm_score": 7, "selected": false, "text": "<p><code>getopt()</code>/<code>getopts()</code> is a good option. Copied from <a href=\"http://aplawrence.com/Unix/getopts.html\" rel=\"nofollow noreferrer\">here</a>:</p>\n<blockquote>\n<p>The simple use of &quot;getopt&quot; is shown in this mini-script:</p>\n</blockquote>\n<pre><code>#!/bin/bash\necho &quot;Before getopt&quot;\nfor i\ndo\n echo $i\ndone\nargs=`getopt abc:d $*`\nset -- $args\necho &quot;After getopt&quot;\nfor i\ndo\n echo &quot;--&gt;$i&quot;\ndone\n</code></pre>\n<blockquote>\n<p>What we have said is that any of -a,\n-b, -c or -d will be allowed, but that -c is followed by an argument (the &quot;c:&quot; says that).</p>\n<p>If we call this &quot;g&quot; and try it out:</p>\n</blockquote>\n<pre><code>bash-2.05a$ ./g -abc foo\nBefore getopt\n-abc\nfoo\nAfter getopt\n--&gt;-a\n--&gt;-b\n--&gt;-c\n--&gt;foo\n--&gt;--\n</code></pre>\n<blockquote>\n<p>We start with two arguments, and\n&quot;getopt&quot; breaks apart the options and\nputs each in its own argument. It also\nadded &quot;--&quot;.</p>\n</blockquote>\n" }, { "answer_id": 9518714, "author": "Alek", "author_id": 1243005, "author_profile": "https://Stackoverflow.com/users/1243005", "pm_score": 4, "selected": false, "text": "<p>I think this one is simple enough to use:</p>\n<pre><code>#!/bin/bash\n#\n\nreadopt='getopts $opts opt;rc=$?;[ &quot;$rc$opt&quot; = &quot;0?&quot; ]&amp;&amp;exit 1;[ $rc = 0 ]||{ shift $[OPTIND-1];false; }'\n\nopts=vfdo:\n\n# Enumerating options\nwhile eval &quot;$readopt&quot;\ndo\n echo OPT:$opt ${OPTARG+OPTARG:$OPTARG}\ndone\n\n# Enumerating arguments\nfor arg\ndo\n echo ARG:$arg\ndone\n</code></pre>\n<p>Invocation example:</p>\n<pre><code>./myscript -v -do /fizz/someOtherFile -f ./foo/bar/someFile\nOPT:v \nOPT:d \nOPT:o OPTARG:/fizz/someOtherFile\nOPT:f \nARG:./foo/bar/someFile\n</code></pre>\n" }, { "answer_id": 13359121, "author": "guneysus", "author_id": 1766716, "author_profile": "https://Stackoverflow.com/users/1766716", "pm_score": 7, "selected": false, "text": "<p>From <a href=\"https://web.archive.org/web/20120818044047/http://www.digitalpeer.com/id/parsing\" rel=\"noreferrer\">digitalpeer.com</a> with minor modifications:</p>\n<p>Usage <code> myscript.sh -p=my_prefix -s=dirname -l=libname</code></p>\n<pre><code>#!/bin/bash\nfor i in &quot;$@&quot;\ndo\ncase $i in\n -p=*|--prefix=*)\n PREFIX=&quot;${i#*=}&quot;\n\n ;;\n -s=*|--searchpath=*)\n SEARCHPATH=&quot;${i#*=}&quot;\n ;;\n -l=*|--lib=*)\n DIR=&quot;${i#*=}&quot;\n ;;\n --default)\n DEFAULT=YES\n ;;\n *)\n # unknown option\n ;;\nesac\ndone\necho PREFIX = ${PREFIX}\necho SEARCH PATH = ${SEARCHPATH}\necho DIRS = ${DIR}\necho DEFAULT = ${DEFAULT}\n</code></pre>\n<p>To better understand <code>${i#*=}</code> search for &quot;Substring Removal&quot; in <a href=\"http://tldp.org/LDP/abs/html/string-manipulation.html\" rel=\"noreferrer\">this guide</a>. It is functionally equivalent to <code>`sed 's/[^=]*=//' &lt;&lt;&lt; &quot;$i&quot;`</code> which calls a needless subprocess or <code>`echo &quot;$i&quot; | sed 's/[^=]*=//'`</code> which calls <em>two</em> needless subprocesses.</p>\n" }, { "answer_id": 14203146, "author": "Bruno Bronosky", "author_id": 117471, "author_profile": "https://Stackoverflow.com/users/117471", "pm_score": 13, "selected": true, "text": "<h4>Bash Space-Separated (e.g., <code>--option argument</code>)</h4>\n\n<pre class=\"lang-sh prettyprint-override\"><code>cat &gt;/tmp/demo-space-separated.sh &lt;&lt;'EOF'\n#!/bin/bash\n\nPOSITIONAL_ARGS=()\n\nwhile [[ $# -gt 0 ]]; do\n case $1 in\n -e|--extension)\n EXTENSION=&quot;$2&quot;\n shift # past argument\n shift # past value\n ;;\n -s|--searchpath)\n SEARCHPATH=&quot;$2&quot;\n shift # past argument\n shift # past value\n ;;\n --default)\n DEFAULT=YES\n shift # past argument\n ;;\n -*|--*)\n echo &quot;Unknown option $1&quot;\n exit 1\n ;;\n *)\n POSITIONAL_ARGS+=(&quot;$1&quot;) # save positional arg\n shift # past argument\n ;;\n esac\ndone\n\nset -- &quot;${POSITIONAL_ARGS[@]}&quot; # restore positional parameters\n\necho &quot;FILE EXTENSION = ${EXTENSION}&quot;\necho &quot;SEARCH PATH = ${SEARCHPATH}&quot;\necho &quot;DEFAULT = ${DEFAULT}&quot;\necho &quot;Number files in SEARCH PATH with EXTENSION:&quot; $(ls -1 &quot;${SEARCHPATH}&quot;/*.&quot;${EXTENSION}&quot; | wc -l)\n\nif [[ -n $1 ]]; then\n echo &quot;Last line of file specified as non-opt/last argument:&quot;\n tail -1 &quot;$1&quot;\nfi\nEOF\n\nchmod +x /tmp/demo-space-separated.sh\n\n/tmp/demo-space-separated.sh -e conf -s /etc /etc/hosts\n</code></pre>\n<h5>Output from copy-pasting the block above</h5>\n<pre class=\"lang-sh prettyprint-override\"><code>FILE EXTENSION = conf\nSEARCH PATH = /etc\nDEFAULT =\nNumber files in SEARCH PATH with EXTENSION: 14\nLast line of file specified as non-opt/last argument:\n#93.184.216.34 example.com\n</code></pre>\n<h5>Usage</h5>\n<pre class=\"lang-bash prettyprint-override\"><code>demo-space-separated.sh -e conf -s /etc /etc/hosts\n</code></pre>\n<hr />\n<h4>Bash Equals-Separated (e.g., <code>--option=argument</code>)</h4>\n<pre class=\"lang-sh prettyprint-override\"><code>cat &gt;/tmp/demo-equals-separated.sh &lt;&lt;'EOF'\n#!/bin/bash\n\nfor i in &quot;$@&quot;; do\n case $i in\n -e=*|--extension=*)\n EXTENSION=&quot;${i#*=}&quot;\n shift # past argument=value\n ;;\n -s=*|--searchpath=*)\n SEARCHPATH=&quot;${i#*=}&quot;\n shift # past argument=value\n ;;\n --default)\n DEFAULT=YES\n shift # past argument with no value\n ;;\n -*|--*)\n echo &quot;Unknown option $i&quot;\n exit 1\n ;;\n *)\n ;;\n esac\ndone\n\necho &quot;FILE EXTENSION = ${EXTENSION}&quot;\necho &quot;SEARCH PATH = ${SEARCHPATH}&quot;\necho &quot;DEFAULT = ${DEFAULT}&quot;\necho &quot;Number files in SEARCH PATH with EXTENSION:&quot; $(ls -1 &quot;${SEARCHPATH}&quot;/*.&quot;${EXTENSION}&quot; | wc -l)\n\nif [[ -n $1 ]]; then\n echo &quot;Last line of file specified as non-opt/last argument:&quot;\n tail -1 $1\nfi\nEOF\n\nchmod +x /tmp/demo-equals-separated.sh\n\n/tmp/demo-equals-separated.sh -e=conf -s=/etc /etc/hosts\n</code></pre>\n<h5>Output from copy-pasting the block above</h5>\n<pre class=\"lang-sh prettyprint-override\"><code>FILE EXTENSION = conf\nSEARCH PATH = /etc\nDEFAULT =\nNumber files in SEARCH PATH with EXTENSION: 14\nLast line of file specified as non-opt/last argument:\n#93.184.216.34 example.com\n</code></pre>\n<h5>Usage</h5>\n<pre class=\"lang-bash prettyprint-override\"><code>demo-equals-separated.sh -e=conf -s=/etc /etc/hosts\n</code></pre>\n<hr />\n<p>To better understand <code>${i#*=}</code> search for &quot;Substring Removal&quot; in <a href=\"http://tldp.org/LDP/abs/html/string-manipulation.html\" rel=\"noreferrer\">this guide</a>. It is functionally equivalent to <code>`sed 's/[^=]*=//' &lt;&lt;&lt; &quot;$i&quot;`</code> which calls a needless subprocess or <code>`echo &quot;$i&quot; | sed 's/[^=]*=//'`</code> which calls <em>two</em> needless subprocesses.</p>\n<hr />\n<h4>Using bash with getopt[s]</h4>\n<p>getopt(1) limitations (older, relatively-recent <code>getopt</code> versions):</p>\n<ul>\n<li>can't handle arguments that are empty strings</li>\n<li>can't handle arguments with embedded whitespace</li>\n</ul>\n<p>More recent <code>getopt</code> versions don't have these limitations. For more information, see these <a href=\"https://mywiki.wooledge.org/BashFAQ/035#getopts\" rel=\"noreferrer\">docs</a>.</p>\n<hr />\n<h4>POSIX getopts</h4>\n<p>Additionally, the POSIX shell and others offer <code>getopts</code> which doen't have these limitations. I've included a simplistic <code>getopts</code> example.</p>\n<pre class=\"lang-sh prettyprint-override\"><code>cat &gt;/tmp/demo-getopts.sh &lt;&lt;'EOF'\n#!/bin/sh\n\n# A POSIX variable\nOPTIND=1 # Reset in case getopts has been used previously in the shell.\n\n# Initialize our own variables:\noutput_file=&quot;&quot;\nverbose=0\n\nwhile getopts &quot;h?vf:&quot; opt; do\n case &quot;$opt&quot; in\n h|\\?)\n show_help\n exit 0\n ;;\n v) verbose=1\n ;;\n f) output_file=$OPTARG\n ;;\n esac\ndone\n\nshift $((OPTIND-1))\n\n[ &quot;${1:-}&quot; = &quot;--&quot; ] &amp;&amp; shift\n\necho &quot;verbose=$verbose, output_file='$output_file', Leftovers: $@&quot;\nEOF\n\nchmod +x /tmp/demo-getopts.sh\n\n/tmp/demo-getopts.sh -vf /etc/hosts foo bar\n</code></pre>\n<h5>Output from copy-pasting the block above</h5>\n<pre class=\"lang-sh prettyprint-override\"><code>verbose=1, output_file='/etc/hosts', Leftovers: foo bar\n</code></pre>\n<h5>Usage</h5>\n<pre class=\"lang-bash prettyprint-override\"><code>demo-getopts.sh -vf /etc/hosts foo bar\n</code></pre>\n<p>The advantages of <code>getopts</code> are:</p>\n<ol>\n<li>It's more portable, and will work in other shells like <code>dash</code>.</li>\n<li>It can handle multiple single options like <code>-vf filename</code> in the typical Unix way, automatically.</li>\n</ol>\n<p>The disadvantage of <code>getopts</code> is that it can only handle short options (<code>-h</code>, not <code>--help</code>) without additional code.</p>\n<p>There is a <a href=\"http://wiki.bash-hackers.org/howto/getopts_tutorial\" rel=\"noreferrer\">getopts tutorial</a> which explains what all of the syntax and variables mean. In bash, there is also <code>help getopts</code>, which might be informative.</p>\n" }, { "answer_id": 17553853, "author": "Volodymyr M. Lisivka", "author_id": 196559, "author_profile": "https://Stackoverflow.com/users/196559", "pm_score": 2, "selected": false, "text": "<p>Use module \"arguments\" from <a href=\"https://github.com/vlisivka/bash-modules\" rel=\"nofollow\">bash-modules</a></p>\n\n<p>Example:</p>\n\n<pre><code>#!/bin/bash\n. import.sh log arguments\n\nNAME=\"world\"\n\nparse_arguments \"-n|--name)NAME;S\" -- \"$@\" || {\n error \"Cannot parse command line.\"\n exit 1\n}\n\ninfo \"Hello, $NAME!\"\n</code></pre>\n" }, { "answer_id": 17740813, "author": "akostadinov", "author_id": 520567, "author_profile": "https://Stackoverflow.com/users/520567", "pm_score": 3, "selected": false, "text": "<p>This is how I do in a function to avoid breaking getopts run at the same time somewhere higher in stack:</p>\n\n<pre><code>function waitForWeb () {\n local OPTIND=1 OPTARG OPTION\n local host=localhost port=8080 proto=http\n while getopts \"h:p:r:\" OPTION; do\n case \"$OPTION\" in\n h)\n host=\"$OPTARG\"\n ;;\n p)\n port=\"$OPTARG\"\n ;;\n r)\n proto=\"$OPTARG\"\n ;;\n esac\n done\n...\n}\n</code></pre>\n" }, { "answer_id": 24121652, "author": "unsynchronized", "author_id": 830899, "author_profile": "https://Stackoverflow.com/users/830899", "pm_score": 4, "selected": false, "text": "<p>If you are making scripts that are interchangeable with other utilities, below flexibility may be useful.</p>\n<p>Either:</p>\n<pre><code>command -x=myfilename.ext --another_switch \n</code></pre>\n<p>Or:</p>\n<pre><code>command -x myfilename.ext --another_switch\n</code></pre>\n<p>Here is the code:</p>\n<pre><code>STD_IN=0\n\nprefix=&quot;&quot;\nkey=&quot;&quot;\nvalue=&quot;&quot;\nfor keyValue in &quot;$@&quot;\ndo\n case &quot;${prefix}${keyValue}&quot; in\n -i=*|--input_filename=*) key=&quot;-i&quot;; value=&quot;${keyValue#*=}&quot;;; \n -ss=*|--seek_from=*) key=&quot;-ss&quot;; value=&quot;${keyValue#*=}&quot;;;\n -t=*|--play_seconds=*) key=&quot;-t&quot;; value=&quot;${keyValue#*=}&quot;;;\n -|--stdin) key=&quot;-&quot;; value=1;;\n *) value=$keyValue;;\n esac\n case $key in\n -i) MOVIE=$(resolveMovie &quot;${value}&quot;); prefix=&quot;&quot;; key=&quot;&quot;;;\n -ss) SEEK_FROM=&quot;${value}&quot;; prefix=&quot;&quot;; key=&quot;&quot;;;\n -t) PLAY_SECONDS=&quot;${value}&quot;; prefix=&quot;&quot;; key=&quot;&quot;;;\n -) STD_IN=${value}; prefix=&quot;&quot;; key=&quot;&quot;;; \n *) prefix=&quot;${keyValue}=&quot;;;\n esac\ndone\n</code></pre>\n" }, { "answer_id": 24222736, "author": "Mike Q", "author_id": 1618630, "author_profile": "https://Stackoverflow.com/users/1618630", "pm_score": 1, "selected": false, "text": "<p>This also might be useful to know: you can set a value and if someone provides input, override the default with that value.</p>\n<p><code>myscript.sh -f ./serverlist.txt</code> or just <code>./myscript.sh</code> (and it takes defaults)</p>\n<pre><code> #!/bin/bash\n # --- set the value, if there is inputs, override the defaults.\n\n HOME_FOLDER=&quot;${HOME}/owned_id_checker&quot;\n SERVER_FILE_LIST=&quot;${HOME_FOLDER}/server_list.txt&quot;\n\n while [[ $# &gt; 1 ]]\n do\n key=&quot;$1&quot;\n shift\n \n case $key in\n -i|--inputlist)\n SERVER_FILE_LIST=&quot;$1&quot;\n shift\n ;;\n esac\n done\n\n \n echo &quot;SERVER LIST = ${SERVER_FILE_LIST}&quot;\n</code></pre>\n" }, { "answer_id": 24501190, "author": "Shane Day", "author_id": 3792174, "author_profile": "https://Stackoverflow.com/users/3792174", "pm_score": 5, "selected": false, "text": "<p>I used the earlier answers as a starting point to tidy up my old adhoc param parsing. I then refactored out the following template code. It handles both long and short params, using = or space separated arguments, as well as multiple short params grouped together. Finally it re-inserts any non-param arguments back into the $1,$2.. variables.</p>\n<pre><code>#!/usr/bin/env bash\n\n# NOTICE: Uncomment if your script depends on bashisms.\n#if [ -z &quot;$BASH_VERSION&quot; ]; then bash $0 $@ ; exit $? ; fi\n\necho &quot;Before&quot;\nfor i ; do echo - $i ; done\n\n\n# Code template for parsing command line parameters using only portable shell\n# code, while handling both long and short params, handling '-f file' and\n# '-f=file' style param data and also capturing non-parameters to be inserted\n# back into the shell positional parameters.\n\nwhile [ -n &quot;$1&quot; ]; do\n # Copy so we can modify it (can't modify $1)\n OPT=&quot;$1&quot;\n # Detect argument termination\n if [ x&quot;$OPT&quot; = x&quot;--&quot; ]; then\n shift\n for OPT ; do\n REMAINS=&quot;$REMAINS \\&quot;$OPT\\&quot;&quot;\n done\n break\n fi\n # Parse current opt\n while [ x&quot;$OPT&quot; != x&quot;-&quot; ] ; do\n case &quot;$OPT&quot; in\n # Handle --flag=value opts like this\n -c=* | --config=* )\n CONFIGFILE=&quot;${OPT#*=}&quot;\n shift\n ;;\n # and --flag value opts like this\n -c* | --config )\n CONFIGFILE=&quot;$2&quot;\n shift\n ;;\n -f* | --force )\n FORCE=true\n ;;\n -r* | --retry )\n RETRY=true\n ;;\n # Anything unknown is recorded for later\n * )\n REMAINS=&quot;$REMAINS \\&quot;$OPT\\&quot;&quot;\n break\n ;;\n esac\n # Check for multiple short options\n # NOTICE: be sure to update this pattern to match valid options\n NEXTOPT=&quot;${OPT#-[cfr]}&quot; # try removing single short opt\n if [ x&quot;$OPT&quot; != x&quot;$NEXTOPT&quot; ] ; then\n OPT=&quot;-$NEXTOPT&quot; # multiple short opts, keep going\n else\n break # long form, exit inner loop\n fi\n done\n # Done with that param. move to next\n shift\ndone\n# Set the non-parameters back into the positional parameters ($1 $2 ..)\neval set -- $REMAINS\n\n\necho -e &quot;After: \\n configfile='$CONFIGFILE' \\n force='$FORCE' \\n retry='$RETRY' \\n remains='$REMAINS'&quot;\nfor i ; do echo - $i ; done\n</code></pre>\n" }, { "answer_id": 28488486, "author": "vangorra", "author_id": 1267536, "author_profile": "https://Stackoverflow.com/users/1267536", "pm_score": 4, "selected": false, "text": "<p>getopts works great if #1 you have it installed and #2 you intend to run it on the same platform. OSX and Linux (for example) behave differently in this respect.</p>\n\n<p>Here is a (non getopts) solution that supports equals, non-equals, and boolean flags. For example you could run your script in this way:</p>\n\n<pre><code>./script --arg1=value1 --arg2 value2 --shouldClean\n\n# parse the arguments.\nCOUNTER=0\nARGS=(\"$@\")\nwhile [ $COUNTER -lt $# ]\ndo\n arg=${ARGS[$COUNTER]}\n let COUNTER=COUNTER+1\n nextArg=${ARGS[$COUNTER]}\n\n if [[ $skipNext -eq 1 ]]; then\n echo \"Skipping\"\n skipNext=0\n continue\n fi\n\n argKey=\"\"\n argVal=\"\"\n if [[ \"$arg\" =~ ^\\- ]]; then\n # if the format is: -key=value\n if [[ \"$arg\" =~ \\= ]]; then\n argVal=$(echo \"$arg\" | cut -d'=' -f2)\n argKey=$(echo \"$arg\" | cut -d'=' -f1)\n skipNext=0\n\n # if the format is: -key value\n elif [[ ! \"$nextArg\" =~ ^\\- ]]; then\n argKey=\"$arg\"\n argVal=\"$nextArg\"\n skipNext=1\n\n # if the format is: -key (a boolean flag)\n elif [[ \"$nextArg\" =~ ^\\- ]] || [[ -z \"$nextArg\" ]]; then\n argKey=\"$arg\"\n argVal=\"\"\n skipNext=0\n fi\n # if the format has not flag, just a value.\n else\n argKey=\"\"\n argVal=\"$arg\"\n skipNext=0\n fi\n\n case \"$argKey\" in \n --source-scmurl)\n SOURCE_URL=\"$argVal\"\n ;;\n --dest-scmurl)\n DEST_URL=\"$argVal\"\n ;;\n --version-num)\n VERSION_NUM=\"$argVal\"\n ;;\n -c|--clean)\n CLEAN_BEFORE_START=\"1\"\n ;;\n -h|--help|-help|--h)\n showUsage\n exit\n ;;\n esac\ndone\n</code></pre>\n" }, { "answer_id": 29754866, "author": "Robert Siemer", "author_id": 825924, "author_profile": "https://Stackoverflow.com/users/825924", "pm_score": 10, "selected": false, "text": "<p><strong>No answer showcases <em>enhanced getopt</em>. And the <a href=\"https://stackoverflow.com/a/14203146/825924\">top-voted answer</a> is misleading:</strong> It either ignores <code>-⁠vfd</code> style short options (requested by the OP) or options after positional arguments (also requested by the OP); and it ignores parsing-errors. Instead:</p>\n<ul>\n<li><strong>Use enhanced <code>getopt</code> from util-linux or formerly GNU glibc</strong>.<sup><sub>1</sub></sup></li>\n<li>It works with <code>getopt_long()</code> the C function of GNU glibc.</li>\n<li><em>no other solution on this page can do all this</em>:\n<ul>\n<li>handles spaces, quoting characters and even binary in arguments<sup><sub>2</sub></sup> (non-enhanced <code>getopt</code> can’t do this)</li>\n<li>it can handle options at the end: <code>script.sh -o outFile file1 file2 -v</code> (<code>getopts</code> doesn’t do this)</li>\n<li>allows <code>=</code>-style long options: <code>script.sh --outfile=fileOut --infile fileIn</code> (allowing both is lengthy if self parsing)</li>\n<li>allows combined short options, e.g. <code>-vfd</code> (real work if self parsing)</li>\n<li>allows touching option-arguments, e.g. <code>-oOutfile</code> or <code>-vfdoOutfile</code></li>\n</ul>\n</li>\n<li>Is so old already<sup><sub>3</sub></sup> that no GNU system is missing this (e.g. any Linux has it).</li>\n<li>You can test for its existence with: <code>getopt --test</code> → return value 4.</li>\n<li>Other <code>getopt</code> or shell-builtin <code>getopts</code> are of limited use.</li>\n</ul>\n<p>The following calls</p>\n<pre><code>myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile\nmyscript -v -f -d -o/fizz/someOtherFile -- ./foo/bar/someFile\nmyscript --verbose --force --debug ./foo/bar/someFile -o/fizz/someOtherFile\nmyscript --output=/fizz/someOtherFile ./foo/bar/someFile -vfd\nmyscript ./foo/bar/someFile -df -v --output /fizz/someOtherFile\n</code></pre>\n<p>all return</p>\n<pre><code>verbose: y, force: y, debug: y, in: ./foo/bar/someFile, out: /fizz/someOtherFile\n</code></pre>\n<p>with the following <code>myscript</code></p>\n<pre><code>#!/bin/bash\n# More safety, by turning some bugs into errors.\n# Without `errexit` you don’t need ! and can replace\n# ${PIPESTATUS[0]} with a simple $?, but I prefer safety.\nset -o errexit -o pipefail -o noclobber -o nounset\n\n# -allow a command to fail with !’s side effect on errexit\n# -use return value from ${PIPESTATUS[0]}, because ! hosed $?\n! getopt --test &gt; /dev/null \nif [[ ${PIPESTATUS[0]} -ne 4 ]]; then\n echo 'I’m sorry, `getopt --test` failed in this environment.'\n exit 1\nfi\n\n# option --output/-o requires 1 argument\nLONGOPTS=debug,force,output:,verbose\nOPTIONS=dfo:v\n\n# -regarding ! and PIPESTATUS see above\n# -temporarily store output to be able to check for errors\n# -activate quoting/enhanced mode (e.g. by writing out “--options”)\n# -pass arguments only via -- &quot;$@&quot; to separate them correctly\n! PARSED=$(getopt --options=$OPTIONS --longoptions=$LONGOPTS --name &quot;$0&quot; -- &quot;$@&quot;)\nif [[ ${PIPESTATUS[0]} -ne 0 ]]; then\n # e.g. return value is 1\n # then getopt has complained about wrong arguments to stdout\n exit 2\nfi\n# read getopt’s output this way to handle the quoting right:\neval set -- &quot;$PARSED&quot;\n\nd=n f=n v=n outFile=-\n# now enjoy the options in order and nicely split until we see --\nwhile true; do\n case &quot;$1&quot; in\n -d|--debug)\n d=y\n shift\n ;;\n -f|--force)\n f=y\n shift\n ;;\n -v|--verbose)\n v=y\n shift\n ;;\n -o|--output)\n outFile=&quot;$2&quot;\n shift 2\n ;;\n --)\n shift\n break\n ;;\n *)\n echo &quot;Programming error&quot;\n exit 3\n ;;\n esac\ndone\n\n# handle non-option arguments\nif [[ $# -ne 1 ]]; then\n echo &quot;$0: A single input file is required.&quot;\n exit 4\nfi\n\necho &quot;verbose: $v, force: $f, debug: $d, in: $1, out: $outFile&quot;\n</code></pre>\n<hr />\n<p><sup><sub>1</sub></sup> enhanced getopt is available on most “bash-systems”, including Cygwin; on OS X try <a href=\"https://stackoverflow.com/a/37485578/825924\">brew install gnu-getopt</a> or <code>sudo port install getopt</code><br>\n<sup><sub>2</sub></sup> the POSIX <code>exec()</code> conventions have no reliable way to pass binary NULL in command line arguments; those bytes prematurely end the argument<br>\n<sup><sub>3</sub></sup> first version released in 1997 or before (I only tracked it back to 1997)</p>\n" }, { "answer_id": 29886343, "author": "Mark Fox", "author_id": 934195, "author_profile": "https://Stackoverflow.com/users/934195", "pm_score": 2, "selected": false, "text": "<h2>Mixing positional and flag-based arguments</h2>\n\n<h3>--param=arg (equals delimited)</h3>\n\n<p>Freely mixing flags between positional arguments:</p>\n\n<pre><code>./script.sh dumbo 127.0.0.1 --environment=production -q -d\n./script.sh dumbo --environment=production 127.0.0.1 --quiet -d\n</code></pre>\n\n<p>can be accomplished with a fairly concise approach:</p>\n\n<pre><code># process flags\npointer=1\nwhile [[ $pointer -le $# ]]; do\n param=${!pointer}\n if [[ $param != \"-\"* ]]; then ((pointer++)) # not a parameter flag so advance pointer\n else\n case $param in\n # paramter-flags with arguments\n -e=*|--environment=*) environment=\"${param#*=}\";;\n --another=*) another=\"${param#*=}\";;\n\n # binary flags\n -q|--quiet) quiet=true;;\n -d) debug=true;;\n esac\n\n # splice out pointer frame from positional list\n [[ $pointer -gt 1 ]] \\\n &amp;&amp; set -- ${@:1:((pointer - 1))} ${@:((pointer + 1)):$#} \\\n || set -- ${@:((pointer + 1)):$#};\n fi\ndone\n\n# positional remain\nnode_name=$1\nip_address=$2\n</code></pre>\n\n<h3>--param arg (space delimited)</h3>\n\n<p>It's usualy clearer to not mix <code>--flag=value</code> and <code>--flag value</code> styles.</p>\n\n<pre><code>./script.sh dumbo 127.0.0.1 --environment production -q -d\n</code></pre>\n\n<p>This is a little dicey to read, but is still valid</p>\n\n<pre><code>./script.sh dumbo --environment production 127.0.0.1 --quiet -d\n</code></pre>\n\n<p>Source</p>\n\n<pre><code># process flags\npointer=1\nwhile [[ $pointer -le $# ]]; do\n if [[ ${!pointer} != \"-\"* ]]; then ((pointer++)) # not a parameter flag so advance pointer\n else\n param=${!pointer}\n ((pointer_plus = pointer + 1))\n slice_len=1\n\n case $param in\n # paramter-flags with arguments\n -e|--environment) environment=${!pointer_plus}; ((slice_len++));;\n --another) another=${!pointer_plus}; ((slice_len++));;\n\n # binary flags\n -q|--quiet) quiet=true;;\n -d) debug=true;;\n esac\n\n # splice out pointer frame from positional list\n [[ $pointer -gt 1 ]] \\\n &amp;&amp; set -- ${@:1:((pointer - 1))} ${@:((pointer + $slice_len)):$#} \\\n || set -- ${@:((pointer + $slice_len)):$#};\n fi\ndone\n\n# positional remain\nnode_name=$1\nip_address=$2\n</code></pre>\n" }, { "answer_id": 31024664, "author": "galmok", "author_id": 946979, "author_profile": "https://Stackoverflow.com/users/946979", "pm_score": 3, "selected": false, "text": "<p>I'd like to offer my version of option parsing, that allows for the following:</p>\n\n<pre><code>-s p1\n--stage p1\n-w somefolder\n--workfolder somefolder\n-sw p1 somefolder\n-e=hello\n</code></pre>\n\n<p>Also allows for this (could be unwanted):</p>\n\n<pre><code>-s--workfolder p1 somefolder\n-se=hello p1\n-swe=hello p1 somefolder\n</code></pre>\n\n<p>You have to decide before use if = is to be used on an option or not. This is to keep the code clean(ish).</p>\n\n<pre><code>while [[ $# &gt; 0 ]]\ndo\n key=\"$1\"\n while [[ ${key+x} ]]\n do\n case $key in\n -s*|--stage)\n STAGE=\"$2\"\n shift # option has parameter\n ;;\n -w*|--workfolder)\n workfolder=\"$2\"\n shift # option has parameter\n ;;\n -e=*)\n EXAMPLE=\"${key#*=}\"\n break # option has been fully handled\n ;;\n *)\n # unknown option\n echo Unknown option: $key #1&gt;&amp;2\n exit 10 # either this: my preferred way to handle unknown options\n break # or this: do this to signal the option has been handled (if exit isn't used)\n ;;\n esac\n # prepare for next option in this key, if any\n [[ \"$key\" = -? || \"$key\" == --* ]] &amp;&amp; unset key || key=\"${key/#-?/-}\"\n done\n shift # option(s) fully processed, proceed to next input argument\ndone\n</code></pre>\n" }, { "answer_id": 31443098, "author": "bronson", "author_id": 912602, "author_profile": "https://Stackoverflow.com/users/912602", "pm_score": 7, "selected": false, "text": "<pre class=\"lang-bash prettyprint-override\"><code>while [ &quot;$#&quot; -gt 0 ]; do\n case &quot;$1&quot; in\n -n) name=&quot;$2&quot;; shift 2;;\n -p) pidfile=&quot;$2&quot;; shift 2;;\n -l) logfile=&quot;$2&quot;; shift 2;;\n\n --name=*) name=&quot;${1#*=}&quot;; shift 1;;\n --pidfile=*) pidfile=&quot;${1#*=}&quot;; shift 1;;\n --logfile=*) logfile=&quot;${1#*=}&quot;; shift 1;;\n --name|--pidfile|--logfile) echo &quot;$1 requires an argument&quot; &gt;&amp;2; exit 1;;\n \n -*) echo &quot;unknown option: $1&quot; &gt;&amp;2; exit 1;;\n *) handle_argument &quot;$1&quot;; shift 1;;\n esac\ndone\n</code></pre>\n<p>This solution:</p>\n<ul>\n<li>handles <code>-n arg</code> and <code>--name=arg</code></li>\n<li>allows arguments at the end</li>\n<li>shows sane errors if anything is misspelled</li>\n<li>compatible, doesn't use bashisms</li>\n<li>readable, doesn't require maintaining state in a loop</li>\n</ul>\n" }, { "answer_id": 32965658, "author": "Masadow", "author_id": 2836899, "author_profile": "https://Stackoverflow.com/users/2836899", "pm_score": 1, "selected": false, "text": "<p>Here is my improved solution of Bruno Bronosky's answer using variable arrays.</p>\n\n<p>it lets you mix parameters position and give you a parameter array preserving the order without the options</p>\n\n<pre><code>#!/bin/bash\n\necho $@\n\nPARAMS=()\nSOFT=0\nSKIP=()\nfor i in \"$@\"\ndo\ncase $i in\n -n=*|--skip=*)\n SKIP+=(\"${i#*=}\")\n ;;\n -s|--soft)\n SOFT=1\n ;;\n *)\n # unknown option\n PARAMS+=(\"$i\")\n ;;\nesac\ndone\necho \"SKIP = ${SKIP[@]}\"\necho \"SOFT = $SOFT\"\n echo \"Parameters:\"\n echo ${PARAMS[@]}\n</code></pre>\n\n<p>Will output for example:</p>\n\n<pre><code>$ ./test.sh parameter -s somefile --skip=.c --skip=.obj\nparameter -s somefile --skip=.c --skip=.obj\nSKIP = .c .obj\nSOFT = 1\nParameters:\nparameter somefile\n</code></pre>\n" }, { "answer_id": 33191693, "author": "phk", "author_id": 2261442, "author_profile": "https://Stackoverflow.com/users/2261442", "pm_score": 1, "selected": false, "text": "<h1>Another solution without getopt[s], POSIX, old Unix style</h1>\n\n<p>Similar to <a href=\"https://stackoverflow.com/a/14203146/2261442\">the solution Bruno Bronosky posted</a> this here is one without the usage of <code>getopt(s)</code>.</p>\n\n<p>Main differentiating feature of my solution is that it allows to have options concatenated together just like <code>tar -xzf foo.tar.gz</code> is equal to <code>tar -x -z -f foo.tar.gz</code>. And just like in <code>tar</code>, <code>ps</code> etc. the leading hyphen is optional for a block of short options (but this can be changed easily). Long options are supported as well (but when a block starts with one then two leading hyphens are required).</p>\n\n<h2>Code with example options</h2>\n\n\n\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/sh\n\necho\necho \"POSIX-compliant getopt(s)-free old-style-supporting option parser from phk@[se.unix]\"\necho\n\nprint_usage() {\n echo \"Usage:\n\n $0 {a|b|c} [ARG...]\n\nOptions:\n\n --aaa-0-args\n -a\n Option without arguments.\n\n --bbb-1-args ARG\n -b ARG\n Option with one argument.\n\n --ccc-2-args ARG1 ARG2\n -c ARG1 ARG2\n Option with two arguments.\n\n\" &gt;&amp;2\n}\n\nif [ $# -le 0 ]; then\n print_usage\n exit 1\nfi\n\nopt=\nwhile :; do\n\n if [ $# -le 0 ]; then\n\n # no parameters remaining -&gt; end option parsing\n break\n\n elif [ ! \"$opt\" ]; then\n\n # we are at the beginning of a fresh block\n # remove optional leading hyphen and strip trailing whitespaces\n opt=$(echo \"$1\" | sed 's/^-\\?\\([a-zA-Z0-9\\?-]*\\)/\\1/')\n\n fi\n\n # get the first character -&gt; check whether long option\n first_chr=$(echo \"$opt\" | awk '{print substr($1, 1, 1)}')\n [ \"$first_chr\" = - ] &amp;&amp; long_option=T || long_option=F\n\n # note to write the options here with a leading hyphen less\n # also do not forget to end short options with a star\n case $opt in\n\n -)\n\n # end of options\n shift\n break\n ;;\n\n a*|-aaa-0-args)\n\n echo \"Option AAA activated!\"\n ;;\n\n b*|-bbb-1-args)\n\n if [ \"$2\" ]; then\n echo \"Option BBB with argument '$2' activated!\"\n shift\n else\n echo \"BBB parameters incomplete!\" &gt;&amp;2\n print_usage\n exit 1\n fi\n ;;\n\n c*|-ccc-2-args)\n\n if [ \"$2\" ] &amp;&amp; [ \"$3\" ]; then\n echo \"Option CCC with arguments '$2' and '$3' activated!\"\n shift 2\n else\n echo \"CCC parameters incomplete!\" &gt;&amp;2\n print_usage\n exit 1\n fi\n ;;\n\n h*|\\?*|-help)\n\n print_usage\n exit 0\n ;;\n\n *)\n\n if [ \"$long_option\" = T ]; then\n opt=$(echo \"$opt\" | awk '{print substr($1, 2)}')\n else\n opt=$first_chr\n fi\n printf 'Error: Unknown option: \"%s\"\\n' \"$opt\" &gt;&amp;2\n print_usage\n exit 1\n ;;\n\n esac\n\n if [ \"$long_option\" = T ]; then\n\n # if we had a long option then we are going to get a new block next\n shift\n opt=\n\n else\n\n # if we had a short option then just move to the next character\n opt=$(echo \"$opt\" | awk '{print substr($1, 2)}')\n\n # if block is now empty then shift to the next one\n [ \"$opt\" ] || shift\n\n fi\n\ndone\n\necho \"Doing something...\"\n\nexit 0\n</code></pre>\n\n<p>For the example usage please see the examples further below.</p>\n\n<h2>Position of options with arguments</h2>\n\n<p>For what its worth there the options with arguments don't be the last (only long options need to be). So while e.g. in <code>tar</code> (at least in some implementations) the <code>f</code> options needs to be last because the file name follows (<code>tar xzf bar.tar.gz</code> works but <code>tar xfz bar.tar.gz</code> does not) this is not the case here (see the later examples).</p>\n\n<h2>Multiple options with arguments</h2>\n\n<p>As another bonus the option parameters are consumed in the order of the options by the parameters with required options. Just look at the output of my script here with the command line <code>abc X Y Z</code> (or <code>-abc X Y Z</code>):</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Option AAA activated!\nOption BBB with argument 'X' activated!\nOption CCC with arguments 'Y' and 'Z' activated!\n</code></pre>\n\n<h2>Long options concatenated as well</h2>\n\n<p>Also you can also have long options in option block given that they occur last in the block. So the following command lines are all equivalent (including the order in which the options and its arguments are being processed):</p>\n\n<ul>\n<li><code>-cba Z Y X</code></li>\n<li><code>cba Z Y X</code></li>\n<li><code>-cb-aaa-0-args Z Y X</code></li>\n<li><code>-c-bbb-1-args Z Y X -a</code></li>\n<li><code>--ccc-2-args Z Y -ba X</code></li>\n<li><code>c Z Y b X a</code></li>\n<li><code>-c Z Y -b X -a</code></li>\n<li><code>--ccc-2-args Z Y --bbb-1-args X --aaa-0-args</code></li>\n</ul>\n\n<p>All of these lead to:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Option CCC with arguments 'Z' and 'Y' activated!\nOption BBB with argument 'X' activated!\nOption AAA activated!\nDoing something...\n</code></pre>\n\n<h2>Not in this solution</h2>\n\n<h3>Optional arguments</h3>\n\n<p>Options with optional arguments should be possible with a bit of work, e.g. by looking forward whether there is a block without a hyphen; the user would then need to put a hyphen in front of every block following a block with a parameter having an optional parameter. Maybe this is too complicated to communicate to the user so better just require a leading hyphen altogether in this case.</p>\n\n<p>Things get even more complicated with multiple possible parameters. I would advise against making the options trying to be smart by determining whether the an argument might be for it or not (e.g. with an option just takes a number as an optional argument) because this might break in the future.</p>\n\n<p>I personally favor additional options instead of optional arguments.</p>\n\n<h3>Option arguments introduced with an equal sign</h3>\n\n<p>Just like with optional arguments I am not a fan of this (BTW, is there a thread for discussing the pros/cons of different parameter styles?) but if you want this you could probably implement it yourself just like done at <a href=\"http://mywiki.wooledge.org/BashFAQ/035#Manual_loop\" rel=\"nofollow noreferrer\">http://mywiki.wooledge.org/BashFAQ/035#Manual_loop</a> with a <code>--long-with-arg=?*</code> case statement and then stripping the equal sign (this is BTW the site that says that making parameter concatenation is possible with some effort but \"left [it] as an exercise for the reader\" which made me take them at their word but I started from scratch).</p>\n\n<h2>Other notes</h2>\n\n<p>POSIX-compliant, works even on ancient Busybox setups I had to deal with (with e.g. <code>cut</code>, <code>head</code> and <code>getopts</code> missing).</p>\n" }, { "answer_id": 33216429, "author": "schily", "author_id": 5298132, "author_profile": "https://Stackoverflow.com/users/5298132", "pm_score": 2, "selected": false, "text": "<p>Note that <code>getopt(1)</code> was a short living mistake from AT&amp;T.</p>\n\n<p>getopt was created in 1984 but already buried in 1986 because it was not really usable.</p>\n\n<p>A proof for the fact that <code>getopt</code> is very outdated is that the <code>getopt(1)</code> man page still mentions <code>\"$*\"</code> instead of <code>\"$@\"</code>, that was added to the Bourne Shell in 1986 together with the <code>getopts(1)</code> shell builtin in order to deal with arguments with spaces inside.</p>\n\n<p>BTW: if you are interested in parsing long options in shell scripts, it may be of interest to know that the <code>getopt(3)</code> implementation from libc (Solaris) and <code>ksh93</code> both added a uniform long option implementation that supports long options as aliases for short options. This causes <code>ksh93</code> and the <code>Bourne Shell</code> to implement a uniform interface for long options via <code>getopts</code>.</p>\n\n<p>An example for long options taken from the Bourne Shell man page:</p>\n\n<p><code>getopts \"f:(file)(input-file)o:(output-file)\" OPTX \"$@\"</code></p>\n\n<p>shows how long option aliases may be used in both Bourne Shell and ksh93.</p>\n\n<p>See the man page of a recent Bourne Shell:</p>\n\n<p><a href=\"http://schillix.sourceforge.net/man/man1/bosh.1.html\" rel=\"nofollow noreferrer\">http://schillix.sourceforge.net/man/man1/bosh.1.html</a></p>\n\n<p>and the man page for getopt(3) from OpenSolaris:</p>\n\n<p><a href=\"http://schillix.sourceforge.net/man/man3c/getopt.3c.html\" rel=\"nofollow noreferrer\">http://schillix.sourceforge.net/man/man3c/getopt.3c.html</a></p>\n\n<p>and last, the getopt(1) man page to verify the outdated $*:</p>\n\n<p><a href=\"http://schillix.sourceforge.net/man/man1/getopt.1.html\" rel=\"nofollow noreferrer\">http://schillix.sourceforge.net/man/man1/getopt.1.html</a></p>\n" }, { "answer_id": 33826763, "author": "Inanc Gumus", "author_id": 115363, "author_profile": "https://Stackoverflow.com/users/115363", "pm_score": 9, "selected": false, "text": "<p><strong>deploy.sh</strong></p>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/bash\n\nwhile [[ &quot;$#&quot; -gt 0 ]]; do\n case $1 in\n -t|--target) target=&quot;$2&quot;; shift ;;\n -u|--uglify) uglify=1 ;;\n *) echo &quot;Unknown parameter passed: $1&quot;; exit 1 ;;\n esac\n shift\ndone\n\necho &quot;Where to deploy: $target&quot;\necho &quot;Should uglify : $uglify&quot;\n</code></pre>\n<p><strong>Usage:</strong></p>\n<pre class=\"lang-sh prettyprint-override\"><code>./deploy.sh -t dev -u\n\n# OR:\n\n./deploy.sh --target dev --uglify\n</code></pre>\n" }, { "answer_id": 38153758, "author": "Oleksii Chekulaiev", "author_id": 1359178, "author_profile": "https://Stackoverflow.com/users/1359178", "pm_score": 4, "selected": false, "text": "<p>I give you The Function <code>parse_params</code> that will parse params from the command line.</p>\n\n<ol>\n<li>It is a pure Bash solution, no additional utilities.</li>\n<li>Does not pollute global scope. </li>\n<li>Effortlessly returns you simple to use variables, that you could build further logic on.</li>\n<li>Amount of dashes before params does not matter (<code>--all</code> equals <code>-all</code> equals <code>all=all</code>)</li>\n</ol>\n\n<p>The script below is a copy-paste working demonstration. See <code>show_use</code> function to understand how to use <code>parse_params</code>.</p>\n\n<p>Limitations: </p>\n\n<ol>\n<li>Does not support space delimited params (<code>-d 1</code>)</li>\n<li>Param names will lose dashes so <code>--any-param</code> and <code>-anyparam</code> are equivalent</li>\n<li><code>eval $(parse_params \"$@\")</code> must be used inside bash <strong>function</strong> (it will not work in the global scope)</li>\n</ol>\n\n<hr>\n\n<pre><code>#!/bin/bash\n\n# Universal Bash parameter parsing\n# Parse equal sign separated params into named local variables\n# Standalone named parameter value will equal its param name (--force creates variable $force==\"force\")\n# Parses multi-valued named params into an array (--path=path1 --path=path2 creates ${path[*]} array)\n# Puts un-named params as-is into ${ARGV[*]} array\n# Additionally puts all named params as-is into ${ARGN[*]} array\n# Additionally puts all standalone \"option\" params as-is into ${ARGO[*]} array\n# @author Oleksii Chekulaiev\n# @version v1.4.1 (Jul-27-2018)\nparse_params ()\n{\n local existing_named\n local ARGV=() # un-named params\n local ARGN=() # named params\n local ARGO=() # options (--params)\n echo \"local ARGV=(); local ARGN=(); local ARGO=();\"\n while [[ \"$1\" != \"\" ]]; do\n # Escape asterisk to prevent bash asterisk expansion, and quotes to prevent string breakage\n _escaped=${1/\\*/\\'\\\"*\\\"\\'}\n _escaped=${_escaped//\\'/\\\\\\'}\n _escaped=${_escaped//\\\"/\\\\\\\"}\n # If equals delimited named parameter\n nonspace=\"[^[:space:]]\"\n if [[ \"$1\" =~ ^${nonspace}${nonspace}*=..* ]]; then\n # Add to named parameters array\n echo \"ARGN+=('$_escaped');\"\n # key is part before first =\n local _key=$(echo \"$1\" | cut -d = -f 1)\n # Just add as non-named when key is empty or contains space\n if [[ \"$_key\" == \"\" || \"$_key\" =~ \" \" ]]; then\n echo \"ARGV+=('$_escaped');\"\n shift\n continue\n fi\n # val is everything after key and = (protect from param==value error)\n local _val=\"${1/$_key=}\"\n # remove dashes from key name\n _key=${_key//\\-}\n # skip when key is empty\n # search for existing parameter name\n if (echo \"$existing_named\" | grep \"\\b$_key\\b\" &gt;/dev/null); then\n # if name already exists then it's a multi-value named parameter\n # re-declare it as an array if needed\n if ! (declare -p _key 2&gt; /dev/null | grep -q 'declare \\-a'); then\n echo \"$_key=(\\\"\\$$_key\\\");\"\n fi\n # append new value\n echo \"$_key+=('$_val');\"\n else\n # single-value named parameter\n echo \"local $_key='$_val';\"\n existing_named=\" $_key\"\n fi\n # If standalone named parameter\n elif [[ \"$1\" =~ ^\\-${nonspace}+ ]]; then\n # remove dashes\n local _key=${1//\\-}\n # Just add as non-named when key is empty or contains space\n if [[ \"$_key\" == \"\" || \"$_key\" =~ \" \" ]]; then\n echo \"ARGV+=('$_escaped');\"\n shift\n continue\n fi\n # Add to options array\n echo \"ARGO+=('$_escaped');\"\n echo \"local $_key=\\\"$_key\\\";\"\n # non-named parameter\n else\n # Escape asterisk to prevent bash asterisk expansion\n _escaped=${1/\\*/\\'\\\"*\\\"\\'}\n echo \"ARGV+=('$_escaped');\"\n fi\n shift\n done\n}\n\n#--------------------------- DEMO OF THE USAGE -------------------------------\n\nshow_use ()\n{\n eval $(parse_params \"$@\")\n # --\n echo \"${ARGV[0]}\" # print first unnamed param\n echo \"${ARGV[1]}\" # print second unnamed param\n echo \"${ARGN[0]}\" # print first named param\n echo \"${ARG0[0]}\" # print first option param (--force)\n echo \"$anyparam\" # print --anyparam value\n echo \"$k\" # print k=5 value\n echo \"${multivalue[0]}\" # print first value of multi-value\n echo \"${multivalue[1]}\" # print second value of multi-value\n [[ \"$force\" == \"force\" ]] &amp;&amp; echo \"\\$force is set so let the force be with you\"\n}\n\nshow_use \"param 1\" --anyparam=\"my value\" param2 k=5 --force --multi-value=test1 --multi-value=test2\n</code></pre>\n" }, { "answer_id": 38297066, "author": "bubla", "author_id": 592892, "author_profile": "https://Stackoverflow.com/users/592892", "pm_score": 6, "selected": false, "text": "<p>I have found the matter to write portable parsing in scripts so frustrating that I have written <a href=\"https://github.com/matejak/argbash\" rel=\"noreferrer\" title=\"Argbash\">Argbash</a> - a FOSS code generator that can generate the arguments-parsing code for your script plus it has some nice features:</p>\n\n<p><a href=\"https://argbash.io\" rel=\"noreferrer\">https://argbash.io</a></p>\n" }, { "answer_id": 38829557, "author": "Daniel Bigham", "author_id": 226539, "author_profile": "https://Stackoverflow.com/users/226539", "pm_score": 1, "selected": false, "text": "<p>The top answer to this question seemed a bit buggy when I tried it -- here's my solution which I've found to be more robust:</p>\n\n<pre><code>boolean_arg=\"\"\narg_with_value=\"\"\n\nwhile [[ $# -gt 0 ]]\ndo\nkey=\"$1\"\ncase $key in\n -b|--boolean-arg)\n boolean_arg=true\n shift\n ;;\n -a|--arg-with-value)\n arg_with_value=\"$2\"\n shift\n shift\n ;;\n -*)\n echo \"Unknown option: $1\"\n exit 1\n ;;\n *)\n arg_num=$(( $arg_num + 1 ))\n case $arg_num in\n 1)\n first_normal_arg=\"$1\"\n shift\n ;;\n 2)\n second_normal_arg=\"$1\"\n shift\n ;;\n *)\n bad_args=TRUE\n esac\n ;;\nesac\ndone\n\n# Handy to have this here when adding arguments to\n# see if they're working. Just edit the '0' to be '1'.\nif [[ 0 == 1 ]]; then\n echo \"first_normal_arg: $first_normal_arg\"\n echo \"second_normal_arg: $second_normal_arg\"\n echo \"boolean_arg: $boolean_arg\"\n echo \"arg_with_value: $arg_with_value\"\n exit 0\nfi\n\nif [[ $bad_args == TRUE || $arg_num &lt; 2 ]]; then\n echo \"Usage: $(basename \"$0\") &lt;first-normal-arg&gt; &lt;second-normal-arg&gt; [--boolean-arg] [--arg-with-value VALUE]\"\n exit 1\nfi\n</code></pre>\n" }, { "answer_id": 39198204, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<h1>Solution that preserves unhandled arguments. Demos Included.</h1>\n\n<p>Here is my solution. It is VERY flexible and unlike others, shouldn't require external packages and handles leftover arguments cleanly.</p>\n\n<p>Usage is: <code>./myscript -flag flagvariable -otherflag flagvar2</code></p>\n\n<p>All you have to do is edit the validflags line. It prepends a hyphen and searches all arguments. It then defines the next argument as the flag name e.g.</p>\n\n<pre><code>./myscript -flag flagvariable -otherflag flagvar2\necho $flag $otherflag\nflagvariable flagvar2\n</code></pre>\n\n<p>The main code (short version, verbose with examples further down, also a version with erroring out):</p>\n\n<pre><code>#!/usr/bin/env bash\n#shebang.io\nvalidflags=\"rate time number\"\ncount=1\nfor arg in $@\ndo\n match=0\n argval=$1\n for flag in $validflags\n do\n sflag=\"-\"$flag\n if [ \"$argval\" == \"$sflag\" ]\n then\n declare $flag=$2\n match=1\n fi\n done\n if [ \"$match\" == \"1\" ]\n then\n shift 2\n else\n leftovers=$(echo $leftovers $argval)\n shift\n fi\n count=$(($count+1))\ndone\n#Cleanup then restore the leftovers\nshift $#\nset -- $leftovers\n</code></pre>\n\n<p>The verbose version with built in echo demos:</p>\n\n<pre><code>#!/usr/bin/env bash\n#shebang.io\nrate=30\ntime=30\nnumber=30\necho \"all args\n$@\"\nvalidflags=\"rate time number\"\ncount=1\nfor arg in $@\ndo\n match=0\n argval=$1\n# argval=$(echo $@ | cut -d ' ' -f$count)\n for flag in $validflags\n do\n sflag=\"-\"$flag\n if [ \"$argval\" == \"$sflag\" ]\n then\n declare $flag=$2\n match=1\n fi\n done\n if [ \"$match\" == \"1\" ]\n then\n shift 2\n else\n leftovers=$(echo $leftovers $argval)\n shift\n fi\n count=$(($count+1))\ndone\n\n#Cleanup then restore the leftovers\necho \"pre final clear args:\n$@\"\nshift $#\necho \"post final clear args:\n$@\"\nset -- $leftovers\necho \"all post set args:\n$@\"\necho arg1: $1 arg2: $2\n\necho leftovers: $leftovers\necho rate $rate time $time number $number\n</code></pre>\n\n<p>Final one, this one errors out if an invalid -argument is passed through.</p>\n\n<pre><code>#!/usr/bin/env bash\n#shebang.io\nrate=30\ntime=30\nnumber=30\nvalidflags=\"rate time number\"\ncount=1\nfor arg in $@\ndo\n argval=$1\n match=0\n if [ \"${argval:0:1}\" == \"-\" ]\n then\n for flag in $validflags\n do\n sflag=\"-\"$flag\n if [ \"$argval\" == \"$sflag\" ]\n then\n declare $flag=$2\n match=1\n fi\n done\n if [ \"$match\" == \"0\" ]\n then\n echo \"Bad argument: $argval\"\n exit 1\n fi\n shift 2\n else\n leftovers=$(echo $leftovers $argval)\n shift\n fi\n count=$(($count+1))\ndone\n#Cleanup then restore the leftovers\nshift $#\nset -- $leftovers\necho rate $rate time $time number $number\necho leftovers: $leftovers\n</code></pre>\n\n<p>Pros: What it does, it handles very well. It preserves unused arguments which a lot of the other solutions here don't. It also allows for variables to be called without being defined by hand in the script. It also allows prepopulation of variables if no corresponding argument is given. (See verbose example).</p>\n\n<p>Cons: Can't parse a single complex arg string e.g. -xcvf would process as a single argument. You could somewhat easily write additional code into mine that adds this functionality though. </p>\n" }, { "answer_id": 39376824, "author": "phyatt", "author_id": 999943, "author_profile": "https://Stackoverflow.com/users/999943", "pm_score": 5, "selected": false, "text": "<p>This example shows how to use <code>getopt</code> and <code>eval</code> and <code>HEREDOC</code> and <code>shift</code> to handle short and long parameters with and without a required value that follows. Also the switch/case statement is concise and easy to follow.</p>\n<pre><code>#!/usr/bin/env bash\n\n# usage function\nfunction usage()\n{\n cat &lt;&lt; HEREDOC\n\n Usage: $progname [--num NUM] [--time TIME_STR] [--verbose] [--dry-run]\n\n optional arguments:\n -h, --help show this help message and exit\n -n, --num NUM pass in a number\n -t, --time TIME_STR pass in a time string\n -v, --verbose increase the verbosity of the bash script\n --dry-run do a dry run, dont change any files\n\nHEREDOC\n} \n\n# initialize variables\nprogname=$(basename $0)\nverbose=0\ndryrun=0\nnum_str=\ntime_str=\n\n# use getopt and store the output into $OPTS\n# note the use of -o for the short options, --long for the long name options\n# and a : for any option that takes a parameter\nOPTS=$(getopt -o &quot;hn:t:v&quot; --long &quot;help,num:,time:,verbose,dry-run&quot; -n &quot;$progname&quot; -- &quot;$@&quot;)\nif [ $? != 0 ] ; then echo &quot;Error in command line arguments.&quot; &gt;&amp;2 ; usage; exit 1 ; fi\neval set -- &quot;$OPTS&quot;\n\nwhile true; do\n # uncomment the next line to see how shift is working\n # echo &quot;\\$1:\\&quot;$1\\&quot; \\$2:\\&quot;$2\\&quot;&quot;\n case &quot;$1&quot; in\n -h | --help ) usage; exit; ;;\n -n | --num ) num_str=&quot;$2&quot;; shift 2 ;;\n -t | --time ) time_str=&quot;$2&quot;; shift 2 ;;\n --dry-run ) dryrun=1; shift ;;\n -v | --verbose ) verbose=$((verbose + 1)); shift ;;\n -- ) shift; break ;;\n * ) break ;;\n esac\ndone\n\nif (( $verbose &gt; 0 )); then\n\n # print out all the parameters we read in\n cat &lt;&lt;EOM\n num=$num_str\n time=$time_str\n verbose=$verbose\n dryrun=$dryrun\nEOM\nfi\n\n# The rest of your script below\n</code></pre>\n<p>The most significant lines of the script above are these:</p>\n<pre><code>OPTS=$(getopt -o &quot;hn:t:v&quot; --long &quot;help,num:,time:,verbose,dry-run&quot; -n &quot;$progname&quot; -- &quot;$@&quot;)\nif [ $? != 0 ] ; then echo &quot;Error in command line arguments.&quot; &gt;&amp;2 ; exit 1 ; fi\neval set -- &quot;$OPTS&quot;\n\nwhile true; do\n case &quot;$1&quot; in\n -h | --help ) usage; exit; ;;\n -n | --num ) num_str=&quot;$2&quot;; shift 2 ;;\n -t | --time ) time_str=&quot;$2&quot;; shift 2 ;;\n --dry-run ) dryrun=1; shift ;;\n -v | --verbose ) verbose=$((verbose + 1)); shift ;;\n -- ) shift; break ;;\n * ) break ;;\n esac\ndone\n</code></pre>\n<p>Short, to the point, readable, and handles just about everything (IMHO).</p>\n<p>Hope that helps someone.</p>\n" }, { "answer_id": 39398359, "author": "Ponyboy47", "author_id": 1478580, "author_profile": "https://Stackoverflow.com/users/1478580", "pm_score": 5, "selected": false, "text": "<pre><code># As long as there is at least one more argument, keep looping\nwhile [[ $# -gt 0 ]]; do\n key=&quot;$1&quot;\n case &quot;$key&quot; in\n # This is a flag type option. Will catch either -f or --foo\n -f|--foo)\n FOO=1\n ;;\n # Also a flag type option. Will catch either -b or --bar\n -b|--bar)\n BAR=1\n ;;\n # This is an arg value type option. Will catch -o value or --output-file value\n -o|--output-file)\n shift # past the key and to the value\n OUTPUTFILE=&quot;$1&quot;\n ;;\n # This is an arg=value type option. Will catch -o=value or --output-file=value\n -o=*|--output-file=*)\n # No need to shift here since the value is part of the same string\n OUTPUTFILE=&quot;${key#*=}&quot;\n ;;\n *)\n # Do whatever you want with extra options\n echo &quot;Unknown option '$key'&quot;\n ;;\n esac\n # Shift after checking all the cases to get the next option\n shift\ndone\n</code></pre>\n<p>This allows you to have both space separated options/values, as well as equal defined values.</p>\n<p>So you could run your script using:</p>\n<pre><code>./myscript --foo -b -o /fizz/file.txt\n</code></pre>\n<p>as well as:</p>\n<pre><code>./myscript -f --bar -o=/fizz/file.txt\n</code></pre>\n<p>and both should have the same end result.</p>\n<p>PROS:</p>\n<ul>\n<li><p>Allows for both -arg=value and -arg value</p>\n</li>\n<li><p>Works with any arg name that you can use in bash</p>\n<ul>\n<li>Meaning -a or -arg or --arg or -a-r-g or whatever</li>\n</ul>\n</li>\n<li><p>Pure bash. No need to learn/use getopt or getopts</p>\n</li>\n</ul>\n<p>CONS:</p>\n<ul>\n<li><p>Can't combine args</p>\n<ul>\n<li>Meaning no -abc. You must do -a -b -c</li>\n</ul>\n</li>\n</ul>\n" }, { "answer_id": 42354567, "author": "Emeric Verschuur", "author_id": 3132486, "author_profile": "https://Stackoverflow.com/users/3132486", "pm_score": 2, "selected": false, "text": "<p>I have write a bash helper to write a nice bash tool</p>\n\n<p>project home: <a href=\"https://gitlab.mbedsys.org/mbedsys/bashopts\" rel=\"nofollow noreferrer\">https://gitlab.mbedsys.org/mbedsys/bashopts</a></p>\n\n<p>example:</p>\n\n<pre><code>#!/bin/bash -ei\n\n# load the library\n. bashopts.sh\n\n# Enable backtrace dusplay on error\ntrap 'bashopts_exit_handle' ERR\n\n# Initialize the library\nbashopts_setup -n \"$0\" -d \"This is myapp tool description displayed on help message\" -s \"$HOME/.config/myapprc\"\n\n# Declare the options\nbashopts_declare -n first_name -l first -o f -d \"First name\" -t string -i -s -r\nbashopts_declare -n last_name -l last -o l -d \"Last name\" -t string -i -s -r\nbashopts_declare -n display_name -l display-name -t string -d \"Display name\" -e \"\\$first_name \\$last_name\"\nbashopts_declare -n age -l number -d \"Age\" -t number\nbashopts_declare -n email_list -t string -m add -l email -d \"Email adress\"\n\n# Parse arguments\nbashopts_parse_args \"$@\"\n\n# Process argument\nbashopts_process_args\n</code></pre>\n\n<p>will give help:</p>\n\n<pre><code>NAME:\n ./example.sh - This is myapp tool description displayed on help message\n\nUSAGE:\n [options and commands] [-- [extra args]]\n\nOPTIONS:\n -h,--help Display this help\n -n,--non-interactive true Non interactive mode - [$bashopts_non_interactive] (type:boolean, default:false)\n -f,--first \"John\" First name - [$first_name] (type:string, default:\"\")\n -l,--last \"Smith\" Last name - [$last_name] (type:string, default:\"\")\n --display-name \"John Smith\" Display name - [$display_name] (type:string, default:\"$first_name $last_name\")\n --number 0 Age - [$age] (type:number, default:0)\n --email Email adress - [$email_list] (type:string, default:\"\")\n</code></pre>\n\n<p>enjoy :)</p>\n" }, { "answer_id": 42811119, "author": "a_z", "author_id": 7462070, "author_profile": "https://Stackoverflow.com/users/7462070", "pm_score": 2, "selected": false, "text": "<p>Here is my approach - using regexp.</p>\n\n<ul>\n<li>no getopts</li>\n<li>it handles block of short parameters <code>-qwerty</code></li>\n<li>it handles short parameters <code>-q -w -e</code></li>\n<li>it handles long options <code>--qwerty</code></li>\n<li>you can pass attribute to short or long option (if you are using block of short options, attribute is attached to the last option)</li>\n<li>you can use spaces or <code>=</code> to provide attributes, but attribute matches until encountering hyphen+space \"delimiter\", so in <code>--q=qwe ty</code> <code>qwe ty</code> is one attribute</li>\n<li>it handles mix of all above so <code>-o a -op attr ibute --option=att ribu te --op-tion attribute --option att-ribute</code> is valid</li>\n</ul>\n\n<p>script:</p>\n\n<pre><code>#!/usr/bin/env sh\n\nhelp_menu() {\n echo \"Usage:\n\n ${0##*/} [-h][-l FILENAME][-d]\n\nOptions:\n\n -h, --help\n display this help and exit\n\n -l, --logfile=FILENAME\n filename\n\n -d, --debug\n enable debug\n \"\n}\n\nparse_options() {\n case $opt in\n h|help)\n help_menu\n exit\n ;;\n l|logfile)\n logfile=${attr}\n ;;\n d|debug)\n debug=true\n ;;\n *)\n echo \"Unknown option: ${opt}\\nRun ${0##*/} -h for help.\"&gt;&amp;2\n exit 1\n esac\n}\noptions=$@\n\nuntil [ \"$options\" = \"\" ]; do\n if [[ $options =~ (^ *(--([a-zA-Z0-9-]+)|-([a-zA-Z0-9-]+))(( |=)(([\\_\\.\\?\\/\\\\a-zA-Z0-9]?[ -]?[\\_\\.\\?a-zA-Z0-9]+)+))?(.*)|(.+)) ]]; then\n if [[ ${BASH_REMATCH[3]} ]]; then # for --option[=][attribute] or --option[=][attribute]\n opt=${BASH_REMATCH[3]}\n attr=${BASH_REMATCH[7]}\n options=${BASH_REMATCH[9]}\n elif [[ ${BASH_REMATCH[4]} ]]; then # for block options -qwert[=][attribute] or single short option -a[=][attribute]\n pile=${BASH_REMATCH[4]}\n while (( ${#pile} &gt; 1 )); do\n opt=${pile:0:1}\n attr=\"\"\n pile=${pile/${pile:0:1}/}\n parse_options\n done\n opt=$pile\n attr=${BASH_REMATCH[7]}\n options=${BASH_REMATCH[9]}\n else # leftovers that don't match\n opt=${BASH_REMATCH[10]}\n options=\"\"\n fi\n parse_options\n fi\ndone\n</code></pre>\n" }, { "answer_id": 46677167, "author": "John", "author_id": 6815248, "author_profile": "https://Stackoverflow.com/users/6815248", "pm_score": 2, "selected": false, "text": "<p>Assume we create a shell script named <code>test_args.sh</code> as follow</p>\n\n<pre><code>#!/bin/sh\nuntil [ $# -eq 0 ]\ndo\n name=${1:1}; shift;\n if [[ -z \"$1\" || $1 == -* ]] ; then eval \"export $name=true\"; else eval \"export $name=$1\"; shift; fi \ndone\necho \"year=$year month=$month day=$day flag=$flag\"\n</code></pre>\n\n<p>After we run the following command:</p>\n\n<pre><code>sh test_args.sh -year 2017 -flag -month 12 -day 22 \n</code></pre>\n\n<p>The output would be:</p>\n\n<pre><code>year=2017 month=12 day=22 flag=true\n</code></pre>\n" }, { "answer_id": 52356831, "author": "Thanh Trung", "author_id": 509916, "author_profile": "https://Stackoverflow.com/users/509916", "pm_score": 3, "selected": false, "text": "<p>I wanna submit my project : <a href=\"https://github.com/flyingangel/argparser\" rel=\"noreferrer\">https://github.com/flyingangel/argparser</a></p>\n\n<pre><code>source argparser.sh\nparse_args \"$@\"\n</code></pre>\n\n<p>Simple as that. The environment will be populated with variables with the same name as the arguments</p>\n" }, { "answer_id": 53800415, "author": "terijo001", "author_id": 10460822, "author_profile": "https://Stackoverflow.com/users/10460822", "pm_score": 1, "selected": false, "text": "<p>Simple and easy to modify, parameters can be in any order. this can be modified to take parameters in any form (-a, --a, a, etc).</p>\n\n<pre><code>for arg in \"$@\"\ndo\n key=$(echo $arg | cut -f1 -d=)`\n value=$(echo $arg | cut -f2 -d=)`\n case \"$key\" in\n name|-name) read_name=$value;;\n id|-id) read_id=$value;;\n *) echo \"I dont know what to do with this\"\n ease\ndone\n</code></pre>\n" }, { "answer_id": 55008165, "author": "jchook", "author_id": 554406, "author_profile": "https://Stackoverflow.com/users/554406", "pm_score": 5, "selected": false, "text": "<p>Expanding on @bruno-bronosky's answer, I added a &quot;preprocessor&quot; to handle some common formatting:</p>\n<ul>\n<li>Expands <code>--longopt=val</code> into <code>--longopt val</code></li>\n<li>Expands <code>-xyz</code> into <code>-x -y -z</code></li>\n<li>Supports <code>--</code> to indicate the end of flags</li>\n<li>Shows an error for unexpected options</li>\n<li>Compact and easy-to-read options switch</li>\n</ul>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/bash\n\n# Report usage\nusage() {\n echo &quot;Usage:&quot;\n echo &quot;$(basename &quot;$0&quot;) [options] [--] [file1, ...]&quot;\n}\n\ninvalid() {\n echo &quot;ERROR: Unrecognized argument: $1&quot; &gt;&amp;2\n usage\n exit 1\n}\n\n# Pre-process options to:\n# - expand -xyz into -x -y -z\n# - expand --longopt=arg into --longopt arg\nARGV=()\nEND_OF_OPT=\nwhile [[ $# -gt 0 ]]; do\n arg=&quot;$1&quot;; shift\n case &quot;${END_OF_OPT}${arg}&quot; in\n --) ARGV+=(&quot;$arg&quot;); END_OF_OPT=1 ;;\n --*=*)ARGV+=(&quot;${arg%%=*}&quot; &quot;${arg#*=}&quot;) ;;\n --*) ARGV+=(&quot;$arg&quot;) ;;\n -*) for i in $(seq 2 ${#arg}); do ARGV+=(&quot;-${arg:i-1:1}&quot;); done ;;\n *) ARGV+=(&quot;$arg&quot;) ;;\n esac\ndone\n\n# Apply pre-processed options\nset -- &quot;${ARGV[@]}&quot;\n\n# Parse options\nEND_OF_OPT=\nPOSITIONAL=()\nwhile [[ $# -gt 0 ]]; do\n case &quot;${END_OF_OPT}${1}&quot; in\n -h|--help) usage; exit 0 ;;\n -p|--password) shift; PASSWORD=&quot;$1&quot; ;;\n -u|--username) shift; USERNAME=&quot;$1&quot; ;;\n -n|--name) shift; names+=(&quot;$1&quot;) ;;\n -q|--quiet) QUIET=1 ;;\n -C|--copy) COPY=1 ;;\n -N|--notify) NOTIFY=1 ;;\n --stdin) READ_STDIN=1 ;;\n --) END_OF_OPT=1 ;;\n -*) invalid &quot;$1&quot; ;;\n *) POSITIONAL+=(&quot;$1&quot;) ;;\n esac\n shift\ndone\n\n# Restore positional parameters\nset -- &quot;${POSITIONAL[@]}&quot;\n</code></pre>\n" }, { "answer_id": 59124908, "author": "mjs", "author_id": 961018, "author_profile": "https://Stackoverflow.com/users/961018", "pm_score": 2, "selected": false, "text": "<p>Here is a getopts that achieves the parsing with minimal code and allows you to define what you wish to extract in one case using eval with substring. </p>\n\n<p>Basically <code>eval \"local key='val'\"</code></p>\n\n<pre><code>function myrsync() {\n\n local backup=(\"${@}\") args=(); while [[ $# -gt 0 ]]; do k=\"$1\";\n case \"$k\" in\n ---sourceuser|---sourceurl|---targetuser|---targeturl|---file|---exclude|---include)\n eval \"local ${k:3}='${2}'\"; shift; shift # Past two arguments\n ;;\n *) # Unknown option \n args+=(\"$1\"); shift; # Past argument only\n ;; \n esac \n done; set -- \"${backup[@]}\" # Restore $@\n\n\n echo \"${sourceurl}\"\n}\n</code></pre>\n\n<p>Declares the variables as locals instead of globals as most answers here. </p>\n\n<p>Called as: </p>\n\n<pre><code>myrsync ---sourceurl http://abc.def.g ---sourceuser myuser ... \n</code></pre>\n\n<p>The ${k:3} is basically a substring to remove the first <code>---</code> from the key. </p>\n" }, { "answer_id": 59463093, "author": "tmoschou", "author_id": 547569, "author_profile": "https://Stackoverflow.com/users/547569", "pm_score": 3, "selected": false, "text": "<p>There are several ways to parse cmdline args (e.g. GNU getopt (not portable) vs BSD (MacOS) getopt vs getopts) - all problematic. This solution</p>\n<ul>\n<li>is portable!</li>\n<li>has zero dependencies, only relies on bash built-ins</li>\n<li>allows for both short and long options</li>\n<li>handles whitespace or simultaneously the use of <code>=</code> separator between option and argument</li>\n<li>supports concatenated short option style <code>-vxf</code></li>\n<li>handles option with optional arguments (E.g. <code>--color</code> vs <code>--color=always</code>),</li>\n<li>correctly detects and reports unknown options</li>\n<li>supports <code>--</code> to signal end of options, and</li>\n<li>doesn't require code bloat compared with alternatives for the same feature set. I.e. succinct, and therefore easier to maintain</li>\n</ul>\n<p>Examples: Any of</p>\n<pre><code># flag\n-f\n--foo\n\n# option with required argument\n-b&quot;Hello World&quot;\n-b &quot;Hello World&quot;\n--bar &quot;Hello World&quot;\n--bar=&quot;Hello World&quot;\n\n# option with optional argument\n--baz\n--baz=&quot;Optional Hello&quot;\n</code></pre>\n<hr />\n<pre><code>#!/usr/bin/env bash\n\nusage() {\n cat - &gt;&amp;2 &lt;&lt;EOF\nNAME\n program-name.sh - Brief description\n \nSYNOPSIS\n program-name.sh [-h|--help]\n program-name.sh [-f|--foo]\n [-b|--bar &lt;arg&gt;]\n [--baz[=&lt;arg&gt;]]\n [--]\n FILE ...\n\nREQUIRED ARGUMENTS\n FILE ...\n input files\n\nOPTIONS\n -h, --help\n Prints this and exits\n\n -f, --foo\n A flag option\n \n -b, --bar &lt;arg&gt;\n Option requiring an argument &lt;arg&gt;\n\n --baz[=&lt;arg&gt;]\n Option that has an optional argument &lt;arg&gt;. If &lt;arg&gt;\n is not specified, defaults to 'DEFAULT'\n -- \n Specify end of options; useful if the first non option\n argument starts with a hyphen\n\nEOF\n}\n\nfatal() {\n for i; do\n echo -e &quot;${i}&quot; &gt;&amp;2\n done\n exit 1\n}\n\n# For long option processing\nnext_arg() {\n if [[ $OPTARG == *=* ]]; then\n # for cases like '--opt=arg'\n OPTARG=&quot;${OPTARG#*=}&quot;\n else\n # for cases like '--opt arg'\n OPTARG=&quot;${args[$OPTIND]}&quot;\n OPTIND=$((OPTIND + 1))\n fi\n}\n\n# ':' means preceding option character expects one argument, except\n# first ':' which make getopts run in silent mode. We handle errors with\n# wildcard case catch. Long options are considered as the '-' character\noptspec=&quot;:hfb:-:&quot;\nargs=(&quot;&quot; &quot;$@&quot;) # dummy first element so $1 and $args[1] are aligned\nwhile getopts &quot;$optspec&quot; optchar; do\n case &quot;$optchar&quot; in\n h) usage; exit 0 ;;\n f) foo=1 ;;\n b) bar=&quot;$OPTARG&quot; ;;\n -) # long option processing\n case &quot;$OPTARG&quot; in\n help)\n usage; exit 0 ;;\n foo)\n foo=1 ;;\n bar|bar=*) next_arg\n bar=&quot;$OPTARG&quot; ;;\n baz)\n baz=DEFAULT ;;\n baz=*) next_arg\n baz=&quot;$OPTARG&quot; ;;\n -) break ;;\n *) fatal &quot;Unknown option '--${OPTARG}'&quot; &quot;see '${0} --help' for usage&quot; ;;\n esac\n ;;\n *) fatal &quot;Unknown option: '-${OPTARG}'&quot; &quot;See '${0} --help' for usage&quot; ;;\n esac\ndone\n\nshift $((OPTIND-1))\n\nif [ &quot;$#&quot; -eq 0 ]; then\n fatal &quot;Expected at least one required argument FILE&quot; \\\n &quot;See '${0} --help' for usage&quot;\nfi\n\necho &quot;foo=$foo, bar=$bar, baz=$baz, files=${@}&quot;\n</code></pre>\n" }, { "answer_id": 61139993, "author": "Mihir Luthra", "author_id": 11498773, "author_profile": "https://Stackoverflow.com/users/11498773", "pm_score": 2, "selected": false, "text": "<p>I wanted to share what I made for parsing options.\nSome of my needs were not fulfilled by the answers here so I had to come up with this: <a href=\"https://github.com/MihirLuthra/bash_option_parser\" rel=\"nofollow noreferrer\">https://github.com/MihirLuthra/bash_option_parser</a></p>\n<p>This supports:</p>\n<ul>\n<li>Suboption parsing</li>\n<li>Alias names for options</li>\n<li>Optional args</li>\n<li>Variable args</li>\n<li>Printing usage and errors</li>\n</ul>\n<p>Let's say we have a command named <code>fruit</code> with usage as follows:</p>\n<pre><code>fruit &lt;fruit-name&gt; ...\n [-e|—-eat|—-chew]\n [-c|--cut &lt;how&gt; &lt;why&gt;]\n &lt;command&gt; [&lt;args&gt;] \n</code></pre>\n<p><code>-e</code> takes no args<br>\n<code>-c</code> takes two args i.e. how to cut and why to cut<br>\n<code>fruit</code> itself takes at least one argument.<br>\n<code>&lt;command&gt;</code> is for suboptions like <code>apple</code>, <code>orange</code> etc. (similar to <code>git</code> which has suboptions <code>commit</code>, <code>push</code> etc. )</p>\n<p>So to parse it:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>parse_options \\\n 'fruit' '1 ...' \\\n '-e' , '--eat' , '--chew' '0' \\\n '-c' , '--cut' '1 1' \\\n 'apple' 'S' \\\n 'orange' 'S' \\\n ';' \\\n &quot;$@&quot;\n</code></pre>\n<p>Now if there was any usage error, it can be printed using <code>option_parser_error_msg</code> as follows:</p>\n<pre><code>retval=$?\n\nif [ $retval -ne 0 ]; then\n # this will manage error messages if\n # insufficient or extra args are supplied\n\n option_parser_error_msg &quot;$retval&quot;\n\n # This will print the usage\n print_usage 'fruit'\n exit 1\nfi\n</code></pre>\n<p>To check now if some options was passed,</p>\n<pre><code>if [ -n &quot;${OPTIONS[-c]}&quot; ]\nthen\n echo &quot;-c was passed&quot;\n\n # args can be accessed in a 2D-array-like format\n echo &quot;Arg1 to -c = ${ARGS[-c,0]}&quot;\n echo &quot;Arg2 to -c = ${ARGS[-c,1]}&quot;\n\nfi\n</code></pre>\n<p>Suboption parsing can also be done by passing <code>$shift_count</code> to <code>parse_options_detailed</code> which makes it start parsing after shifting args to reach args of suboption. It is demonstrated in this <a href=\"https://github.com/MihirLuthra/bash_option_parser/blob/master/example\" rel=\"nofollow noreferrer\">example</a>.</p>\n<p>A detailed description is provided in the readme and examples\nin the <a href=\"https://github.com/MihirLuthra/bash_option_parser\" rel=\"nofollow noreferrer\">repository</a>.</p>\n" }, { "answer_id": 62616466, "author": "leogama", "author_id": 3738764, "author_profile": "https://Stackoverflow.com/users/3738764", "pm_score": 4, "selected": false, "text": "<h1>Another Shell Argument Parser (ASAP)</h1>\n<h2>POSIX compliant, no <code>getopt(s)</code></h2>\n<p>I was inspired by the relatively simple <a href=\"https://stackoverflow.com/a/31443098/3738764\">answer by @bronson</a> and tempted to try to improve it (without adding too much complexity). Here's the result:</p>\n<ul>\n<li>Use any of the <code>-n [arg]</code>, <code>-abn [arg]</code>, <code>--name [arg]</code> <strong>and</strong> <code>--name=arg</code> styles of options;</li>\n<li>Arguments may occur in any order, only <strong>positional ones are left in</strong> <code>$@</code> after the loop;</li>\n<li><strong>Use</strong> <code>--</code> <strong>to force</strong> remaining arguments to be treated as positional;</li>\n<li>Detects invalid options and missing arguments;</li>\n<li>Doesn't depend on <code>getopt(s)</code> or external tools (one feature uses a simple <code>sed</code> command);</li>\n<li>Portable, compact, quite readable, with <strong>independent features</strong>.</li>\n</ul>\n<pre class=\"lang-bash prettyprint-override\"><code># Convenience functions.\nusage_error () { echo &gt;&amp;2 &quot;$(basename $0): $1&quot;; exit 2; }\nassert_argument () { test &quot;$1&quot; != &quot;$EOL&quot; || usage_error &quot;$2 requires an argument&quot;; }\n\n# One loop, nothing more.\nif [ &quot;$#&quot; != 0 ]; then\n EOL=$(printf '\\1\\3\\3\\7')\n set -- &quot;$@&quot; &quot;$EOL&quot;\n while [ &quot;$1&quot; != &quot;$EOL&quot; ]; do\n opt=&quot;$1&quot;; shift\n case &quot;$opt&quot; in\n\n # Your options go here.\n -f|--flag) flag='true';;\n -n|--name) assert_argument &quot;$1&quot; &quot;$opt&quot;; name=&quot;$1&quot;; shift;;\n\n # Arguments processing. You may remove any unneeded line after the 1st.\n -|''|[!-]*) set -- &quot;$@&quot; &quot;$opt&quot;;; # positional argument, rotate to the end\n --*=*) set -- &quot;${opt%%=*}&quot; &quot;${opt#*=}&quot; &quot;$@&quot;;; # convert '--name=arg' to '--name' 'arg'\n -[!-]?*) set -- $(echo &quot;${opt#-}&quot; | sed 's/\\(.\\)/ -\\1/g') &quot;$@&quot;;; # convert '-abc' to '-a' '-b' '-c'\n --) while [ &quot;$1&quot; != &quot;$EOL&quot; ]; do set -- &quot;$@&quot; &quot;$1&quot;; shift; done;; # process remaining arguments as positional\n -*) usage_error &quot;unknown option: '$opt'&quot;;; # catch misspelled options\n *) usage_error &quot;this should NEVER happen ($opt)&quot;;; # sanity test for previous patterns\n\n esac\n done\n shift # $EOL\nfi\n\n# Do something cool with &quot;$@&quot;... \\o/\n</code></pre>\n<p><em>Note:</em> I know... An argument with the <em>binary pattern</em> <code>0x01030307</code> could break the logic. But, if anyone passes such an argument in a command-line, they deserve it.</p>\n" }, { "answer_id": 63044632, "author": "Meir Gabay", "author_id": 5285732, "author_profile": "https://Stackoverflow.com/users/5285732", "pm_score": 2, "selected": false, "text": "<p>I wrote down a script that can assist with parsing command-line arguments easily - <a href=\"https://github.com/unfor19/bargs\" rel=\"nofollow noreferrer\">https://github.com/unfor19/bargs</a></p>\n<h3>Examples</h3>\n<pre class=\"lang-sh prettyprint-override\"><code>$ bash example.sh -n Willy --gender male -a 99\nName: Willy\nAge: 99\nGender: male\nLocation: chocolate-factory\n</code></pre>\n<pre class=\"lang-sh prettyprint-override\"><code>$ bash example.sh -n Meir --gender male\n[ERROR] Required argument: age\n\nUsage: bash example.sh -n Willy --gender male -a 99\n\n--person_name | -n [Willy] What is your name?\n--age | -a [Required]\n--gender | -g [Required]\n--location | -l [chocolate-factory] insert your location\n</code></pre>\n<pre><code>$ bash example.sh -h\n\nUsage: bash example.sh -n Willy --gender male -a 99\n--person_name | -n [Willy] What is your name?\n--age | -a [Required]\n--gender | -g [Required]\n--location | -l [chocolate-factory] insert your location\n</code></pre>\n" }, { "answer_id": 63413837, "author": "Koichi Nakashima", "author_id": 11267590, "author_profile": "https://Stackoverflow.com/users/11267590", "pm_score": 4, "selected": false, "text": "<h1>Yet another option parser (generator)</h1>\n<p>An elegant option parser for shell scripts (full support for all POSIX shells)\n<a href=\"https://github.com/ko1nksm/getoptions\" rel=\"nofollow noreferrer\">https://github.com/ko1nksm/getoptions</a> (Update: v3.3.0 released on 2021-05-02)</p>\n<p><strong>getoptions</strong> is a new option parser (generator) written in POSIX-compliant shell script and released in august 2020. It is for those who want to support the POSIX / GNU style option syntax in your shell scripts.</p>\n<p>The supported syntaxes are <code>-a</code>, <code>+a</code>, <code>-abc</code>, <code>-vvv</code>, <code>-p VALUE</code>, <code>-pVALUE</code>, <code>--flag</code>, <code>--no-flag</code>, <code>--with-flag</code>, <code>--without-flag</code>, <code>--param VALUE</code>, <code>--param=VALUE</code>, <code>--option[=VALUE]</code>, <code>--no-option</code> <code>--</code>.</p>\n<p>It supports subcommands, validation, abbreviated options, and automatic help generation. And works with all POSIX shells (dash 0.5.4+, bash 2.03+, ksh88+, mksh R28+, zsh 3.1.9+, yash 2.29+, busybox ash 1.1.3+, etc).</p>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/sh\n\nVERSION=&quot;0.1&quot;\n\nparser_definition() {\n setup REST help:usage -- &quot;Usage: example.sh [options]... [arguments]...&quot; ''\n msg -- 'Options:'\n flag FLAG -f --flag -- &quot;takes no arguments&quot;\n param PARAM -p --param -- &quot;takes one argument&quot;\n option OPTION -o --option on:&quot;default&quot; -- &quot;takes one optional argument&quot;\n disp :usage -h --help\n disp VERSION --version\n}\n\neval &quot;$(getoptions parser_definition) exit 1&quot;\n\necho &quot;FLAG: $FLAG, PARAM: $PARAM, OPTION: $OPTION&quot;\nprintf '%s\\n' &quot;$@&quot; # rest arguments\n</code></pre>\n<p>It's parses the following arguments:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>example.sh -f --flag -p VALUE --param VALUE -o --option -oVALUE --option=VALUE 1 2 3\n</code></pre>\n<p>And automatic help generation.</p>\n<pre class=\"lang-sh prettyprint-override\"><code>$ example.sh --help\n\nUsage: example.sh [options]... [arguments]...\n\nOptions:\n -f, --flag takes no arguments\n -p, --param PARAM takes one argument\n -o, --option[=OPTION] takes one optional argument\n -h, --help\n --version\n</code></pre>\n<p>It is also an option parser generator, generates the following simple option parsing code. If you use the generated code, you won't need <code>getoptions</code>. <strong>Achieve true portability and zero dependency.</strong></p>\n<pre class=\"lang-sh prettyprint-override\"><code>FLAG=''\nPARAM=''\nOPTION=''\nREST=''\ngetoptions_parse() {\n OPTIND=$(($#+1))\n while OPTARG= &amp;&amp; [ $# -gt 0 ]; do\n case $1 in\n --?*=*) OPTARG=$1; shift\n eval 'set -- &quot;${OPTARG%%\\=*}&quot; &quot;${OPTARG#*\\=}&quot;' ${1+'&quot;$@&quot;'}\n ;;\n --no-*|--without-*) unset OPTARG ;;\n -[po]?*) OPTARG=$1; shift\n eval 'set -- &quot;${OPTARG%&quot;${OPTARG#??}&quot;}&quot; &quot;${OPTARG#??}&quot;' ${1+'&quot;$@&quot;'}\n ;;\n -[fh]?*) OPTARG=$1; shift\n eval 'set -- &quot;${OPTARG%&quot;${OPTARG#??}&quot;}&quot; -&quot;${OPTARG#??}&quot;' ${1+'&quot;$@&quot;'}\n OPTARG= ;;\n esac\n case $1 in\n '-f'|'--flag')\n [ &quot;${OPTARG:-}&quot; ] &amp;&amp; OPTARG=${OPTARG#*\\=} &amp;&amp; set &quot;noarg&quot; &quot;$1&quot; &amp;&amp; break\n eval '[ ${OPTARG+x} ] &amp;&amp;:' &amp;&amp; OPTARG='1' || OPTARG=''\n FLAG=&quot;$OPTARG&quot;\n ;;\n '-p'|'--param')\n [ $# -le 1 ] &amp;&amp; set &quot;required&quot; &quot;$1&quot; &amp;&amp; break\n OPTARG=$2\n PARAM=&quot;$OPTARG&quot;\n shift ;;\n '-o'|'--option')\n set -- &quot;$1&quot; &quot;$@&quot;\n [ ${OPTARG+x} ] &amp;&amp; {\n case $1 in --no-*|--without-*) set &quot;noarg&quot; &quot;${1%%\\=*}&quot;; break; esac\n [ &quot;${OPTARG:-}&quot; ] &amp;&amp; { shift; OPTARG=$2; } || OPTARG='default'\n } || OPTARG=''\n OPTION=&quot;$OPTARG&quot;\n shift ;;\n '-h'|'--help')\n usage\n exit 0 ;;\n '--version')\n echo &quot;${VERSION}&quot;\n exit 0 ;;\n --)\n shift\n while [ $# -gt 0 ]; do\n REST=&quot;${REST} \\&quot;\\${$(($OPTIND-$#))}\\&quot;&quot;\n shift\n done\n break ;;\n [-]?*) set &quot;unknown&quot; &quot;$1&quot;; break ;;\n *)\n REST=&quot;${REST} \\&quot;\\${$(($OPTIND-$#))}\\&quot;&quot;\n esac\n shift\n done\n [ $# -eq 0 ] &amp;&amp; { OPTIND=1; unset OPTARG; return 0; }\n case $1 in\n unknown) set &quot;Unrecognized option: $2&quot; &quot;$@&quot; ;;\n noarg) set &quot;Does not allow an argument: $2&quot; &quot;$@&quot; ;;\n required) set &quot;Requires an argument: $2&quot; &quot;$@&quot; ;;\n pattern:*) set &quot;Does not match the pattern (${1#*:}): $2&quot; &quot;$@&quot; ;;\n notcmd) set &quot;Not a command: $2&quot; &quot;$@&quot; ;;\n *) set &quot;Validation error ($1): $2&quot; &quot;$@&quot;\n esac\n echo &quot;$1&quot; &gt;&amp;2\n exit 1\n}\nusage() {\ncat&lt;&lt;'GETOPTIONSHERE'\nUsage: example.sh [options]... [arguments]...\n\nOptions:\n -f, --flag takes no arguments\n -p, --param PARAM takes one argument\n -o, --option[=OPTION] takes one optional argument\n -h, --help\n --version\nGETOPTIONSHERE\n}\n</code></pre>\n" }, { "answer_id": 66573181, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I use it to iterate over <strong>key =&gt; value</strong> from the end. A first optional argument is caught after the loop.</p>\n<p>Usage is ./script.sh <em>optional-first-arg</em> -key value -key2 value2</p>\n<pre><code>#!/bin/sh\n\na=$(($#-1))\nb=$(($#))\nwhile [ $a -gt 0 ]; do\n eval 'key=&quot;$'$a'&quot;; value=&quot;$'$b'&quot;'\n echo &quot;$key =&gt; $value&quot;\n b=$(($b-2))\n a=$(($a-2))\ndone\nunset a b key value\n\n[ $(($#%2)) -ne 0 ] &amp;&amp; echo &quot;first_arg = $1&quot;\n\n</code></pre>\n<p>Sure you can do it from the left to the right with a few changes.</p>\n<p>This snippet code shows the <strong>key =&gt; value</strong> pairs and the first argument if it exists.</p>\n<pre><code>#!/bin/sh\n\na=$((1+$#%2))\nb=$((1+$a))\n\n[ $(($#%2)) -ne 0 ] &amp;&amp; echo &quot;first_arg = $1&quot;\n\nwhile [ $a -lt $# ]; do\n eval 'key=&quot;$'$a'&quot;; value=&quot;$'$b'&quot;'\n echo &quot;$key =&gt; $value&quot;\n b=$(($b+2))\n a=$(($a+2))\ndone\n\nunset a b key value\n\n</code></pre>\n<p>Tested with 100,000 arguments, fast.</p>\n<p>You can also iterate <strong>key =&gt; value</strong> and <em>first optional arg</em> from the left to the right without eval :</p>\n<pre><code>#!/bin/sh\n\na=$(($#%2))\nb=0\n\n[ $a -eq 1 ] &amp;&amp; echo &quot;first_arg = $1&quot;\n\nfor value; do\n if [ $b -gt $a -a $(($b%2)) -ne $a ]; then\n echo &quot;$key =&gt; $value&quot;\n fi\n key=&quot;$value&quot;\n b=$((1+$b))\ndone\n\nunset a b key value\n\n</code></pre>\n" }, { "answer_id": 67963449, "author": "Top-Master", "author_id": 8740349, "author_profile": "https://Stackoverflow.com/users/8740349", "pm_score": 2, "selected": false, "text": "<p>I ended up implementing the <code>dash</code> (or <code>/bin/sh</code>) version of the <a href=\"https://stackoverflow.com/a/14203146/8740349\">accepted answer</a>, basically, without array usage:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>while [[ $# -gt 0 ]]; do\n case &quot;$1&quot; in\n -v|--verbose) verbose=1; shift;;\n -o|--output) if [[ $# -gt 1 &amp;&amp; &quot;$2&quot; != -* ]]; then\n file=$2; shift 2\n else\n echo &quot;-o requires file-path&quot; 1&gt;&amp;2; exit 1\n fi ;;\n --)\n while [[ $# -gt 0 ]]; do BACKUP=&quot;$BACKUP;$1&quot;; shift; done\n break;;\n *)\n BACKUP=&quot;$BACKUP;$1&quot;\n shift\n ;;\n esac\ndone\n# Restore unused arguments.\nwhile [ -n &quot;$BACKUP&quot; ] ; do\n [ ! -z &quot;${BACKUP%%;*}&quot; ] &amp;&amp; set -- &quot;$@&quot; &quot;${BACKUP%%;*}&quot;\n [ &quot;$BACKUP&quot; = &quot;${BACKUP/;/}&quot; ] &amp;&amp; break\n BACKUP=&quot;${BACKUP#*;}&quot;\ndone\n</code></pre>\n" }, { "answer_id": 69736953, "author": "CIsForCookies", "author_id": 3512538, "author_profile": "https://Stackoverflow.com/users/3512538", "pm_score": 3, "selected": false, "text": "<p>Based on other answers here, this my version:</p>\n<pre><code>#!/bin/bash\nset -e\n\nfunction parse() {\n for arg in &quot;$@&quot;; do # transform long options to short ones\n shift\n case &quot;$arg&quot; in\n &quot;--name&quot;) set -- &quot;$@&quot; &quot;-n&quot; ;;\n &quot;--verbose&quot;) set -- &quot;$@&quot; &quot;-v&quot; ;;\n *) set -- &quot;$@&quot; &quot;$arg&quot;\n esac\n done\n\n while getopts &quot;n:v&quot; optname # left to &quot;:&quot; are flags that expect a value, right to the &quot;:&quot; are flags that expect nothing\n do\n case &quot;$optname&quot; in\n &quot;n&quot;) name=${OPTARG} ;;\n &quot;v&quot;) verbose=true ;;\n esac\n done\n shift &quot;$((OPTIND-1))&quot; # shift out all the already processed options\n}\n\n\nparse &quot;$@&quot;\necho &quot;hello $name&quot;\nif [ ! -z $verbose ]; then echo 'nice to meet you!'; fi\n</code></pre>\n<p>Usage:</p>\n<pre><code>$ ./parse.sh\nhello\n$ ./parse.sh -n YOUR_NAME\nhello YOUR_NAME\n$ ./parse.sh -n YOUR_NAME -v\nhello YOUR_NAME\nnice to meet you!\n$ ./parse.sh -v -n YOUR_NAME\nhello YOUR_NAME\nnice to meet you!\n$ ./parse.sh -v\nhello \nnice to meet you!\n</code></pre>\n" }, { "answer_id": 72242057, "author": "mgutt", "author_id": 318765, "author_profile": "https://Stackoverflow.com/users/318765", "pm_score": 1, "selected": false, "text": "<p>I'm using a combination of <code>optget</code> and <code>optgets</code> to parse short and long options with or without arguments and even non-options (those without <code>-</code> or <code>--</code>):</p>\n<pre><code># catch wrong options and move non-options to the end of the string\nargs=$(getopt -l &quot;$opt_long&quot; &quot;$opt_short&quot; &quot;$@&quot; 2&gt; &gt;(sed -e 's/^/stderr/g')) || echo -n &quot;Error: &quot; &amp;&amp; echo &quot;$args&quot; | grep -oP &quot;(?&lt;=^stderr).*&quot; &amp;&amp; exit 1\nmapfile -t args &lt; &lt;(xargs -n1 &lt;&lt;&lt; &quot;$(echo &quot;$args&quot; | sed -E &quot;s/(--[^ ]+) /\\1=/g&quot;)&quot; )\nset -- &quot;${args[@]}&quot;\n\n# parse short and long options\nwhile getopts &quot;$opt_short-:&quot; opt; do\n ...\ndone\n\n# remove all parsed options from $@\nshift $((OPTIND-1)\n</code></pre>\n<p>By that I'm able to access all options with a variable like <code>$opt_verbose</code> and the non-options are accessible through the default variables <code>$1</code>, <code>$2</code>, etc.:</p>\n<pre><code>echo &quot;help:$opt_help&quot;\necho &quot;file:$opt_file&quot;\necho &quot;verbose:$opt_verbose&quot;\necho &quot;long_only:$opt_long_only&quot;\necho &quot;short_only:$opt_s&quot;\necho &quot;path:$1&quot;\necho &quot;mail:$2&quot;\n</code></pre>\n<p>One of the main features is, that I'm able to pass all options and non-options in a complete random order:</p>\n<pre><code># $opt_file $1 $2 $opt_... $opt_... $opt_...\n# /demo.sh --file=file.txt /dir [email protected] -V -h --long_only=yes -s\nhelp:1\nfile:file.txt\nverbose:1\nlong_only:yes\nshort_only:1\npath:/dir\nmail:[email protected]\n</code></pre>\n<p>More details:\n<a href=\"https://stackoverflow.com/a/74275254/318765\">https://stackoverflow.com/a/74275254/318765</a></p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
Say, I have a script that gets called with this line: ``` ./myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile ``` or this one: ``` ./myscript -v -f -d -o /fizz/someOtherFile ./foo/bar/someFile ``` What's the accepted way of parsing this such that in each case (or some combination of the two) `$v`, `$f`, and `$d` will all be set to `true` and `$outFile` will be equal to `/fizz/someOtherFile`?
#### Bash Space-Separated (e.g., `--option argument`) ```sh cat >/tmp/demo-space-separated.sh <<'EOF' #!/bin/bash POSITIONAL_ARGS=() while [[ $# -gt 0 ]]; do case $1 in -e|--extension) EXTENSION="$2" shift # past argument shift # past value ;; -s|--searchpath) SEARCHPATH="$2" shift # past argument shift # past value ;; --default) DEFAULT=YES shift # past argument ;; -*|--*) echo "Unknown option $1" exit 1 ;; *) POSITIONAL_ARGS+=("$1") # save positional arg shift # past argument ;; esac done set -- "${POSITIONAL_ARGS[@]}" # restore positional parameters echo "FILE EXTENSION = ${EXTENSION}" echo "SEARCH PATH = ${SEARCHPATH}" echo "DEFAULT = ${DEFAULT}" echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l) if [[ -n $1 ]]; then echo "Last line of file specified as non-opt/last argument:" tail -1 "$1" fi EOF chmod +x /tmp/demo-space-separated.sh /tmp/demo-space-separated.sh -e conf -s /etc /etc/hosts ``` ##### Output from copy-pasting the block above ```sh FILE EXTENSION = conf SEARCH PATH = /etc DEFAULT = Number files in SEARCH PATH with EXTENSION: 14 Last line of file specified as non-opt/last argument: #93.184.216.34 example.com ``` ##### Usage ```bash demo-space-separated.sh -e conf -s /etc /etc/hosts ``` --- #### Bash Equals-Separated (e.g., `--option=argument`) ```sh cat >/tmp/demo-equals-separated.sh <<'EOF' #!/bin/bash for i in "$@"; do case $i in -e=*|--extension=*) EXTENSION="${i#*=}" shift # past argument=value ;; -s=*|--searchpath=*) SEARCHPATH="${i#*=}" shift # past argument=value ;; --default) DEFAULT=YES shift # past argument with no value ;; -*|--*) echo "Unknown option $i" exit 1 ;; *) ;; esac done echo "FILE EXTENSION = ${EXTENSION}" echo "SEARCH PATH = ${SEARCHPATH}" echo "DEFAULT = ${DEFAULT}" echo "Number files in SEARCH PATH with EXTENSION:" $(ls -1 "${SEARCHPATH}"/*."${EXTENSION}" | wc -l) if [[ -n $1 ]]; then echo "Last line of file specified as non-opt/last argument:" tail -1 $1 fi EOF chmod +x /tmp/demo-equals-separated.sh /tmp/demo-equals-separated.sh -e=conf -s=/etc /etc/hosts ``` ##### Output from copy-pasting the block above ```sh FILE EXTENSION = conf SEARCH PATH = /etc DEFAULT = Number files in SEARCH PATH with EXTENSION: 14 Last line of file specified as non-opt/last argument: #93.184.216.34 example.com ``` ##### Usage ```bash demo-equals-separated.sh -e=conf -s=/etc /etc/hosts ``` --- To better understand `${i#*=}` search for "Substring Removal" in [this guide](http://tldp.org/LDP/abs/html/string-manipulation.html). It is functionally equivalent to ``sed 's/[^=]*=//' <<< "$i"`` which calls a needless subprocess or ``echo "$i" | sed 's/[^=]*=//'`` which calls *two* needless subprocesses. --- #### Using bash with getopt[s] getopt(1) limitations (older, relatively-recent `getopt` versions): * can't handle arguments that are empty strings * can't handle arguments with embedded whitespace More recent `getopt` versions don't have these limitations. For more information, see these [docs](https://mywiki.wooledge.org/BashFAQ/035#getopts). --- #### POSIX getopts Additionally, the POSIX shell and others offer `getopts` which doen't have these limitations. I've included a simplistic `getopts` example. ```sh cat >/tmp/demo-getopts.sh <<'EOF' #!/bin/sh # A POSIX variable OPTIND=1 # Reset in case getopts has been used previously in the shell. # Initialize our own variables: output_file="" verbose=0 while getopts "h?vf:" opt; do case "$opt" in h|\?) show_help exit 0 ;; v) verbose=1 ;; f) output_file=$OPTARG ;; esac done shift $((OPTIND-1)) [ "${1:-}" = "--" ] && shift echo "verbose=$verbose, output_file='$output_file', Leftovers: $@" EOF chmod +x /tmp/demo-getopts.sh /tmp/demo-getopts.sh -vf /etc/hosts foo bar ``` ##### Output from copy-pasting the block above ```sh verbose=1, output_file='/etc/hosts', Leftovers: foo bar ``` ##### Usage ```bash demo-getopts.sh -vf /etc/hosts foo bar ``` The advantages of `getopts` are: 1. It's more portable, and will work in other shells like `dash`. 2. It can handle multiple single options like `-vf filename` in the typical Unix way, automatically. The disadvantage of `getopts` is that it can only handle short options (`-h`, not `--help`) without additional code. There is a [getopts tutorial](http://wiki.bash-hackers.org/howto/getopts_tutorial) which explains what all of the syntax and variables mean. In bash, there is also `help getopts`, which might be informative.
192,256
<p>What would be the best method to implement extra functionality in a database layer that uses Linq-to-SQL? Currently I'm looking at implementing functions for adding information based on presets and similar tasks?</p> <p>Inserts, updates and deletes requires access to the <code>DataContext</code> and in the <code>Table</code> classes you don't have access to the context. I've seen solutions that uses Singletons but it seems like a hack and I wonder if anyone else has run into this problem and what your solutions were? Is there a better way all together to implement similar functionality.</p> <p>The reason for me looking to add this functionality to the database layer is that I have several applications that all use the same database objects and I want to be able to use these functions from all applications so I don't have to rewrite a lot of code.</p> <hr> <p>That's not quite what I meant. I want to be able to do complex actions like updating one table and adding a record to another table based on information from the first one.</p> <p>Say I have selected a Customer record and I want to update this with information, and when this happens I want it to add another record to the "Updates" table to keep track of when updates happened and who did them. This is only an example of course. Things needed to be done can be more complex.</p> <p>Basically I want to add a method to a table object to perform modifications to a specific row in that table and then do inserts and updates on other objects. I know that you can use partial classes and I do that extensively already.</p> <p>Example:</p> <pre><code>db.Customers.Where(c =&gt; c.CustomerID == 5).AddOrder(orderDetails); </code></pre> <p>I feel that I can't really put my problem into words to make it understandable :)</p>
[ { "answer_id": 192338, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I hate to say it, but what about stored procedures? </p>\n\n<p>On my project, whatever extra functionality we want to provide we stick in a partial class. The data context class is marked partial, so you can add methods to the context without worrying about re-generating the context nuking your work. </p>\n" }, { "answer_id": 193082, "author": "aogan", "author_id": 4795, "author_profile": "https://Stackoverflow.com/users/4795", "pm_score": 0, "selected": false, "text": "<p>You can use generic data context extensions for common data access methods like insert,delete etc as described in <a href=\"http://weblogs.asp.net/stephenwalther/archive/2008/08/26/asp-net-mvc-tip-38-simplify-linq-to-sql-with-extension-methods.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/stephenwalther/archive/2008/08/26/asp-net-mvc-tip-38-simplify-linq-to-sql-with-extension-methods.aspx</a>. and partial classes for less common functionality as Will suggested.</p>\n" }, { "answer_id": 237147, "author": "Thomas Eyde", "author_id": 3282, "author_profile": "https://Stackoverflow.com/users/3282", "pm_score": 1, "selected": false, "text": "<p>Entity classes in Linq to SQL are partial. You could extend them with the rules you need. </p>\n\n<p>Or you could build your own business entities from the Linq to SQL entities. Your business entities would then contain the rules on when to do what.</p>\n" }, { "answer_id": 7253842, "author": "dougajmcdonald", "author_id": 777733, "author_profile": "https://Stackoverflow.com/users/777733", "pm_score": 1, "selected": false, "text": "<p>If you're purely after adding some wrapper functionality around linq or any class generally, could you not use the Extension method approach in C# 3 and above by using static helper methods along these lines:</p>\n\n<pre><code>public static class StringExtensions \n{\n public static int ToInt(this string oString)\n {\n return int.Parse(oString);\n }\n}\n</code></pre>\n\n<p>That way you could have a static helper class offering helper functionality specific to particular classes which you can port about between projects or possibly chuck into a seperate DLL and just import where needed?</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26746/" ]
What would be the best method to implement extra functionality in a database layer that uses Linq-to-SQL? Currently I'm looking at implementing functions for adding information based on presets and similar tasks? Inserts, updates and deletes requires access to the `DataContext` and in the `Table` classes you don't have access to the context. I've seen solutions that uses Singletons but it seems like a hack and I wonder if anyone else has run into this problem and what your solutions were? Is there a better way all together to implement similar functionality. The reason for me looking to add this functionality to the database layer is that I have several applications that all use the same database objects and I want to be able to use these functions from all applications so I don't have to rewrite a lot of code. --- That's not quite what I meant. I want to be able to do complex actions like updating one table and adding a record to another table based on information from the first one. Say I have selected a Customer record and I want to update this with information, and when this happens I want it to add another record to the "Updates" table to keep track of when updates happened and who did them. This is only an example of course. Things needed to be done can be more complex. Basically I want to add a method to a table object to perform modifications to a specific row in that table and then do inserts and updates on other objects. I know that you can use partial classes and I do that extensively already. Example: ``` db.Customers.Where(c => c.CustomerID == 5).AddOrder(orderDetails); ``` I feel that I can't really put my problem into words to make it understandable :)
Entity classes in Linq to SQL are partial. You could extend them with the rules you need. Or you could build your own business entities from the Linq to SQL entities. Your business entities would then contain the rules on when to do what.
192,260
<p>I am currently working on a website to track projects. In it, it is possible to create Service Level Agreements (SLAs). These are configurable with days of the week that a project can be worked on and also the timespan on each of those days. Eg. on Monday it might be between 08:00 and 16:00 and then on friday from 10:00 to 14:00. They are also configured with a deadline time depending on priority. Eg. a project created with the "Low" priority has a deadline time of two weeks, and a project with "High" priority has a deadline of four hours.</p> <p>The problem I'm having is calculating the deadline AROUND the hours described earlier. Say I create a project on Monday at 14:00 with a "High" priority. That means I have four hours for this project. But because of the working hours, I have two hours on monday (untill 16:00) and then another two hours on Friday. That means the Deadline must be set for Friday at 12:00.</p> <p>I've spent quite some time googling this, and I can find quite a few examples of finding out how many working hours there are between a given start end ending date. I just can't figure out how to convert it into FINDING the ending datetime, given a starting time and an amount of time untill the deadline.</p> <p>The day/timespans are stored in an sql database in the format:</p> <p>Day(Eg. 1 for Monday) StartHour EndHour</p> <p>The StartHour/EndHour are saved as DateTimes, but of course only the time part is important.</p> <p>The way I figure it is, I have to somehow iterate through these times and do some datetime calculations. I just can't quite figure out what those calculations should be, what the best way is.</p> <p>I found <a href="https://stackoverflow.com/questions/5260/what-is-the-best-way-to-wrap-time-around-the-work-day">this Question</a> here on the site as I was writing this. It is sort of what I want and I'm playing with it right now, but I'm still lost on how exactly to make it work around my dynamic work days/hours.</p>
[ { "answer_id": 192307, "author": "Ian Jacobs", "author_id": 22818, "author_profile": "https://Stackoverflow.com/users/22818", "pm_score": 1, "selected": false, "text": "<p>There's a recursive solution that could work, try thinking along these lines:</p>\n\n<pre><code>public DateTime getDeadline(SubmitTime, ProjectTimeAllowed)\n{\n if (SubmitTime+ProjectTimeAllowed &gt;= DayEndTime)\n return getDeadline(NextDayStart, ProjectTimeAllowed-DayEndTime-SubmitTime)\n else\n return SubmitTime + ProjectTimeAllowed\n}\n</code></pre>\n\n<p>Obviously this is quite rough pseudocode. Hopefully it just gives you another way to think about the problem.</p>\n" }, { "answer_id": 192764, "author": "Dan Goldstein", "author_id": 23427, "author_profile": "https://Stackoverflow.com/users/23427", "pm_score": 1, "selected": false, "text": "<p>Here's how I would do it. The algorithm is to see whether the issue can be closed today and if not, use all of today's time to reduce the issue's remaining time and go to tomorrow.</p>\n\n<ol>\n<li>Find the time you have to close the issue as a TimeSpan (I'm calling this the issue's remaining time)</li>\n<li>For each working day, create a DateTime that has only the time of the start and end.</li>\n<li>Set the start time to now.</li>\n<li>Loop: \n\n<ol>\n<li>Find today's remaining time by subtracting today's end time minus the start time (the result should be a TimeSpan)</li>\n<li>If today's remaining time is greater than the issue's remaining time, take today's date and today's starttime + issue remaining time</li>\n<li>If the issue's remaining time is greater, set the issue's remaining time to be the issue's remaining time minus today's remaining time, move to tomorrow, and go to the top of the loop.</li>\n</ol></li>\n</ol>\n" }, { "answer_id": 192791, "author": "Loscas", "author_id": 22706, "author_profile": "https://Stackoverflow.com/users/22706", "pm_score": 1, "selected": false, "text": "<p>Using Stu's <a href=\"https://stackoverflow.com/questions/5260/what-is-the-best-way-to-wrap-time-around-the-work-day#5334\">answer</a> as a starting point, modify the IsInBusinessHours function to look up you business hours for the date parameter. A procedure like the following could be used:</p>\n\n<pre><code>CREATE PROCEDURE [dbo].[IsInBusinessHours]\n @MyDate DateTime \nAS\nBEGIN\n SELECT CASE Count(*) WHEN 0 THEN 0 ELSE 1 END AS IsBusinessHour\nFROM WorkHours\nWHERE (DATEPART(hour, StartHours) &lt;= DATEPART(hour, @MyDate)) AND (DATEPART(hour, EndHours) &gt; DATEPART(hour, @MyDate)) AND (Day = DATEPART(WEEKDAY, \n @MyDate))\nEND\n</code></pre>\n" }, { "answer_id": 192800, "author": "Esteban Brenes", "author_id": 14177, "author_profile": "https://Stackoverflow.com/users/14177", "pm_score": 2, "selected": false, "text": "<p>Here's some C# code which might help, it could be much cleaner, but it's a quick first draft.</p>\n\n<pre><code> class Program\n {\n static void Main(string[] args)\n {\n // Test\n DateTime deadline = DeadlineManager.CalculateDeadline(DateTime.Now, new TimeSpan(4, 0, 0));\n Console.WriteLine(deadline);\n Console.ReadLine();\n }\n }\n\n static class DeadlineManager\n {\n public static DateTime CalculateDeadline(DateTime start, TimeSpan workhours)\n {\n DateTime current = new DateTime(start.Year, start.Month, start.Day, start.Hour, start.Minute, 0);\n while(workhours.TotalMinutes &gt; 0)\n {\n DayOfWeek dayOfWeek = current.DayOfWeek;\n Workday workday = Workday.GetWorkday(dayOfWeek);\n if(workday == null)\n {\n DayOfWeek original = dayOfWeek;\n while (workday == null)\n {\n current = current.AddDays(1);\n dayOfWeek = current.DayOfWeek;\n workday = Workday.GetWorkday(dayOfWeek);\n if (dayOfWeek == original)\n {\n throw new InvalidOperationException(\"no work days\");\n }\n }\n current = current.AddHours(workday.startTime.Hour - current.Hour);\n current = current.AddMinutes(workday.startTime.Minute - current.Minute);\n }\n\n TimeSpan worked = Workday.WorkHours(workday, current);\n if (workhours &gt; worked)\n {\n workhours = workhours - worked;\n // Add one day and reset hour/minutes\n current = current.Add(new TimeSpan(1, current.Hour * -1, current.Minute * -1, 0));\n }\n else\n {\n current.Add(workhours);\n return current;\n }\n }\n return DateTime.MinValue;\n }\n }\n\n class Workday\n {\n private static readonly Dictionary&lt;DayOfWeek, Workday&gt; Workdays = new Dictionary&lt;DayOfWeek, Workday&gt;(7);\n static Workday()\n {\n Workdays.Add(DayOfWeek.Monday, new Workday(DayOfWeek.Monday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 16, 0, 0)));\n Workdays.Add(DayOfWeek.Tuesday, new Workday(DayOfWeek.Tuesday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 16, 0, 0)));\n Workdays.Add(DayOfWeek.Wednesday, new Workday(DayOfWeek.Wednesday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 16, 0, 0)));\n Workdays.Add(DayOfWeek.Thursday, new Workday(DayOfWeek.Thursday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 16, 0, 0)));\n Workdays.Add(DayOfWeek.Friday, new Workday(DayOfWeek.Friday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 14, 0, 0)));\n }\n\n public static Workday GetWorkday(DayOfWeek dayofWeek)\n {\n if (Workdays.ContainsKey(dayofWeek))\n {\n return Workdays[dayofWeek];\n }\n else return null;\n }\n\n public static TimeSpan WorkHours(Workday workday, DateTime time)\n {\n DateTime sTime = new DateTime(time.Year, time.Month, time.Day,\n workday.startTime.Hour, workday.startTime.Millisecond, workday.startTime.Second);\n DateTime eTime = new DateTime(time.Year, time.Month, time.Day,\n workday.endTime.Hour, workday.endTime.Millisecond, workday.endTime.Second);\n if (sTime &lt; time)\n {\n sTime = time;\n }\n TimeSpan span = eTime - sTime;\n return span;\n }\n\n public static DayOfWeek GetNextWeekday(DayOfWeek dayOfWeek)\n {\n int i = (dayOfWeek == DayOfWeek.Saturday) ? 0 : ((int)dayOfWeek) + 1;\n return (DayOfWeek)i;\n }\n\n\n private Workday(DayOfWeek dayOfWeek, DateTime start, DateTime end)\n {\n this.dayOfWeek = dayOfWeek;\n this.startTime = start;\n this.endTime = end;\n }\n\n public DayOfWeek dayOfWeek;\n public DateTime startTime;\n public DateTime endTime;\n }\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192260", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26841/" ]
I am currently working on a website to track projects. In it, it is possible to create Service Level Agreements (SLAs). These are configurable with days of the week that a project can be worked on and also the timespan on each of those days. Eg. on Monday it might be between 08:00 and 16:00 and then on friday from 10:00 to 14:00. They are also configured with a deadline time depending on priority. Eg. a project created with the "Low" priority has a deadline time of two weeks, and a project with "High" priority has a deadline of four hours. The problem I'm having is calculating the deadline AROUND the hours described earlier. Say I create a project on Monday at 14:00 with a "High" priority. That means I have four hours for this project. But because of the working hours, I have two hours on monday (untill 16:00) and then another two hours on Friday. That means the Deadline must be set for Friday at 12:00. I've spent quite some time googling this, and I can find quite a few examples of finding out how many working hours there are between a given start end ending date. I just can't figure out how to convert it into FINDING the ending datetime, given a starting time and an amount of time untill the deadline. The day/timespans are stored in an sql database in the format: Day(Eg. 1 for Monday) StartHour EndHour The StartHour/EndHour are saved as DateTimes, but of course only the time part is important. The way I figure it is, I have to somehow iterate through these times and do some datetime calculations. I just can't quite figure out what those calculations should be, what the best way is. I found [this Question](https://stackoverflow.com/questions/5260/what-is-the-best-way-to-wrap-time-around-the-work-day) here on the site as I was writing this. It is sort of what I want and I'm playing with it right now, but I'm still lost on how exactly to make it work around my dynamic work days/hours.
Here's some C# code which might help, it could be much cleaner, but it's a quick first draft. ``` class Program { static void Main(string[] args) { // Test DateTime deadline = DeadlineManager.CalculateDeadline(DateTime.Now, new TimeSpan(4, 0, 0)); Console.WriteLine(deadline); Console.ReadLine(); } } static class DeadlineManager { public static DateTime CalculateDeadline(DateTime start, TimeSpan workhours) { DateTime current = new DateTime(start.Year, start.Month, start.Day, start.Hour, start.Minute, 0); while(workhours.TotalMinutes > 0) { DayOfWeek dayOfWeek = current.DayOfWeek; Workday workday = Workday.GetWorkday(dayOfWeek); if(workday == null) { DayOfWeek original = dayOfWeek; while (workday == null) { current = current.AddDays(1); dayOfWeek = current.DayOfWeek; workday = Workday.GetWorkday(dayOfWeek); if (dayOfWeek == original) { throw new InvalidOperationException("no work days"); } } current = current.AddHours(workday.startTime.Hour - current.Hour); current = current.AddMinutes(workday.startTime.Minute - current.Minute); } TimeSpan worked = Workday.WorkHours(workday, current); if (workhours > worked) { workhours = workhours - worked; // Add one day and reset hour/minutes current = current.Add(new TimeSpan(1, current.Hour * -1, current.Minute * -1, 0)); } else { current.Add(workhours); return current; } } return DateTime.MinValue; } } class Workday { private static readonly Dictionary<DayOfWeek, Workday> Workdays = new Dictionary<DayOfWeek, Workday>(7); static Workday() { Workdays.Add(DayOfWeek.Monday, new Workday(DayOfWeek.Monday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 16, 0, 0))); Workdays.Add(DayOfWeek.Tuesday, new Workday(DayOfWeek.Tuesday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 16, 0, 0))); Workdays.Add(DayOfWeek.Wednesday, new Workday(DayOfWeek.Wednesday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 16, 0, 0))); Workdays.Add(DayOfWeek.Thursday, new Workday(DayOfWeek.Thursday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 16, 0, 0))); Workdays.Add(DayOfWeek.Friday, new Workday(DayOfWeek.Friday, new DateTime(1, 1, 1, 10, 0, 0), new DateTime(1, 1, 1, 14, 0, 0))); } public static Workday GetWorkday(DayOfWeek dayofWeek) { if (Workdays.ContainsKey(dayofWeek)) { return Workdays[dayofWeek]; } else return null; } public static TimeSpan WorkHours(Workday workday, DateTime time) { DateTime sTime = new DateTime(time.Year, time.Month, time.Day, workday.startTime.Hour, workday.startTime.Millisecond, workday.startTime.Second); DateTime eTime = new DateTime(time.Year, time.Month, time.Day, workday.endTime.Hour, workday.endTime.Millisecond, workday.endTime.Second); if (sTime < time) { sTime = time; } TimeSpan span = eTime - sTime; return span; } public static DayOfWeek GetNextWeekday(DayOfWeek dayOfWeek) { int i = (dayOfWeek == DayOfWeek.Saturday) ? 0 : ((int)dayOfWeek) + 1; return (DayOfWeek)i; } private Workday(DayOfWeek dayOfWeek, DateTime start, DateTime end) { this.dayOfWeek = dayOfWeek; this.startTime = start; this.endTime = end; } public DayOfWeek dayOfWeek; public DateTime startTime; public DateTime endTime; } ```
192,261
<p>Using something like this:</p> <pre><code>try: # Something... except Exception as excep: logger = logging.getLogger("component") logger.warning("something raised an exception: " + excep) logger.info("something raised an exception: " + excep) </code></pre> <p>I would rather not have it on the error-level cause in my special case it is not an error.</p>
[ { "answer_id": 193153, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 8, "selected": true, "text": "<p>From the <a href=\"http://docs.python.org/library/logging.html#logging.Logger.debug\" rel=\"noreferrer\">logging documentation</a>:</p>\n\n<blockquote>\n <p>There are three keyword arguments in <code>kwargs</code> which are inspected: <code>exc_info</code>, <code>stack_info</code>, and <code>extra</code>.</p>\n \n <p>If <code>exc_info</code> does not evaluate as false, it causes exception information to be added to the logging message. If an exception tuple (in the format returned by <a href=\"https://docs.python.org/3/library/sys.html#sys.exc_info\" rel=\"noreferrer\"><code>sys.exc_info()</code></a>) or an exception instance is provided, it is used; otherwise, <a href=\"https://docs.python.org/3/library/sys.html#sys.exc_info\" rel=\"noreferrer\"><code>sys.exc_info()</code></a> is called to get the exception information.</p>\n</blockquote>\n\n<p>So do:</p>\n\n<pre><code>logger.warning(\"something raised an exception:\", exc_info=True)\n</code></pre>\n" }, { "answer_id": 4909282, "author": "Scubahubby", "author_id": 604684, "author_profile": "https://Stackoverflow.com/users/604684", "pm_score": 2, "selected": false, "text": "<p>Here is one that works (python 2.6.5).</p>\n\n<pre><code>logger.critical(\"caught exception, traceback =\", exc_info=True)\n</code></pre>\n" }, { "answer_id": 49975391, "author": "Benyamin Jafari - aGn", "author_id": 3702377, "author_profile": "https://Stackoverflow.com/users/3702377", "pm_score": 1, "selected": false, "text": "<p>You can try this:</p>\n\n<pre><code>from logging import getLogger\n\nlogger = getLogger('warning')\n\ntry:\n # Somethings that is wrong.\n\nexcept Exception as exp:\n logger.warning(\"something raised an exception: \" , exc_info=True)\n logger.warning(\"something raised an exception: {}\".format(exp)) # another way\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26905/" ]
Using something like this: ``` try: # Something... except Exception as excep: logger = logging.getLogger("component") logger.warning("something raised an exception: " + excep) logger.info("something raised an exception: " + excep) ``` I would rather not have it on the error-level cause in my special case it is not an error.
From the [logging documentation](http://docs.python.org/library/logging.html#logging.Logger.debug): > > There are three keyword arguments in `kwargs` which are inspected: `exc_info`, `stack_info`, and `extra`. > > > If `exc_info` does not evaluate as false, it causes exception information to be added to the logging message. If an exception tuple (in the format returned by [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info)) or an exception instance is provided, it is used; otherwise, [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info) is called to get the exception information. > > > So do: ``` logger.warning("something raised an exception:", exc_info=True) ```
192,264
<p>I have a page that is hitting a webservice every 5 seconds to update the information on the page. I'm using the DynamicPopulateExtender from the Ajax Control Toolkit to just populate a panel with some text.</p> <p>What I was wanting to do, is if a certain condition is met, to refresh the page completely. </p> <p>Am I going to be able to do this in the current method that I have? here's my current stuff:</p> <hr> <p>ASP.NET</p> <pre><code>&lt;cc1:DynamicPopulateExtender ID="DynamicPopulateExtender1" runat="server" ClearContentsDuringUpdate="true" TargetControlID="panelQueue" BehaviorID="dp1" ServiceMethod="GetQueueTable" UpdatingCssClass="dynamicPopulate_Updating" /&gt; </code></pre> <p>Javascript</p> <pre><code>Sys.Application.add_load(function(){updateQueue();}); function updateQueue() { var queueShown = document.getElementById('&lt;%= hiddenFieldQueueShown.ClientID %&gt;').value; if(queueShown == 1) { var behavior = $find('dp1'); if (behavior) { behavior.populate(); setTimeout('updateQueue()', 5000); } } } </code></pre> <p>SERVER (C#)</p> <pre><code>[System.Web.Services.WebMethod] [System.Web.Script.Services.ScriptMethod] public static string GetQueueTable() { System.Text.StringBuilder builder = new System.Text.StringBuilder(); try { // do stuff } catch (Exception ex) { // do stuff } return builder.ToString(); } </code></pre>
[ { "answer_id": 192316, "author": "Jason Kealey", "author_id": 20893, "author_profile": "https://Stackoverflow.com/users/20893", "pm_score": 3, "selected": true, "text": "<ul>\n<li>You can't do anything from your ASMX.</li>\n<li>You can refresh the page from JavaScript by using a conventional page reload or by doing a postback that would perform server-side changes and then update via your UpdatePanel or, more simply, a Response.Redirect. </li>\n</ul>\n" }, { "answer_id": 192393, "author": "Alfred B. Thordarson", "author_id": 3379, "author_profile": "https://Stackoverflow.com/users/3379", "pm_score": 2, "selected": false, "text": "<p>You can force a Postback from Javascript, see this Default.aspx page for a example:</p>\n\n<hr>\n\n<h2>Default.aspx</h2>\n\n<pre><code>&lt;html xmlns=\"http://www.w3.org/1999/xhtml\" &gt;\n&lt;head runat=\"server\"&gt;\n &lt;title&gt;Untitled Page&lt;/title&gt;\n\n &lt;script type=\"text/javascript\" language=\"javascript\"&gt;\n function forcePostback()\n {\n &lt;%=getPostBackJavascriptCode()%&gt;;\n }\n &lt;/script&gt;\n\n&lt;/head&gt;\n\n&lt;body onload=\"javascript:forcePostback()\"&gt;\n &lt;form id=\"form1\" runat=\"server\"&gt;\n &lt;div&gt;\n &lt;asp:Label ID=\"Label1\" runat=\"server\" Text=\"Postbacking right now...\"&gt;&lt;/asp:Label&gt;\n &lt;/div&gt;\n &lt;/form&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<hr>\n\n<h2>Default.aspx.cs</h2>\n\n<pre><code>namespace ForcingApostback\n{\n public partial class _Default : System.Web.UI.Page\n {\n protected void Page_Load(object sender, EventArgs e)\n {\n if (IsPostBack) Label1.Text = \"Done postbacking!!!\";\n }\n\n protected string getPostBackJavascriptCode()\n {\n return ClientScript.GetPostBackEventReference(this, null);\n\n }\n }\n}\n</code></pre>\n\n<p>On the client-side, under any condition, you could then call the forcePostback() Javascript function to force the Postback.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21828/" ]
I have a page that is hitting a webservice every 5 seconds to update the information on the page. I'm using the DynamicPopulateExtender from the Ajax Control Toolkit to just populate a panel with some text. What I was wanting to do, is if a certain condition is met, to refresh the page completely. Am I going to be able to do this in the current method that I have? here's my current stuff: --- ASP.NET ``` <cc1:DynamicPopulateExtender ID="DynamicPopulateExtender1" runat="server" ClearContentsDuringUpdate="true" TargetControlID="panelQueue" BehaviorID="dp1" ServiceMethod="GetQueueTable" UpdatingCssClass="dynamicPopulate_Updating" /> ``` Javascript ``` Sys.Application.add_load(function(){updateQueue();}); function updateQueue() { var queueShown = document.getElementById('<%= hiddenFieldQueueShown.ClientID %>').value; if(queueShown == 1) { var behavior = $find('dp1'); if (behavior) { behavior.populate(); setTimeout('updateQueue()', 5000); } } } ``` SERVER (C#) ``` [System.Web.Services.WebMethod] [System.Web.Script.Services.ScriptMethod] public static string GetQueueTable() { System.Text.StringBuilder builder = new System.Text.StringBuilder(); try { // do stuff } catch (Exception ex) { // do stuff } return builder.ToString(); } ```
* You can't do anything from your ASMX. * You can refresh the page from JavaScript by using a conventional page reload or by doing a postback that would perform server-side changes and then update via your UpdatePanel or, more simply, a Response.Redirect.
192,292
<p>The way you would normally include a script is with "source"</p> <p>eg:</p> <p>main.sh:</p> <pre><code>#!/bin/bash source incl.sh echo "The main script" </code></pre> <p>incl.sh:</p> <pre><code>echo "The included script" </code></pre> <p>The output of executing "./main.sh" is:</p> <pre><code>The included script The main script </code></pre> <p>... Now, if you attempt to execute that shell script from another location, it can't find the include unless it's in your path.</p> <p>What's a good way to ensure that your script can find the include script, especially if for instance, the script needs to be portable?</p>
[ { "answer_id": 192305, "author": "Chris Boran", "author_id": 25660, "author_profile": "https://Stackoverflow.com/users/25660", "pm_score": 9, "selected": true, "text": "<p>I tend to make my scripts all be relative to one another. \nThat way I can use dirname:</p>\n\n<pre><code>#!/bin/sh\n\nmy_dir=\"$(dirname \"$0\")\"\n\n\"$my_dir/other_script.sh\"\n</code></pre>\n" }, { "answer_id": 192306, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 6, "selected": false, "text": "<p>If it is in the same directory you can use <code>dirname $0</code>:</p>\n\n<pre><code>#!/bin/bash\n\nsource $(dirname $0)/incl.sh\n\necho \"The main script\"\n</code></pre>\n" }, { "answer_id": 192312, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 3, "selected": false, "text": "<p>I'd suggest that you create a setenv script whose sole purpose is to provide locations for various components across your system.</p>\n\n<p>All other scripts would then source this script so that all locations are common across all scripts using the setenv script.</p>\n\n<p>This is very useful when running cronjobs. You get a minimal environment when running cron, but if you make all cron scripts first include the setenv script then you are able to control and synchronise the environment that you want the cronjobs to execute in.</p>\n\n<p>We used such a technique on our build monkey that was used for continuous integration across a project of about 2,000 kSLOC.</p>\n" }, { "answer_id": 192381, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 3, "selected": false, "text": "<p>You need to specify the location of the other scripts, there is no other way around it. I'd recommend a configurable variable at the top of your script:</p>\n\n<pre><code>#!/bin/bash\ninstallpath=/where/your/scripts/are\n\n. $installpath/incl.sh\n\necho \"The main script\"\n</code></pre>\n\n<p>Alternatively, you can insist that the user maintain an environment variable indicating where your program home is at, like PROG_HOME or somesuch. This can be supplied for the user automatically by creating a script with that information in /etc/profile.d/, which will be sourced every time a user logs in.</p>\n" }, { "answer_id": 192524, "author": "tardate", "author_id": 6329, "author_profile": "https://Stackoverflow.com/users/6329", "pm_score": 6, "selected": false, "text": "<p>An alternative to:</p>\n\n<pre><code>scriptPath=$(dirname $0)\n</code></pre>\n\n<p>is:</p>\n\n<pre><code>scriptPath=${0%/*}\n</code></pre>\n\n<p>.. the advantage being not having the dependence on dirname, which is not a built-in command (and not always available in emulators)</p>\n" }, { "answer_id": 193988, "author": "Rob Wells", "author_id": 2974, "author_profile": "https://Stackoverflow.com/users/2974", "pm_score": 2, "selected": false, "text": "<p>Steve's reply is definitely the correct technique but it should be refactored so that your installpath variable is in a separate environment script where all such declarations are made.</p>\n\n<p>Then all scripts source that script and should installpath change, you only need to change it in one location. Makes things more, er, futureproof. God I hate that word! (-:</p>\n\n<p>BTW You should really refer to the variable using ${installpath} when using it in the way shown in your example:</p>\n\n<pre><code>. ${installpath}/incl.sh\n</code></pre>\n\n<p>If the braces are left out, some shells will try and expand the variable \"installpath/incl.sh\"!</p>\n" }, { "answer_id": 992855, "author": "Max Arnold", "author_id": 65523, "author_profile": "https://Stackoverflow.com/users/65523", "pm_score": 5, "selected": false, "text": "<pre><code>SRC=$(cd $(dirname \"$0\"); pwd)\nsource \"${SRC}/incl.sh\"\n</code></pre>\n" }, { "answer_id": 3692080, "author": "konsolebox", "author_id": 445221, "author_profile": "https://Stackoverflow.com/users/445221", "pm_score": 2, "selected": false, "text": "<p><strong><a href=\"http://loader.sourceforge.net/\" rel=\"noreferrer\">Shell Script Loader</a></strong> is my solution for this.</p>\n\n<p>It provides a function named include() that can be called many times in many scripts to refer a single script but will only load the script once. The function can accept complete paths or partial paths (script is searched in a search path). A similar function named load() is also provided that will load the scripts unconditionally.</p>\n\n<p>It works for <strong>bash</strong>, <strong>ksh</strong>, <strong>pd ksh</strong> and <strong>zsh with</strong> optimized scripts for each one of them; and other shells that are generically compatible with the original sh like <strong>ash</strong>, <strong>dash</strong>, <strong>heirloom sh</strong>, etc., through a universal script that automatically optimizes its functions depending on the features the shell can provide.</p>\n\n<p><strong>[Fowarded example]</strong></p>\n\n<p><strong>start.sh</strong></p>\n\n<p>This is an optional starter script. Placing the startup methods here is just a convenience and can be placed in the main script instead. This script is also not needed if the scripts are to be compiled.</p>\n\n<pre><code>#!/bin/sh\n\n# load loader.sh\n. loader.sh\n\n# include directories to search path\nloader_addpath /usr/lib/sh deps source\n\n# load main script\nload main.sh\n</code></pre>\n\n<p><strong>main.sh</strong></p>\n\n<pre><code>include a.sh\ninclude b.sh\n\necho '---- main.sh ----'\n\n# remove loader from shellspace since\n# we no longer need it\nloader_finish\n\n# main procedures go from here\n\n# ...\n</code></pre>\n\n<p><strong>a.sh</strong></p>\n\n<pre><code>include main.sh\ninclude a.sh\ninclude b.sh\n\necho '---- a.sh ----'\n</code></pre>\n\n<p><strong>b.sh</strong></p>\n\n<pre><code>include main.sh\ninclude a.sh\ninclude b.sh\n\necho '---- b.sh ----'\n</code></pre>\n\n<p><strong>output:</strong></p>\n\n<pre><code>---- b.sh ----\n---- a.sh ----\n---- main.sh ----\n</code></pre>\n\n<p>What's best is scripts based on it may also be compiled to form a single script with the available compiler.</p>\n\n<p>Here's a project that uses it: <a href=\"http://sourceforge.net/p/playshell/code/ci/master/tree/\" rel=\"noreferrer\">http://sourceforge.net/p/playshell/code/ci/master/tree/</a>. It can run portably with or without compiling the scripts. Compiling to produce a single script can also happen, and is helpful during installation.</p>\n\n<p>I also created a simpler prototype for any conservative party that may want to have a brief idea of how an implementation script works: <a href=\"https://sourceforge.net/p/loader/code/ci/base/tree/loader-include-prototype.bash\" rel=\"noreferrer\">https://sourceforge.net/p/loader/code/ci/base/tree/loader-include-prototype.bash</a>. It's small and anyone can just include the code in their main script if they want to if their code is intended to run with Bash 4.0 or newer, and it also doesn't use <code>eval</code>.</p>\n" }, { "answer_id": 4047714, "author": "phreed", "author_id": 345427, "author_profile": "https://Stackoverflow.com/users/345427", "pm_score": 2, "selected": false, "text": "<p>I put all my startup scripts in a .bashrc.d directory.\nThis is a common technique in such places as /etc/profile.d, etc.</p>\n\n<pre><code>while read file; do source \"${file}\"; done &lt;&lt;HERE\n$(find ${HOME}/.bashrc.d -type f)\nHERE\n</code></pre>\n\n<p>The problem with the solution using globbing...</p>\n\n<pre><code>for file in ${HOME}/.bashrc.d/*.sh; do source ${file};done\n</code></pre>\n\n<p>...is you might have a file list which is \"too long\".\nAn approach like... </p>\n\n<pre><code>find ${HOME}/.bashrc.d -type f | while read file; do source ${file}; done\n</code></pre>\n\n<p>...runs but doesn't change the environment as desired.</p>\n" }, { "answer_id": 4226925, "author": "Django", "author_id": 513726, "author_profile": "https://Stackoverflow.com/users/513726", "pm_score": -1, "selected": false, "text": "<p>You can also use:</p>\n\n<pre><code>PWD=$(pwd)\nsource \"$PWD/inc.sh\"\n</code></pre>\n" }, { "answer_id": 7533252, "author": "Mat131", "author_id": 850780, "author_profile": "https://Stackoverflow.com/users/850780", "pm_score": 5, "selected": false, "text": "<p>I think the best way to do this is to use the Chris Boran's way, BUT you should compute MY_DIR this way:</p>\n<pre><code>#!/bin/sh\nMY_DIR=$(dirname $(readlink -f $0))\n$MY_DIR/other_script.sh\n</code></pre>\n<p>To quote the man pages for readlink:</p>\n<blockquote>\n<pre><code>readlink - display value of a symbolic link\n\n...\n\n -f, --canonicalize\n canonicalize by following every symlink in every component of the given \n name recursively; all but the last component must exist\n</code></pre>\n</blockquote>\n<p>I've never encountered a use case where <code>MY_DIR</code> is not correctly computed. If you access your script through a symlink in your <code>$PATH</code> it works.</p>\n" }, { "answer_id": 12694189, "author": "sacii", "author_id": 1714902, "author_profile": "https://Stackoverflow.com/users/1714902", "pm_score": 8, "selected": false, "text": "<p>I know I am late to the party, but this should work no matter how you start the script and uses builtins exclusively:</p>\n\n<pre><code>DIR=\"${BASH_SOURCE%/*}\"\nif [[ ! -d \"$DIR\" ]]; then DIR=\"$PWD\"; fi\n. \"$DIR/incl.sh\"\n. \"$DIR/main.sh\"\n</code></pre>\n\n<p><code>.</code> (dot) command is an alias to <code>source</code>, <code>$PWD</code> is the Path for the Working Directory, <code>BASH_SOURCE</code> is an array variable whose members are the source filenames, <code>${string%substring}</code> strips shortest match of $substring from back of $string</p>\n" }, { "answer_id": 13222994, "author": "francoisrv", "author_id": 754522, "author_profile": "https://Stackoverflow.com/users/754522", "pm_score": 1, "selected": false, "text": "<p>Using source or $0 will not give you the real path of your script. You could use the process id of the script to retrieve its real path</p>\n\n<pre><code>ls -l /proc/$$/fd | \ngrep \"255 -&gt;\" |\nsed -e 's/^.\\+-&gt; //'\n</code></pre>\n\n<p>I am using this script and it has always served me well :)</p>\n" }, { "answer_id": 21163311, "author": "fastrizwaan", "author_id": 3189318, "author_profile": "https://Stackoverflow.com/users/3189318", "pm_score": 0, "selected": false, "text": "<p>we just need to find out the folder where our incl.sh and main.sh is stored; just change your main.sh with this:</p>\n\n<p>main.sh</p>\n\n<pre><code>#!/bin/bash\n\nSCRIPT_NAME=$(basename $0)\nSCRIPT_DIR=\"$(echo $0| sed \"s/$SCRIPT_NAME//g\")\"\nsource $SCRIPT_DIR/incl.sh\n\necho \"The main script\"\n</code></pre>\n" }, { "answer_id": 26727011, "author": "modulitos", "author_id": 1884158, "author_profile": "https://Stackoverflow.com/users/1884158", "pm_score": 1, "selected": false, "text": "<p>Of course, to each their own, but I think the block below is pretty solid. I believe this involves the \"best\" way to find a directory, and the \"best\" way to call another bash script:</p>\n\n<pre><code>scriptdir=`dirname \"$BASH_SOURCE\"`\nsource $scriptdir/incl.sh\n\necho \"The main script\"\n</code></pre>\n\n<p>So this may be the \"best\" way to include other scripts. This is based off another \"best\" answer that <a href=\"https://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in\">tells a bash script where it is stored</a> </p>\n" }, { "answer_id": 30654404, "author": "PSkocik", "author_id": 1084774, "author_profile": "https://Stackoverflow.com/users/1084774", "pm_score": 2, "selected": false, "text": "<p>This should work reliably:</p>\n\n<pre><code>source_relative() {\n local dir=\"${BASH_SOURCE%/*}\"\n [[ -z \"$dir\" ]] &amp;&amp; dir=\"$PWD\"\n source \"$dir/$1\"\n}\n\nsource_relative incl.sh\n</code></pre>\n" }, { "answer_id": 31960707, "author": "Alessandro Pezzato", "author_id": 786186, "author_profile": "https://Stackoverflow.com/users/786186", "pm_score": 4, "selected": false, "text": "<p>This works even if the script is sourced:</p>\n\n<pre><code>source \"$( dirname \"${BASH_SOURCE[0]}\" )/incl.sh\"\n</code></pre>\n" }, { "answer_id": 34208365, "author": "Brian Cannard", "author_id": 84661, "author_profile": "https://Stackoverflow.com/users/84661", "pm_score": 5, "selected": false, "text": "<p><strong>A combination of the answers to this question provides the most robust solution.</strong></p>\n\n<p>It worked for us in production-grade scripts with great support of dependencies and directory structure:</p>\n\n<pre>#!/bin/bash\n\n# Full path of the current script\nTHIS=`readlink -f \"${BASH_SOURCE[0]}\" 2>/dev/null||echo $0`\n\n# The directory where current script resides\nDIR=`dirname \"${THIS}\"`\n\n# 'Dot' means 'source', i.e. 'include':\n. \"$DIR/compile.sh\"</pre>\n\n<p><strong>The method supports all of these:</strong></p>\n\n<ul>\n<li><strong>Spaces</strong> in path</li>\n<li><strong>Links</strong> (via <code>readlink</code>)</li>\n<li><code>${BASH_SOURCE[0]}</code> is more robust than <code>$0</code></li>\n</ul>\n" }, { "answer_id": 49706459, "author": "Alexar", "author_id": 257479, "author_profile": "https://Stackoverflow.com/users/257479", "pm_score": 4, "selected": false, "text": "<h1>1. Neatest</h1>\n<p>I explored almost every suggestion and here is the neatest one that worked for me:</p>\n<p><code>script_root=$(dirname $(readlink -f $0))</code></p>\n<p>It works even when the script is symlinked to a <code>$PATH</code> directory.</p>\n<p>See it in action here: <a href=\"https://github.com/pendashteh/hcagent/blob/master/bin/hcagent\" rel=\"noreferrer\">https://github.com/pendashteh/hcagent/blob/master/bin/hcagent</a></p>\n<h1>2. The coolest</h1>\n<pre><code># Copyright https://stackoverflow.com/a/13222994/257479\nscript_root=$(ls -l /proc/$$/fd | grep &quot;255 -&gt;&quot; | sed -e 's/^.\\+-&gt; //')\n</code></pre>\n<p>This is actually from another answer on this very page, but I'm adding it to my answer too!</p>\n<h1>3. The most reliable</h1>\n<p>Alternatively, in the rare case that those didn't work, here is the bullet proof approach:</p>\n<pre><code># Copyright http://stackoverflow.com/a/7400673/257479\nmyreadlink() { [ ! -h &quot;$1&quot; ] &amp;&amp; echo &quot;$1&quot; || (local link=&quot;$(expr &quot;$(command ls -ld -- &quot;$1&quot;)&quot; : '.*-&gt; \\(.*\\)$')&quot;; cd $(dirname $1); myreadlink &quot;$link&quot; | sed &quot;s|^\\([^/].*\\)\\$|$(dirname $1)/\\1|&quot;); }\nwhereis() { echo $1 | sed &quot;s|^\\([^/].*/.*\\)|$(pwd)/\\1|;s|^\\([^/]*\\)$|$(which -- $1)|;s|^$|$1|&quot;; } \nwhereis_realpath() { local SCRIPT_PATH=$(whereis $1); myreadlink ${SCRIPT_PATH} | sed &quot;s|^\\([^/].*\\)\\$|$(dirname ${SCRIPT_PATH})/\\1|&quot;; } \n\nscript_root=$(dirname $(whereis_realpath &quot;$0&quot;))\n</code></pre>\n<p>You can see it in action in <code>taskrunner</code> source: <a href=\"https://github.com/pendashteh/taskrunner/blob/master/bin/taskrunner\" rel=\"noreferrer\">https://github.com/pendashteh/taskrunner/blob/master/bin/taskrunner</a></p>\n<p>Hope this help someone out there :)</p>\n<p>Also, please leave it as a comment if one did not work for you and mention your operating system and emulator. Thanks!</p>\n" }, { "answer_id": 51783337, "author": "Xaqron", "author_id": 313421, "author_profile": "https://Stackoverflow.com/users/313421", "pm_score": 1, "selected": false, "text": "<p>Personally put all libraries in a <code>lib</code> folder and use an <code>import</code> function to load them.</p>\n\n<p><em>folder structure</em></p>\n\n<p><a href=\"https://i.stack.imgur.com/2NPbb.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/2NPbb.png\" alt=\"enter image description here\"></a></p>\n\n<p><em><code>script.sh</code> contents</em></p>\n\n<pre><code># Imports '.sh' files from 'lib' directory\nfunction import()\n{\n local file=\"./lib/$1.sh\"\n local error=\"\\e[31mError: \\e[0mCannot find \\e[1m$1\\e[0m library at: \\e[2m$file\\e[0m\"\n if [ -f \"$file\" ]; then\n source \"$file\"\n if [ -z $IMPORTED ]; then\n echo -e $error\n exit 1\n fi\n else\n echo -e $error\n exit 1\n fi\n}\n</code></pre>\n\n<p>Note that this import function should be at the beginning of your script and then you can easily import your libraries like this:</p>\n\n<pre><code>import \"utils\"\nimport \"requirements\"\n</code></pre>\n\n<p>Add a single line at the top of each library (i.e. utils.sh):</p>\n\n<pre><code>IMPORTED=\"$BASH_SOURCE\"\n</code></pre>\n\n<p>Now you have access to functions inside <code>utils.sh</code> and <code>requirements.sh</code> from <code>script.sh</code></p>\n\n<p>TODO: Write a linker to build a single <code>sh</code> file</p>\n" }, { "answer_id": 56917434, "author": "Alexander Yancharuk", "author_id": 2648942, "author_profile": "https://Stackoverflow.com/users/2648942", "pm_score": 0, "selected": false, "text": "<p>According <a href=\"http://man7.org/linux/man-pages/man7/hier.7.html\" rel=\"nofollow noreferrer\"><code>man hier</code></a> suitable place for script includes is <code>/usr/local/lib/</code></p>\n\n<blockquote>\n <p>/usr/local/lib</p>\n \n <p>Files associated with locally installed programs.</p>\n</blockquote>\n\n<p>Personally I prefer <code>/usr/local/lib/bash/includes</code> for includes.\nThere is <a href=\"https://github.com/nafigator/bash-helpers#features\" rel=\"nofollow noreferrer\">bash-helper</a> lib for including libs in that way:</p>\n\n<pre><code>#!/bin/bash\n\n. /usr/local/lib/bash/includes/bash-helpers.sh\n\ninclude api-client || exit 1 # include shared functions\ninclude mysql-status/query-builder || exit 1 # include script functions\n\n# include script functions with status message\ninclude mysql-status/process-checker; status 'process-checker' $? || exit 1\ninclude mysql-status/nonexists; status 'nonexists' $? || exit 1\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/7Q3lF.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/7Q3lF.jpg\" alt=\"bash-helpers includes status output\"></a></p>\n" }, { "answer_id": 66371711, "author": "Joaommp", "author_id": 6421961, "author_profile": "https://Stackoverflow.com/users/6421961", "pm_score": 0, "selected": false, "text": "<p>Most of the answers I saw here seem to overcomplicate things. This method has always worked reliably for me:</p>\n<pre><code>FULLPATH=$(readlink -f $0)\nINCPATH=${FULLPATH%/*}\n</code></pre>\n<p>INCPATH will hold the complete path of the script excluding the script filename, regardless of how the script is called (by $PATH, relative or absolute).</p>\n<p>After that, one only needs to do this to include files in the same directory:</p>\n<pre><code>. $INCPATH/file_to_include.sh\n</code></pre>\n<p>Reference: <a href=\"https://tecporto.pt/wiki/index.php/Location_independent_includes\" rel=\"nofollow noreferrer\">TecPorto / Location independent includes</a></p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16258/" ]
The way you would normally include a script is with "source" eg: main.sh: ``` #!/bin/bash source incl.sh echo "The main script" ``` incl.sh: ``` echo "The included script" ``` The output of executing "./main.sh" is: ``` The included script The main script ``` ... Now, if you attempt to execute that shell script from another location, it can't find the include unless it's in your path. What's a good way to ensure that your script can find the include script, especially if for instance, the script needs to be portable?
I tend to make my scripts all be relative to one another. That way I can use dirname: ``` #!/bin/sh my_dir="$(dirname "$0")" "$my_dir/other_script.sh" ```
192,319
<p>How can I determine the name of the Bash script file inside the script itself?</p> <p>Like if my script is in file <code>runme.sh</code>, then how would I make it to display "You are running runme.sh" message without hardcoding that?</p>
[ { "answer_id": 192337, "author": "Tanktalus", "author_id": 23512, "author_profile": "https://Stackoverflow.com/users/23512", "pm_score": 11, "selected": true, "text": "<pre><code>me=`basename \"$0\"`\n</code></pre>\n\n<p>For reading through a symlink<sup>1</sup>, which is usually not what you want (you usually don't want to confuse the user this way), try:</p>\n\n<pre><code>me=\"$(basename \"$(test -L \"$0\" &amp;&amp; readlink \"$0\" || echo \"$0\")\")\"\n</code></pre>\n\n<p>IMO, that'll produce confusing output. \"I ran foo.sh, but it's saying I'm running bar.sh!? Must be a bug!\" Besides, one of the purposes of having differently-named symlinks is to provide different functionality based on the name it's called as (think gzip and gunzip on some platforms).</p>\n\n<hr>\n\n<p><sup>1</sup> That is, to resolve symlinks such that when the user executes <code>foo.sh</code> which is actually a symlink to <code>bar.sh</code>, you wish to use the resolved name <code>bar.sh</code> rather than <code>foo.sh</code>.</p>\n" }, { "answer_id": 192339, "author": "mmacaulay", "author_id": 22152, "author_profile": "https://Stackoverflow.com/users/22152", "pm_score": -1, "selected": false, "text": "<p>echo \"You are running $0\"</p>\n" }, { "answer_id": 192344, "author": "VolkA", "author_id": 25472, "author_profile": "https://Stackoverflow.com/users/25472", "pm_score": 3, "selected": false, "text": "<p>You can use $0 to determine your script name (with full path) - to get the script name only you can trim that variable with</p>\n\n<pre><code>basename $0\n</code></pre>\n" }, { "answer_id": 192358, "author": "Josh Lee", "author_id": 19750, "author_profile": "https://Stackoverflow.com/users/19750", "pm_score": 6, "selected": false, "text": "<p>If the script name has spaces in it, a more robust way is to use <code>\"$0\"</code> or <code>\"$(basename \"$0\")\"</code> - or on MacOS: <code>\"$(basename \\\"$0\\\")\"</code>. This prevents the name from getting mangled or interpreted in any way. In general, it is good practice to always double-quote variable names in the shell.</p>\n" }, { "answer_id": 192533, "author": "Travis B. Hartwell", "author_id": 10873, "author_profile": "https://Stackoverflow.com/users/10873", "pm_score": 5, "selected": false, "text": "<p>To answer <a href=\"https://stackoverflow.com/questions/192319/in-the-bash-script-how-do-i-know-the-script-file-name#192440\">Chris Conway</a>, on Linux (at least) you would do this:</p>\n\n<pre><code>echo $(basename $(readlink -nf $0))\n</code></pre>\n\n<p>readlink prints out the value of a symbolic link. If it isn't a symbolic link, it prints the file name. -n tells it to not print a newline. -f tells it to follow the link completely (if a symbolic link was a link to another link, it would resolve that one as well).</p>\n" }, { "answer_id": 192699, "author": "Mr. Muskrat", "author_id": 2657951, "author_profile": "https://Stackoverflow.com/users/2657951", "pm_score": 5, "selected": false, "text": "<p>If you want it without the path then you would use <code>${0##*/}</code></p>\n" }, { "answer_id": 639204, "author": "Jim Dodd", "author_id": 45493, "author_profile": "https://Stackoverflow.com/users/45493", "pm_score": 4, "selected": false, "text": "<p>These answers are correct for the cases they state but there is a still a problem if you run the script from another script using the 'source' keyword (so that it runs in the same shell). In this case, you get the $0 of the calling script. And in this case, I don't think it is possible to get the name of the script itself.</p>\n\n<p>This is an edge case and should not be taken TOO seriously. If you run the script from another script directly (without 'source'), using $0 will work.</p>\n" }, { "answer_id": 639500, "author": "Dimitre Radoulov", "author_id": 430749, "author_profile": "https://Stackoverflow.com/users/430749", "pm_score": 8, "selected": false, "text": "<p>With <em>bash >= 3</em> the following works:</p>\n\n<pre><code>$ ./s\n0 is: ./s\nBASH_SOURCE is: ./s\n$ . ./s\n0 is: bash\nBASH_SOURCE is: ./s\n\n$ cat s\n#!/bin/bash\n\nprintf '$0 is: %s\\n$BASH_SOURCE is: %s\\n' \"$0\" \"$BASH_SOURCE\"\n</code></pre>\n" }, { "answer_id": 3588939, "author": "Bill Hernandez", "author_id": 433461, "author_profile": "https://Stackoverflow.com/users/433461", "pm_score": 8, "selected": false, "text": "<pre>\n# ------------- SCRIPT ------------- #\n<code>\n#!/bin/bash\n\necho\necho \"# arguments called with ----> ${@} \"\necho \"# \\$1 ----------------------> $1 \"\necho \"# \\$2 ----------------------> $2 \"\necho \"# path to me ---------------> ${0} \"\necho \"# parent path --------------> ${0%/*} \"\necho \"# my name ------------------> ${0##*/} \"\necho\nexit\n</code>\n# ------------- CALLED ------------- #\n\n# Notice on the next line, the first argument is called within double, \n# and single quotes, since it contains two words\n\n<strong>$ /misc/shell_scripts/check_root/show_parms.sh \"'hello there'\" \"'william'\"</strong>\n\n# ------------- RESULTS ------------- #\n\n# arguments called with ---> 'hello there' 'william'\n# $1 ----------------------> 'hello there'\n# $2 ----------------------> 'william'\n# path to me --------------> /misc/shell_scripts/check_root/show_parms.sh\n# parent path -------------> /misc/shell_scripts/check_root\n# my name -----------------> show_parms.sh\n\n# ------------- END ------------- #\n</pre>\n" }, { "answer_id": 3939695, "author": "simon", "author_id": 88411, "author_profile": "https://Stackoverflow.com/users/88411", "pm_score": 3, "selected": false, "text": "<p>Re: Tanktalus's (accepted) answer above, a slightly cleaner way is to use:</p>\n\n<pre><code>me=$(readlink --canonicalize --no-newline $0)\n</code></pre>\n\n<p>If your script has been sourced from another bash script, you can use:</p>\n\n<pre><code>me=$(readlink --canonicalize --no-newline $BASH_SOURCE)\n</code></pre>\n\n<p>I agree that it would be confusing to dereference symlinks if your objective is to provide feedback to the user, but there are occasions when you do need to get the canonical name to a script or other file, and this is the best way, imo.</p>\n" }, { "answer_id": 5816258, "author": "Koter84", "author_id": 372131, "author_profile": "https://Stackoverflow.com/users/372131", "pm_score": 0, "selected": false, "text": "<pre><code>DIRECTORY=$(cd `dirname $0` &amp;&amp; pwd)\n</code></pre>\n\n<p>I got the above from another Stack&nbsp;Overflow question, <em><a href=\"https://stackoverflow.com/questions/59895\">Can a Bash script tell what directory it's stored in?</a></em>, but I think it's useful for this topic as well.</p>\n" }, { "answer_id": 6355632, "author": "Zainka", "author_id": 799290, "author_profile": "https://Stackoverflow.com/users/799290", "pm_score": 7, "selected": false, "text": "<p><code>$BASH_SOURCE</code> gives the correct answer when sourcing the script.</p>\n\n<p>This however includes the path so to get the scripts filename only, use:</p>\n\n<pre><code>$(basename $BASH_SOURCE) \n</code></pre>\n" }, { "answer_id": 13382923, "author": "jcalfee314", "author_id": 766233, "author_profile": "https://Stackoverflow.com/users/766233", "pm_score": 3, "selected": false, "text": "<pre><code>this=\"$(dirname \"$(realpath \"$BASH_SOURCE\")\")\"\n</code></pre>\n\n<p>This resolves symbolic links (realpath does that), handles spaces (double quotes do this), and will find the current script name even when sourced (. ./myscript) or called by other scripts ($BASH_SOURCE handles that). After all that, it is good to save this in a environment variable for re-use or for easy copy elsewhere (this=)...</p>\n" }, { "answer_id": 25596257, "author": "gkb0986", "author_id": 1988435, "author_profile": "https://Stackoverflow.com/users/1988435", "pm_score": 4, "selected": false, "text": "<p>I've found this line to always work, regardless of whether the file is being sourced or run as a script.</p>\n\n<pre><code>echo \"${BASH_SOURCE[${#BASH_SOURCE[@]} - 1]}\"\n</code></pre>\n\n<p>If you want to follow symlinks use <code>readlink</code> on the path you get above, recursively or non-recursively.</p>\n\n<p>The reason the one-liner works is explained by the use of the <code>BASH_SOURCE</code> environment variable and its associate <code>FUNCNAME</code>.</p>\n\n<blockquote>\n <p>BASH_SOURCE</p>\n \n <p>An array variable whose members are the source filenames where the corresponding shell function names in the FUNCNAME array variable are defined. The shell function ${FUNCNAME[$i]} is defined in the file ${BASH_SOURCE[$i]} and called from ${BASH_SOURCE[$i+1]}.</p>\n \n <p>FUNCNAME</p>\n \n <p>An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bottom-most element (the one with the highest index) is \"main\". This variable exists only when a shell function is executing. Assignments to FUNCNAME have no effect and return an error status. If FUNCNAME is unset, it loses its special properties, even if it is subsequently reset. </p>\n \n <p>This variable can be used with BASH_LINENO and BASH_SOURCE. Each element of FUNCNAME has corresponding elements in BASH_LINENO and BASH_SOURCE to describe the call stack. For instance, ${FUNCNAME[$i]} was called from the file ${BASH_SOURCE[$i+1]} at line number ${BASH_LINENO[$i]}. The caller builtin displays the current call stack using this information.</p>\n</blockquote>\n\n<p>[Source: Bash manual]</p>\n" }, { "answer_id": 28655324, "author": "linxuser", "author_id": 4593132, "author_profile": "https://Stackoverflow.com/users/4593132", "pm_score": 1, "selected": false, "text": "<p>Info thanks to Bill Hernandez. I added some preferences I'm adopting.</p>\n\n<pre><code>#!/bin/bash\nfunction Usage(){\n echo \" Usage: show_parameters [ arg1 ][ arg2 ]\"\n}\n[[ ${#2} -eq 0 ]] &amp;&amp; Usage || {\n echo\n echo \"# arguments called with ----&gt; ${@} \"\n echo \"# \\$1 -----------------------&gt; $1 \"\n echo \"# \\$2 -----------------------&gt; $2 \"\n echo \"# path to me ---------------&gt; ${0} \" | sed \"s/$USER/\\$USER/g\"\n echo \"# parent path --------------&gt; ${0%/*} \" | sed \"s/$USER/\\$USER/g\"\n echo \"# my name ------------------&gt; ${0##*/} \"\n echo\n}\n</code></pre>\n\n<p>Cheers</p>\n" }, { "answer_id": 29672098, "author": "hynt", "author_id": 4723557, "author_profile": "https://Stackoverflow.com/users/4723557", "pm_score": -1, "selected": false, "text": "<p>somthing like this? </p>\n\n<pre><code>export LC_ALL=en_US.UTF-8\n#!/bin/bash\n#!/bin/sh\n\n#----------------------------------------------------------------------\nstart_trash(){\nver=\"htrash.sh v0.0.4\"\n$TRASH_DIR # url to trash $MY_USER\n$TRASH_SIZE # Show Trash Folder Size\n\necho \"Would you like to empty Trash [y/n]?\"\nread ans\nif [ $ans = y -o $ans = Y -o $ans = yes -o $ans = Yes -o $ans = YES ]\nthen\necho \"'yes'\"\ncd $TRASH_DIR &amp;&amp; $EMPTY_TRASH\nfi\nif [ $ans = n -o $ans = N -o $ans = no -o $ans = No -o $ans = NO ]\nthen\necho \"'no'\"\nfi\n return $TRUE\n} \n#-----------------------------------------------------------------------\n\nstart_help(){\necho \"HELP COMMANDS-----------------------------\"\necho \"htest www open a homepage \"\necho \"htest trash empty trash \"\n return $TRUE\n} #end Help\n#-----------------------------------------------#\n\nhomepage=\"\"\n\nreturn $TRUE\n} #end cpdebtemp\n\n# -Case start\n# if no command line arg given\n# set val to Unknown\nif [ -z $1 ]\nthen\n val=\"*** Unknown ***\"\nelif [ -n $1 ]\nthen\n# otherwise make first arg as val\n val=$1\nfi\n# use case statement to make decision for rental\ncase $val in\n \"trash\") start_trash ;;\n \"help\") start_help ;;\n \"www\") firefox $homepage ;;\n *) echo \"Sorry, I can not get a $val for you!\";;\nesac\n# Case stop\n</code></pre>\n" }, { "answer_id": 41842579, "author": "LawrenceLi", "author_id": 2338372, "author_profile": "https://Stackoverflow.com/users/2338372", "pm_score": 3, "selected": false, "text": "<p>if your invoke shell script like </p>\n\n<pre><code>/home/mike/runme.sh\n</code></pre>\n\n<p>$0 is full name</p>\n\n<pre><code> /home/mike/runme.sh\n</code></pre>\n\n<p>basename $0 will get the base file name</p>\n\n<pre><code> runme.sh\n</code></pre>\n\n<p>and you need to put this basic name into a variable like</p>\n\n<pre><code>filename=$(basename $0)\n</code></pre>\n\n<p>and add your additional text </p>\n\n<pre><code>echo \"You are running $filename\"\n</code></pre>\n\n<p>so your scripts like </p>\n\n<pre><code>/home/mike/runme.sh\n#!/bin/bash \nfilename=$(basename $0)\necho \"You are running $filename\"\n</code></pre>\n" }, { "answer_id": 45658001, "author": "ecwpz91", "author_id": 7497692, "author_profile": "https://Stackoverflow.com/users/7497692", "pm_score": 2, "selected": false, "text": "<pre><code>echo \"$(basename \"`test -L ${BASH_SOURCE[0]} \\\n &amp;&amp; readlink ${BASH_SOURCE[0]} \\\n || echo ${BASH_SOURCE[0]}`\")\"\n</code></pre>\n" }, { "answer_id": 48344019, "author": "rashok", "author_id": 596370, "author_profile": "https://Stackoverflow.com/users/596370", "pm_score": 2, "selected": false, "text": "<p>In <code>bash</code> you can get the script file name using <code>$0</code>. Generally <code>$1</code>, <code>$2</code> etc are to access CLI arguments. Similarly <code>$0</code> is to access the name which triggers the script(script file name).</p>\n\n<pre><code>#!/bin/bash\necho \"You are running $0\"\n...\n...\n</code></pre>\n\n<p>If you invoke the script with path like <code>/path/to/script.sh</code> then <code>$0</code> also will give the filename with path. In that case need to use <code>$(basename $0)</code> to get only script file name.</p>\n" }, { "answer_id": 48628868, "author": "Simon Mattes", "author_id": 3687883, "author_profile": "https://Stackoverflow.com/users/3687883", "pm_score": 4, "selected": false, "text": "<p>Since some comments asked about the filename without extension, here's an example how to accomplish that:</p>\n\n<pre><code>FileName=${0##*/}\nFileNameWithoutExtension=${FileName%.*}\n</code></pre>\n\n<p>Enjoy!</p>\n" }, { "answer_id": 53457925, "author": "Salathiel Genèse", "author_id": 3748178, "author_profile": "https://Stackoverflow.com/users/3748178", "pm_score": 0, "selected": false, "text": "<p>Here is what I came up with, inspired by <a href=\"https://stackoverflow.com/users/430749/dimitre-radoulov\">Dimitre Radoulov</a>'s answer <em>(which I upvoted, by the way)</em>.</p>\n\n<pre><code>script=\"$BASH_SOURCE\"\n[ -z \"$BASH_SOURCE\" ] &amp;&amp; script=\"$0\"\n\necho \"Called $script with $# argument(s)\"\n</code></pre>\n\n<p>regardless of the way you call your script</p>\n\n<pre><code>. path/to/script.sh\n</code></pre>\n\n<p>or</p>\n\n<pre><code>./path/to/script.sh\n</code></pre>\n" }, { "answer_id": 57553697, "author": "Bơ Loong A Nhứi", "author_id": 4728084, "author_profile": "https://Stackoverflow.com/users/4728084", "pm_score": 2, "selected": false, "text": "<p>Short, clear and simple, in <code>my_script.sh</code></p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>#!/bin/bash\n\nrunning_file_name=$(basename \"$0\")\n\necho \"You are running '$running_file_name' file.\"\n</code></pre>\n\n<p>Out put:</p>\n\n<pre><code>./my_script.sh\nYou are running 'my_script.sh' file.\n</code></pre>\n" }, { "answer_id": 64516836, "author": "Nishant", "author_id": 452102, "author_profile": "https://Stackoverflow.com/users/452102", "pm_score": 3, "selected": false, "text": "<p>This works fine with <code>./self.sh</code>, <code>~/self.sh</code>, <code>source self.sh</code>, <code>source ~/self.sh</code>:</p>\n<pre><code>#!/usr/bin/env bash\n\nself=$(readlink -f &quot;${BASH_SOURCE[0]}&quot;)\nbasename=$(basename &quot;$self&quot;)\n\necho &quot;$self&quot;\necho &quot;$basename&quot;\n</code></pre>\n<p>Credits: I combined multiple answers to get this one.</p>\n" }, { "answer_id": 68599693, "author": "Ali Yar Khan", "author_id": 9138027, "author_profile": "https://Stackoverflow.com/users/9138027", "pm_score": 0, "selected": false, "text": "<p>$0 will give the name of the script you are running. Create a script file and add following code</p>\n<pre><code>#!/bin/bash\necho &quot;Name of the file is $0&quot;\n</code></pre>\n<p>then run from terminal like this</p>\n<pre><code>./file_name.sh\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192319", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20390/" ]
How can I determine the name of the Bash script file inside the script itself? Like if my script is in file `runme.sh`, then how would I make it to display "You are running runme.sh" message without hardcoding that?
``` me=`basename "$0"` ``` For reading through a symlink1, which is usually not what you want (you usually don't want to confuse the user this way), try: ``` me="$(basename "$(test -L "$0" && readlink "$0" || echo "$0")")" ``` IMO, that'll produce confusing output. "I ran foo.sh, but it's saying I'm running bar.sh!? Must be a bug!" Besides, one of the purposes of having differently-named symlinks is to provide different functionality based on the name it's called as (think gzip and gunzip on some platforms). --- 1 That is, to resolve symlinks such that when the user executes `foo.sh` which is actually a symlink to `bar.sh`, you wish to use the resolved name `bar.sh` rather than `foo.sh`.
192,329
<p>I have boiled down an issue I'm seeing in one of my applications to an incredibly simple reproduction sample. I need to know if there's something amiss or something I'm missing.</p> <p>Anyway, below is the code. The behavior is that the code runs and steadily grows in memory until it crashes with an OutOfMemoryException. That takes a while, but the behavior is that objects are being allocated and are not being garbage collected. </p> <p>I've taken memory dumps and ran !gcroot on some things as well as used ANTS to figure out what the problem is, but I've been at it for a while and need some new eyes.</p> <p>This reproduction sample is a simple console application that creates a Canvas and adds a Line to it. It does this continually. This is all the code does. It sleeps every now and again to ensure that the CPU is not so taxed that your system is unresponsive (and to ensure there's no weirdness with the GC not being able to run). </p> <p>Anyone have any thoughts? I've tried this with .NET 3.0 only, .NET 3.5 and also .NET 3.5 SP1 and the same behavior occurred in all three environments.</p> <p>Also note that I've put this code in a WPF application project as well and triggered the code in a button click and it occurs there too.</p> <pre> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Controls; using System.Windows.Shapes; using System.Windows; namespace SimplestReproSample { class Program { [STAThread] static void Main(string[] args) { long count = 0; while (true) { if (count++ % 100 == 0) { // sleep for a while to ensure we aren't using up the whole CPU System.Threading.Thread.Sleep(50); } BuildCanvas(); } } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void BuildCanvas() { Canvas c = new Canvas(); Line line = new Line(); line.X1 = 1; line.Y1 = 1; line.X2 = 100; line.Y2 = 100; line.Width = 100; c.Children.Add(line); c.Measure(new Size(300, 300)); c.Arrange(new Rect(0, 0, 300, 300)); } } } </pre> <p>NOTE: the first answer below is a bit off-base since I explicitly stated already that this same behavior occurs during a WPF application's button click event. I did not explicitly state, however, that in that app I only do a limited number of iterations (say 1000). Doing it that way would allow the GC to run as you click around the application. Also note that I explicitly said I've taken a memory dump and found my objects were rooted via !gcroot. I also disagree that the GC would not be able to run. The GC does not run on my console application's main thread, especially since I'm on a dual core machine which means the Concurrent Workstation GC is active. Message pump, however, yes.</p> <p>To prove the point, here's a WPF application version that runs the test on a DispatcherTimer. It performs 1000 iterations during a 100ms timer interval. More than enough time to process any messages out of the pump and keep the CPU usage low.</p> <pre> using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Shapes; namespace SimpleReproSampleWpfApp { public partial class Window1 : Window { private System.Windows.Threading.DispatcherTimer _timer; public Window1() { InitializeComponent(); _timer = new System.Windows.Threading.DispatcherTimer(); _timer.Interval = TimeSpan.FromMilliseconds(100); _timer.Tick += new EventHandler(_timer_Tick); _timer.Start(); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] void RunTest() { for (int i = 0; i &lt; 1000; i++) { BuildCanvas(); } } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void BuildCanvas() { Canvas c = new Canvas(); Line line = new Line(); line.X1 = 1; line.Y1 = 1; line.X2 = 100; line.Y2 = 100; line.Width = 100; c.Children.Add(line); c.Measure(new Size(300, 300)); c.Arrange(new Rect(0, 0, 300, 300)); } void _timer_Tick(object sender, EventArgs e) { _timer.Stop(); RunTest(); _timer.Start(); } } } </pre> <p>NOTE2: I used the code from the first answer and my memory grew very slowly. Note that 1ms is much slower and less iterations than my example. You have to let it run for a couple minutes before you start to notice growth. After 5 minutes it's at 46MB from a starting point of 30MB. </p> <p>NOTE3: Removing the call to .Arrange completely eliminates the growth. Unfortunately, that call is pretty vital to my use since in many cases I'm creating PNG files from the Canvas (via the RenderTargetBitmap class). Without the call to .Arrange it doesn't layout the canvas at all.</p>
[ { "answer_id": 192421, "author": "Joel B Fant", "author_id": 22211, "author_profile": "https://Stackoverflow.com/users/22211", "pm_score": 0, "selected": false, "text": "<p><strong>Edit 2:</strong> Obviously not the answer, but was part of the back-and-forth among answers and comments here, so I'm not deleting it.</p>\n\n<p>The GC never gets a chance to collect those objects because your loop and its blocking calls never end, and therefore the message pump and events never get their turn. If you used a <code>Timer</code> of some sort so that messages and events actually have a chance to process, you probably wouldn't be able to eat up all your memory.</p>\n\n<p><strong>Edit:</strong> The following does not eat up my memory as long as the interval is greater than zero. Even if the interval is just 1 Tick, as long as it isn't 0. If it's 0, we're back to the infinite loop.</p>\n\n<pre><code>public partial class Window1 : Window {\n Class1 c;\n DispatcherTimer t;\n int count = 0;\n public Window1() {\n InitializeComponent();\n\n t = new DispatcherTimer();\n t.Interval = TimeSpan.FromMilliseconds( 1 );\n t.Tick += new EventHandler( t_Tick );\n t.Start();\n }\n\n void t_Tick( object sender, EventArgs e ) {\n count++;\n BuildCanvas();\n }\n\n private static void BuildCanvas() {\n Canvas c = new Canvas();\n\n Line line = new Line();\n line.X1 = 1;\n line.Y1 = 1;\n line.X2 = 100;\n line.Y2 = 100;\n line.Width = 100;\n c.Children.Add( line );\n\n c.Measure( new Size( 300, 300 ) );\n c.Arrange( new Rect( 0, 0, 300, 300 ) );\n }\n}\n</code></pre>\n" }, { "answer_id": 192578, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 1, "selected": false, "text": "<p>Normally in .NET GC gets triggered on object allocation upon crossing a certain threshold, it does not depend on message pumps (I can't imagine it's different with WPF).</p>\n\n<p>I suspect that Canvas objects are somehow rooted deep inside or something. If you do c.Children.Clear() right before the BuildCanvas method finishes, the memory growth slows down dramatically.</p>\n\n<p>Anyway, as a commenter noted here, such usage of framework elements is pretty unusual. Why do you need so many Canvases? </p>\n" }, { "answer_id": 193609, "author": "Bradley Grainger", "author_id": 23633, "author_profile": "https://Stackoverflow.com/users/23633", "pm_score": 5, "selected": true, "text": "<p>I was able to reproduce your problem using the code you provided. Memory keeps growing because the Canvas objects are never released; a memory profiler indicates that the Dispatcher's ContextLayoutManager is holding on to them all (so that it can invoke OnRenderSizeChanged when necessary).</p>\n\n<p>It seems that a simple workaround is to add</p>\n\n<pre><code>c.UpdateLayout()\n</code></pre>\n\n<p>to the end of <code>BuildCanvas</code>.</p>\n\n<p>That said, note that <code>Canvas</code> is a <code>UIElement</code>; it's supposed to be used in UI. It's not designed to be used as an arbitrary drawing surface. As other commenters have already noted, the creation of thousands of Canvas objects may indicate a design flaw. I realise that your production code may be more complicated, but if it's just drawing simple shapes on a canvas, GDI+-based code (i.e., the System.Drawing classes) may be more appropriate.</p>\n" }, { "answer_id": 3614625, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<p>WPF in .NET 3 and 3.5 has an internal memory leak. It only triggers under certain situations. We could never figure out exactly what triggers it, but we had it in our app. Apparently it's fixed in .NET 4.</p>\n\n<p>I think it's the same as the one mentioned in <a href=\"http://wesaday.wordpress.com/tag/cmilchannel-hwndsource/\" rel=\"nofollow noreferrer\">this blog post</a></p>\n\n<p>At any rate, putting the following code in the <code>App.xaml.cs</code> constructor solved it for us</p>\n\n<pre><code>public partial class App : Application\n{\n public App() \n { \n new HwndSource(new HwndSourceParameters()); \n } \n}\n</code></pre>\n\n<p>If nothing else solves it, try that and see</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13322/" ]
I have boiled down an issue I'm seeing in one of my applications to an incredibly simple reproduction sample. I need to know if there's something amiss or something I'm missing. Anyway, below is the code. The behavior is that the code runs and steadily grows in memory until it crashes with an OutOfMemoryException. That takes a while, but the behavior is that objects are being allocated and are not being garbage collected. I've taken memory dumps and ran !gcroot on some things as well as used ANTS to figure out what the problem is, but I've been at it for a while and need some new eyes. This reproduction sample is a simple console application that creates a Canvas and adds a Line to it. It does this continually. This is all the code does. It sleeps every now and again to ensure that the CPU is not so taxed that your system is unresponsive (and to ensure there's no weirdness with the GC not being able to run). Anyone have any thoughts? I've tried this with .NET 3.0 only, .NET 3.5 and also .NET 3.5 SP1 and the same behavior occurred in all three environments. Also note that I've put this code in a WPF application project as well and triggered the code in a button click and it occurs there too. ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Controls; using System.Windows.Shapes; using System.Windows; namespace SimplestReproSample { class Program { [STAThread] static void Main(string[] args) { long count = 0; while (true) { if (count++ % 100 == 0) { // sleep for a while to ensure we aren't using up the whole CPU System.Threading.Thread.Sleep(50); } BuildCanvas(); } } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void BuildCanvas() { Canvas c = new Canvas(); Line line = new Line(); line.X1 = 1; line.Y1 = 1; line.X2 = 100; line.Y2 = 100; line.Width = 100; c.Children.Add(line); c.Measure(new Size(300, 300)); c.Arrange(new Rect(0, 0, 300, 300)); } } } ``` NOTE: the first answer below is a bit off-base since I explicitly stated already that this same behavior occurs during a WPF application's button click event. I did not explicitly state, however, that in that app I only do a limited number of iterations (say 1000). Doing it that way would allow the GC to run as you click around the application. Also note that I explicitly said I've taken a memory dump and found my objects were rooted via !gcroot. I also disagree that the GC would not be able to run. The GC does not run on my console application's main thread, especially since I'm on a dual core machine which means the Concurrent Workstation GC is active. Message pump, however, yes. To prove the point, here's a WPF application version that runs the test on a DispatcherTimer. It performs 1000 iterations during a 100ms timer interval. More than enough time to process any messages out of the pump and keep the CPU usage low. ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Shapes; namespace SimpleReproSampleWpfApp { public partial class Window1 : Window { private System.Windows.Threading.DispatcherTimer _timer; public Window1() { InitializeComponent(); _timer = new System.Windows.Threading.DispatcherTimer(); _timer.Interval = TimeSpan.FromMilliseconds(100); _timer.Tick += new EventHandler(_timer_Tick); _timer.Start(); } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] void RunTest() { for (int i = 0; i < 1000; i++) { BuildCanvas(); } } [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] private static void BuildCanvas() { Canvas c = new Canvas(); Line line = new Line(); line.X1 = 1; line.Y1 = 1; line.X2 = 100; line.Y2 = 100; line.Width = 100; c.Children.Add(line); c.Measure(new Size(300, 300)); c.Arrange(new Rect(0, 0, 300, 300)); } void _timer_Tick(object sender, EventArgs e) { _timer.Stop(); RunTest(); _timer.Start(); } } } ``` NOTE2: I used the code from the first answer and my memory grew very slowly. Note that 1ms is much slower and less iterations than my example. You have to let it run for a couple minutes before you start to notice growth. After 5 minutes it's at 46MB from a starting point of 30MB. NOTE3: Removing the call to .Arrange completely eliminates the growth. Unfortunately, that call is pretty vital to my use since in many cases I'm creating PNG files from the Canvas (via the RenderTargetBitmap class). Without the call to .Arrange it doesn't layout the canvas at all.
I was able to reproduce your problem using the code you provided. Memory keeps growing because the Canvas objects are never released; a memory profiler indicates that the Dispatcher's ContextLayoutManager is holding on to them all (so that it can invoke OnRenderSizeChanged when necessary). It seems that a simple workaround is to add ``` c.UpdateLayout() ``` to the end of `BuildCanvas`. That said, note that `Canvas` is a `UIElement`; it's supposed to be used in UI. It's not designed to be used as an arbitrary drawing surface. As other commenters have already noted, the creation of thousands of Canvas objects may indicate a design flaw. I realise that your production code may be more complicated, but if it's just drawing simple shapes on a canvas, GDI+-based code (i.e., the System.Drawing classes) may be more appropriate.
192,332
<p>What I am looking for is a way to call a method after another method has been invoked but before it is entered. Example:</p> <pre><code>public class Test { public void Tracer ( ... ) { } public int SomeFunction( string str ) { return 0; } public void TestFun() { SomeFunction( "" ); } } </code></pre> <p>In the example above I would like to have Tracer() called after SomeFunction() has been invoked by TestFun() but before SomeFunction() is entered. I'd also like to get reflection data on SomeFunction().</p> <hr> <p>I found something interesting in everyone's answers. The <strong>best answer to the question</strong> is to use Castle's DynamicProxy; however, this is not that I'm going to use to solve my problem because it requires adding a library to my project. I have only a few methods that I need to "trace" so I've chosen to go with a modified "core" methodology mixed with the way Dynamic Proxy is implemented. I explain this in my answer to my own question below.</p> <p>Just as a note I'm going to be looking into AOP and the ContextBoundObject class for some other applications.</p>
[ { "answer_id": 192355, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 2, "selected": false, "text": "<p>Use a *Core method:</p>\n\n<pre><code>public int SomeFunction(string str)\n{\n Tracer();\n return SomeFunctionCore(str);\n}\n\nprivate int SomeFunctionCore(string str)\n{\n return 0;\n}\n</code></pre>\n\n<p>A number of the .NET APIs use this (lots do in WPF).</p>\n" }, { "answer_id": 192356, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 4, "selected": true, "text": "<p>You can use a dynamic proxy (<a href=\"http://www.castleproject.org/dynamicproxy/index.html\" rel=\"nofollow noreferrer\">Castle's DynamicProxy</a> for example) to intercept the call, run whatever code you wish, and then either invoke your method or not, depending on your needs.</p>\n" }, { "answer_id": 192359, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 1, "selected": false, "text": "<p>You want to look into Aspect Oriented Programming. Here's a page I found for AOP in .NET: <a href=\"http://www.postsharp.org/aop.net/\" rel=\"nofollow noreferrer\">http://www.postsharp.org/aop.net/</a></p>\n\n<p>Aspect Oriented Programming involves separating out \"crosscutting concerns\" from code. One example of this is logging - logging exists (hopefully) across all of your code. Should these methods all really need to know about logging? Maybe not. AOP is the study of separating these concerns from the code they deal with, and injecting them back in, either at compile-time or run-time. The link I posted contains links to several tools that can be used for both compile-time and run-time AOP.</p>\n" }, { "answer_id": 192360, "author": "jop", "author_id": 11830, "author_profile": "https://Stackoverflow.com/users/11830", "pm_score": 0, "selected": false, "text": "<p>You would have to use some form of AOP framework like <a href=\"http://www.springframework.net/doc-latest/reference/html/aop-quickstart.html\" rel=\"nofollow noreferrer\">SpringFramework.NET</a> to do that.</p>\n" }, { "answer_id": 192675, "author": "Brian ONeil", "author_id": 21371, "author_profile": "https://Stackoverflow.com/users/21371", "pm_score": 1, "selected": false, "text": "<p>.NET has a class called ContextBoundObject that you can use to setup message sinks to do call interception as long as you don't mind deriving from a base class this will give you what you are looking for without taking an library dependency.</p>\n" }, { "answer_id": 192847, "author": "Tim Farley", "author_id": 4425, "author_profile": "https://Stackoverflow.com/users/4425", "pm_score": 0, "selected": false, "text": "<p>If you need to do this on large scale (i.e. for every function in a program) and you don't want to hugely alter the source, you might look into using the <a href=\"http://msdn.microsoft.com/en-us/magazine/cc301725.aspx\" rel=\"nofollow noreferrer\">.NET Profiling API</a>. Its a little hairy to use since you have to build free-threaded COM objects to do so, but it gives you an enormous amount of control over the execution of the program.</p>\n" }, { "answer_id": 193587, "author": "jr.", "author_id": 2415, "author_profile": "https://Stackoverflow.com/users/2415", "pm_score": 0, "selected": false, "text": "<p>This is the solution I've choosen to solve my problem. Since there is no automatic (attribute like) way to make this work I feel it is the least obtrusive and allows the functionality to be turned on and off by choosing what class get instantiated. Please note that <strong>this is not</strong> the best answer to my question but it is the better answer for my particular situation.</p>\n\n<p>What's going on is that we're simply deriving a second class that sometimes or always be instantiated in place of its parent. The methods that we want to trace (or otherwise track) are declared virtual and reimplemented in the derived class to perform whatever actions we want to trace and then the function is called in the parent class.</p>\n\n<pre><code>public class TestClass {\n\n public virtual void int SomeFunction( string /*str*/ )\n {\n return 0;\n }\n\n\n public void TestFun()\n {\n SomeFunction( \"\" );\n }\n\n}\n\n\npublic class TestClassTracer : TestClass {\n\n public override void int SomeFunction( string str )\n {\n // do something\n return base.SomeFunction( str );\n }\n\n}\n</code></pre>\n" }, { "answer_id": 194287, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p><strong>Use delegates!</strong></p>\n\n<pre><code>delegate void SomeFunctionDelegate(string s);\n\nvoid Start()\n{\n TraceAndThenCallMethod(SomeFunction, \"hoho\");\n}\n\nvoid SomeFunction(string str)\n{\n //Do stuff with str\n}\n\nvoid TraceAndThenCallMethod(SomeFunctionDelegate sfd, string parameter)\n{\n Trace();\n sfd(parameter);\n}\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2415/" ]
What I am looking for is a way to call a method after another method has been invoked but before it is entered. Example: ``` public class Test { public void Tracer ( ... ) { } public int SomeFunction( string str ) { return 0; } public void TestFun() { SomeFunction( "" ); } } ``` In the example above I would like to have Tracer() called after SomeFunction() has been invoked by TestFun() but before SomeFunction() is entered. I'd also like to get reflection data on SomeFunction(). --- I found something interesting in everyone's answers. The **best answer to the question** is to use Castle's DynamicProxy; however, this is not that I'm going to use to solve my problem because it requires adding a library to my project. I have only a few methods that I need to "trace" so I've chosen to go with a modified "core" methodology mixed with the way Dynamic Proxy is implemented. I explain this in my answer to my own question below. Just as a note I'm going to be looking into AOP and the ContextBoundObject class for some other applications.
You can use a dynamic proxy ([Castle's DynamicProxy](http://www.castleproject.org/dynamicproxy/index.html) for example) to intercept the call, run whatever code you wish, and then either invoke your method or not, depending on your needs.
192,366
<p>Is it possible to grab activedirectory credentials for the user on a client machine from within a web application?</p> <p>To clarify, I am designing a web application which will be hosted on a client's intranet. </p> <p>There is a requirement that the a user of the application not be prompted for credentials when accessing the application, and that instead the credentials of the user logged onto the client machine should be grabbed automatically, without user interaction.</p>
[ { "answer_id": 192405, "author": "Simurr", "author_id": 3478, "author_profile": "https://Stackoverflow.com/users/3478", "pm_score": 1, "selected": false, "text": "<p>Maybe .NET has a more direct way to do it, but with PHP I just access our Active Directory server as an LDAP server.</p>\n\n<p>I'm not sure what adjustments to the server are required to do this. I didn't setup the server, I just query it.\nI'm not suggesting you use PHP either. I just find it easier to deal with LDAP then trying to tie directly into Active Directory.</p>\n" }, { "answer_id": 192414, "author": "Sean Hanley", "author_id": 7290, "author_profile": "https://Stackoverflow.com/users/7290", "pm_score": 3, "selected": false, "text": "<p>Absolutely. This is especially useful for intranet applications.</p>\n\n<p>Since you did not specify your environment, I'll assume it is .NET, but that isn't the only way possible of course.</p>\n\n<p>Active Directory can be queried easily using <a href=\"http://en.wikipedia.org/wiki/LDAP\" rel=\"nofollow noreferrer\">LDAP</a>. If you're using .NET, you can do something like in <a href=\"http://www.codeproject.com/KB/system/QueryADwithDotNet.aspx\" rel=\"nofollow noreferrer\">this code example</a> or my example below. You can also do it within <a href=\"https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-22_11-5259887.html\" rel=\"nofollow noreferrer\">SQL environments</a> as well.</p>\n\n<p>If you just need Windows to handle authentication, you can set, for example, a .NET Web app up for <a href=\"http://weblogs.asp.net/scottgu/archive/2006/07/12/Recipe_3A00_-Enabling-Windows-Authentication-within-an-Intranet-ASP.NET-Web-application.aspx\" rel=\"nofollow noreferrer\">Windows Authentication</a>. Be sure to <a href=\"http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/524404dc-8586-46b0-89ac-0f5db6d33c9c.mspx?mfr=true\" rel=\"nofollow noreferrer\"><strong>turn off Anonymous Logins</strong></a> within IIS for your application. Once done, you'll be able to access the user's Windows logon name and use it to make further security checks (for example, their <a href=\"http://msdn.microsoft.com/en-us/library/4z6b5d42.aspx\" rel=\"nofollow noreferrer\">group/role membership</a> in AD).</p>\n\n<p>You can also simplify the whole mess using something like Enterprise Library's <a href=\"http://msdn.microsoft.com/en-us/library/cc309291.aspx\" rel=\"nofollow noreferrer\">Security Application Block</a>.</p>\n\n<hr>\n\n<p>Here is a short C# example: (convert to VB.NET <a href=\"http://www.developerfusion.com/tools/convert/csharp-to-vb/\" rel=\"nofollow noreferrer\">here</a>)</p>\n\n<pre><code>using System.DirectoryServices;\n\n/// &lt;summary&gt;\n/// Gets the email address, if defined, of a user from Active Directory.\n/// &lt;/summary&gt;\n/// &lt;param name=\"userid\"&gt;The userid of the user in question. Make\n/// sure the domain has been stripped first!&lt;/param&gt;\n/// &lt;returns&gt;A string containing the user's email address, or null\n/// if one was not defined or found.&lt;/returns&gt;\npublic static string GetEmail(string userid)\n{\n DirectorySearcher searcher;\n SearchResult result;\n string email;\n\n // Check first if there is a slash in the userid\n // If there is, domain has not been stripped\n if (!userid.Contains(\"\\\\\"))\n {\n searcher = new DirectorySearcher();\n searcher.Filter = String.Format(\"(SAMAccountName={0})\", userid);\n searcher.PropertiesToLoad.Add(\"mail\");\n result = searcher.FindOne();\n if (result != null)\n {\n email = result.Properties[\"mail\"][0].ToString();\n }\n }\n\n return email;\n}\n</code></pre>\n\n<p>You do not have to specify a domain controller. Performing the empty/default constructor for DirectorySearcher will cause it to attempt to look one up automatically &mdash; in fact, this is <a href=\"http://weblogs.asp.net/steveschofield/archive/2004/04/28/121857.aspx\" rel=\"nofollow noreferrer\"><strong>the preferred method</strong></a>.</p>\n" }, { "answer_id": 192416, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "<p>No, of course not. Can you imagine the havoc that would result in random web apps being able to get your AD username and password?</p>\n\n<p>Now, if you just want the username - that's in REMOTE_USER if you're using <a href=\"http://en.wikipedia.org/wiki/Integrated_Windows_Authentication\" rel=\"nofollow noreferrer\">integated windows auth</a>. And, windows auth will auto login the user to your site - assuming you share a domain (or trust).</p>\n\n<p>Edit: IWA works in an intranet scenario, since IE - by default - includes intranet sites in the Intranet security zone. Also, a sysadmin can use GPO to set other trusted sites. Firefox also <a href=\"http://www.testingreflections.com/node/view/1365\" rel=\"nofollow noreferrer\">supports NTLM</a>, as does <a href=\"http://www.pmwiki.org/wiki/Cookbook/SingleSign-On\" rel=\"nofollow noreferrer\">Opera</a> and <a href=\"http://weblogs.asp.net/erobillard/archive/2008/09/02/google-chrome-works-for-sharepoint-users-less-so-for-administrators.aspx\" rel=\"nofollow noreferrer\">Chrome</a>. All in all, it's not a bad way to setup an intranet.</p>\n\n<p>Note, though - that you don't get credentials. You negotiate a token with the client, which is what keeps IWA secure (and my above point relevant).</p>\n" }, { "answer_id": 193263, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "<p>Windows Integrated Authentication, user has to use IE, AND the site has to be in the user's trusted sites. If these things are true, then IE will pass your windows security token to the web site and it will authenticate with it. We do this with SharePoint on our intranet otherwise it's a pain to access anything restricted -- you'd get prompted every time you click on a document.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26527/" ]
Is it possible to grab activedirectory credentials for the user on a client machine from within a web application? To clarify, I am designing a web application which will be hosted on a client's intranet. There is a requirement that the a user of the application not be prompted for credentials when accessing the application, and that instead the credentials of the user logged onto the client machine should be grabbed automatically, without user interaction.
Absolutely. This is especially useful for intranet applications. Since you did not specify your environment, I'll assume it is .NET, but that isn't the only way possible of course. Active Directory can be queried easily using [LDAP](http://en.wikipedia.org/wiki/LDAP). If you're using .NET, you can do something like in [this code example](http://www.codeproject.com/KB/system/QueryADwithDotNet.aspx) or my example below. You can also do it within [SQL environments](https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-22_11-5259887.html) as well. If you just need Windows to handle authentication, you can set, for example, a .NET Web app up for [Windows Authentication](http://weblogs.asp.net/scottgu/archive/2006/07/12/Recipe_3A00_-Enabling-Windows-Authentication-within-an-Intranet-ASP.NET-Web-application.aspx). Be sure to [**turn off Anonymous Logins**](http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/524404dc-8586-46b0-89ac-0f5db6d33c9c.mspx?mfr=true) within IIS for your application. Once done, you'll be able to access the user's Windows logon name and use it to make further security checks (for example, their [group/role membership](http://msdn.microsoft.com/en-us/library/4z6b5d42.aspx) in AD). You can also simplify the whole mess using something like Enterprise Library's [Security Application Block](http://msdn.microsoft.com/en-us/library/cc309291.aspx). --- Here is a short C# example: (convert to VB.NET [here](http://www.developerfusion.com/tools/convert/csharp-to-vb/)) ``` using System.DirectoryServices; /// <summary> /// Gets the email address, if defined, of a user from Active Directory. /// </summary> /// <param name="userid">The userid of the user in question. Make /// sure the domain has been stripped first!</param> /// <returns>A string containing the user's email address, or null /// if one was not defined or found.</returns> public static string GetEmail(string userid) { DirectorySearcher searcher; SearchResult result; string email; // Check first if there is a slash in the userid // If there is, domain has not been stripped if (!userid.Contains("\\")) { searcher = new DirectorySearcher(); searcher.Filter = String.Format("(SAMAccountName={0})", userid); searcher.PropertiesToLoad.Add("mail"); result = searcher.FindOne(); if (result != null) { email = result.Properties["mail"][0].ToString(); } } return email; } ``` You do not have to specify a domain controller. Performing the empty/default constructor for DirectorySearcher will cause it to attempt to look one up automatically — in fact, this is [**the preferred method**](http://weblogs.asp.net/steveschofield/archive/2004/04/28/121857.aspx).
192,367
<p>I have the following two models:</p> <pre><code>class Activity(models.Model): name = models.CharField(max_length=50, help_text='Some help.') entity = models.ForeignKey(CancellationEntity) ... class Cancellation(models.Model): activity = models.ForeignKey(Activity) date = models.DateField(default=datetime.now().date()) description = models.CharField(max_length=250) ... </code></pre> <p>I would like the Activity model to be aware when a Cancellation related to it is saved (both inserted or updated).</p> <p>What is the best way to go about this?</p>
[ { "answer_id": 192525, "author": "willurd", "author_id": 1943957, "author_profile": "https://Stackoverflow.com/users/1943957", "pm_score": 5, "selected": true, "text": "<p>What you want to look into is <a href=\"http://docs.djangoproject.com/en/dev/ref/signals/\" rel=\"noreferrer\">Django's signals</a> (check out <a href=\"http://docs.djangoproject.com/en/dev/topics/signals/\" rel=\"noreferrer\">this page</a> too), specifically the model signals--more specifically, the <strong>post_save</strong> signal. Signals are Django's version of a plugin/hook system. The post_save signal gets sent every time a model is saved, whether it's updated or created (and it'll let you know if it was created). This is how you'd use signals to get notified when an Activity has a Cancellation</p>\n\n<pre><code>from django.db.models.signals import post_save\n\nclass Activity(models.Model):\n name = models.CharField(max_length=50, help_text='Some help.')\n entity = models.ForeignKey(CancellationEntity)\n\n @classmethod\n def cancellation_occurred (sender, instance, created, raw):\n # grab the current instance of Activity\n self = instance.activity_set.all()[0]\n # do something\n ...\n\n\nclass Cancellation(models.Model):\n activity = models.ForeignKey(Activity)\n date = models.DateField(default=datetime.now().date())\n description = models.CharField(max_length=250)\n ...\n\npost_save.connect(Activity.cancellation_occurred, sender=Cancellation)</code></pre>\n" }, { "answer_id": 193217, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 3, "selected": false, "text": "<p>What's wrong with the following?</p>\n\n<pre><code>class Cancellation( models.Model ):\n blah\n blah\n def save( self, **kw ):\n for a in self.activity_set.all():\n a.somethingChanged( self )\n super( Cancellation, self ).save( **kw )\n</code></pre>\n\n<p>It would allow you to to control the notification among models very precisely. In a way, this is the canonical \"Why is OO so good?\" question. I think OO is good precisely because your collection of Cancellation and Activity objects can cooperate fully.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10825/" ]
I have the following two models: ``` class Activity(models.Model): name = models.CharField(max_length=50, help_text='Some help.') entity = models.ForeignKey(CancellationEntity) ... class Cancellation(models.Model): activity = models.ForeignKey(Activity) date = models.DateField(default=datetime.now().date()) description = models.CharField(max_length=250) ... ``` I would like the Activity model to be aware when a Cancellation related to it is saved (both inserted or updated). What is the best way to go about this?
What you want to look into is [Django's signals](http://docs.djangoproject.com/en/dev/ref/signals/) (check out [this page](http://docs.djangoproject.com/en/dev/topics/signals/) too), specifically the model signals--more specifically, the **post\_save** signal. Signals are Django's version of a plugin/hook system. The post\_save signal gets sent every time a model is saved, whether it's updated or created (and it'll let you know if it was created). This is how you'd use signals to get notified when an Activity has a Cancellation ``` from django.db.models.signals import post_save class Activity(models.Model): name = models.CharField(max_length=50, help_text='Some help.') entity = models.ForeignKey(CancellationEntity) @classmethod def cancellation_occurred (sender, instance, created, raw): # grab the current instance of Activity self = instance.activity_set.all()[0] # do something ... class Cancellation(models.Model): activity = models.ForeignKey(Activity) date = models.DateField(default=datetime.now().date()) description = models.CharField(max_length=250) ... post_save.connect(Activity.cancellation_occurred, sender=Cancellation) ```
192,375
<p>When using <code>before_filter :login_required</code> to protect a particular page, the <code>link_to_unless_current</code> method in the application layout template renders the "Login" link for the login page as a hyperlink instead of just text.</p> <p>The "Login" text/link problem only occurs when redirected to the Login Page via the <code>before_filter</code> machinery, otherwise, the <code>link_to_unless_current</code> method operates as expected.</p> <p>It seems that <code>link_to_unless_current</code> is using the old page data as the "current" instead of the login page (when redirecting).</p>
[ { "answer_id": 198104, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Appreciate the responses and you can tell by the nature of the question that we're new to rails. By the way, we posted the same question on this site: <a href=\"http://railsforum.com\" rel=\"nofollow noreferrer\">http://railsforum.com</a> (not sure if it's the official rails forum) with no response yet. StackOverflow so far seems to be creating a great community of helpers willing to reach out to the programmatically challenged.</p>\n\n<p>I think part of the problem is that we were mixing restful urls with standard routes. The login page is mapped to the restful route \"/login\" but the page redirection was using \"/sessions/new\" (Rick Olson's restful authentication module)</p>\n\n<p>In application.rb, we forced the filter to \"/login\" and that solved the problem:</p>\n\n<pre>\nbefore_filter :login_required\n\nprotected\n\ndef login_required\n return true if logged_in?\n session[:return_to] = request.request_uri\n flash[:error] = \"Please log in first\"\n redirect_to \"/login\" and return false\nend\n</pre>\n\n<p>Comments on the technical merits of this approach appreciated as it may be helpful to other newbs.</p>\n\n<p>Thanks,\nJoe</p>\n" }, { "answer_id": 527112, "author": "Toby Hede", "author_id": 14971, "author_profile": "https://Stackoverflow.com/users/14971", "pm_score": 1, "selected": false, "text": "<p>You can use a route helper method to perform the page redirection:</p>\n\n<pre><code> redirect_to login_url\n</code></pre>\n\n<p>If a \"named route\" for login is defined (which is done by adding an explicit path to \"/login\" in your \"config/routes.rb\" file).</p>\n\n<p>This path is actually the same as that generated by:</p>\n\n<p>new_session_url</p>\n\n<p>For a detailed look at routing, I suggest the <a href=\"http://guides.rubyonrails.org/routing_outside_in.html\" rel=\"nofollow noreferrer\"><strong>Rails Routing Guide</strong></a>.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When using `before_filter :login_required` to protect a particular page, the `link_to_unless_current` method in the application layout template renders the "Login" link for the login page as a hyperlink instead of just text. The "Login" text/link problem only occurs when redirected to the Login Page via the `before_filter` machinery, otherwise, the `link_to_unless_current` method operates as expected. It seems that `link_to_unless_current` is using the old page data as the "current" instead of the login page (when redirecting).
You can use a route helper method to perform the page redirection: ``` redirect_to login_url ``` If a "named route" for login is defined (which is done by adding an explicit path to "/login" in your "config/routes.rb" file). This path is actually the same as that generated by: new\_session\_url For a detailed look at routing, I suggest the [**Rails Routing Guide**](http://guides.rubyonrails.org/routing_outside_in.html).
192,398
<p>I am selecting from a table that has an XML column using T-SQL. I would like to select a certain type of node and have a row created for each one.</p> <p>For instance, suppose I am selecting from a <em>people</em> table. This table has an XML column for <em>addresses</em>. The XML is formated similar to the following:</p> <pre><code>&lt;address&gt; &lt;street&gt;Street 1&lt;/street&gt; &lt;city&gt;City 1&lt;/city&gt; &lt;state&gt;State 1&lt;/state&gt; &lt;zipcode&gt;Zip Code 1&lt;/zipcode&gt; &lt;/address&gt; &lt;address&gt; &lt;street&gt;Street 2&lt;/street&gt; &lt;city&gt;City 2&lt;/city&gt; &lt;state&gt;State 2&lt;/state&gt; &lt;zipcode&gt;Zip Code 2&lt;/zipcode&gt; &lt;/address&gt; </code></pre> <p>How can I get results like this:</p> <p><strong>Name</strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>City</strong>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>State</strong></p> <p>Joe Baker&nbsp;&nbsp;&nbsp;Seattle&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WA</p> <p>Joe Baker&nbsp;&nbsp;&nbsp;Tacoma&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;WA</p> <p>Fred Jones&nbsp;&nbsp;Vancouver&nbsp;BC</p>
[ { "answer_id": 192445, "author": "Wyatt", "author_id": 26626, "author_profile": "https://Stackoverflow.com/users/26626", "pm_score": -1, "selected": false, "text": "<p>If you can use it, the linq api is convenient for XML:</p>\n\n<pre><code>var addresses = dataContext.People.Addresses\n .Elements(\"address\")\n .Select(address =&gt; new { \n street = address.Element(\"street\").Value, \n city = address.Element(\"city\").Value, \n state = address.Element(\"state\").Value, \n zipcode = address.Element(\"zipcode\").Value, \n });\n</code></pre>\n" }, { "answer_id": 193625, "author": "leoinfo", "author_id": 6948, "author_profile": "https://Stackoverflow.com/users/6948", "pm_score": 6, "selected": true, "text": "<p>Here is your solution: </p>\n\n<pre><code>/* TEST TABLE */\nDECLARE @PEOPLE AS TABLE ([Name] VARCHAR(20), [Address] XML )\nINSERT INTO @PEOPLE SELECT \n 'Joel', \n '&lt;address&gt;\n &lt;street&gt;Street 1&lt;/street&gt;\n &lt;city&gt;City 1&lt;/city&gt;\n &lt;state&gt;State 1&lt;/state&gt;\n &lt;zipcode&gt;Zip Code 1&lt;/zipcode&gt;\n &lt;/address&gt;\n &lt;address&gt;\n &lt;street&gt;Street 2&lt;/street&gt;\n &lt;city&gt;City 2&lt;/city&gt;\n &lt;state&gt;State 2&lt;/state&gt;\n &lt;zipcode&gt;Zip Code 2&lt;/zipcode&gt;\n &lt;/address&gt;'\nUNION ALL SELECT\n 'Kim', \n '&lt;address&gt;\n &lt;street&gt;Street 3&lt;/street&gt;\n &lt;city&gt;City 3&lt;/city&gt;\n &lt;state&gt;State 3&lt;/state&gt;\n &lt;zipcode&gt;Zip Code 3&lt;/zipcode&gt;\n &lt;/address&gt;'\n\nSELECT * FROM @PEOPLE\n\n-- BUILD XML\nDECLARE @x XML\nSELECT @x = \n( SELECT \n [Name]\n , [Address].query('\n for $a in //address\n return &lt;address \n street=\"{$a/street}\" \n city=\"{$a/city}\" \n state=\"{$a/state}\" \n zipcode=\"{$a/zipcode}\" \n /&gt;\n ') \n FROM @PEOPLE AS people \n FOR XML AUTO\n) \n\n-- RESULTS\nSELECT [Name] = T.Item.value('../@Name', 'varchar(20)'),\n street = T.Item.value('@street' , 'varchar(20)'),\n city = T.Item.value('@city' , 'varchar(20)'),\n state = T.Item.value('@state' , 'varchar(20)'),\n zipcode = T.Item.value('@zipcode', 'varchar(20)')\nFROM @x.nodes('//people/address') AS T(Item)\n\n/* OUTPUT*/\n\nName | street | city | state | zipcode\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nJoel | Street 1 | City 1 | State 1 | Zip Code 1\nJoel | Street 2 | City 2 | State 2 | Zip Code 2\nKim | Street 3 | City 3 | State 3 | Zip Code 3\n</code></pre>\n" }, { "answer_id": 194657, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 1, "selected": false, "text": "<p>Here's how I do it generically:</p>\n\n<p>I shred the source XML via a call such as</p>\n\n<pre>\n<code>\n\nDECLARE @xmlEntityList xml\nSET @xmlEntityList =\n'\n&lt;ArbitrarilyNamedXmlListElement&gt;\n &lt;ArbitrarilyNamedXmlItemElement&gt;&lt;SomeVeryImportantInteger&gt;1&lt;/SomeVeryImportantInteger&gt;&lt;/ArbitrarilyNamedXmlItemElement&gt;\n &lt;ArbitrarilyNamedXmlItemElement&gt;&lt;SomeVeryImportantInteger&gt;2&lt;/SomeVeryImportantInteger&gt;&lt;/ArbitrarilyNamedXmlItemElement&gt;\n &lt;ArbitrarilyNamedXmlItemElement&gt;&lt;SomeVeryImportantInteger&gt;3&lt;/SomeVeryImportantInteger&gt;&lt;/ArbitrarilyNamedXmlItemElement&gt;\n&lt;/ArbitrarilyNamedXmlListElement&gt;\n'\n\n DECLARE @tblEntityList TABLE(\n SomeVeryImportantInteger int\n )\n\n INSERT @tblEntityList(SomeVeryImportantInteger)\n SELECT \n XmlItem.query('//SomeVeryImportantInteger[1]').value('.','int') as SomeVeryImportantInteger\n FROM\n [dbo].[tvfShredGetOneColumnedTableOfXmlItems] (@xmlEntityList)\n\n\n</code>\n</pre>\n\n<p>by utilizing the scalar-valued function</p>\n\n<pre>\n<code>\n/* Example Inputs */\n/*\nDECLARE @xmlListFormat xml\nSET @xmlListFormat =\n '\n &lt;ArbitrarilyNamedXmlListElement&gt;\n &lt;ArbitrarilyNamedXmlItemElement&gt;004421UB7&lt;/ArbitrarilyNamedXmlItemElement&gt;\n &lt;ArbitrarilyNamedXmlItemElement&gt;59020UH24&lt;/ArbitrarilyNamedXmlItemElement&gt;\n &lt;ArbitrarilyNamedXmlItemElement&gt;542514NA8&lt;/ArbitrarilyNamedXmlItemElement&gt;\n &lt;/ArbitrarilyNamedXmlListElement&gt;\n '\ndeclare @tblResults TABLE \n(\n XmlItem xml\n)\n\n*/\n\n-- =============================================\n-- Author: 6eorge Jetson\n-- Create date: 01/02/3003\n-- Description: Shreds a list of XML items conforming to\n-- the expected generic @xmlListFormat\n-- =============================================\nCREATE FUNCTION [dbo].[tvfShredGetOneColumnedTableOfXmlItems] \n(\n -- Add the parameters for the function here\n @xmlListFormat xml\n)\nRETURNS \n@tblResults TABLE \n(\n -- Add the column definitions for the TABLE variable here\n XmlItem xml\n)\nAS\nBEGIN\n\n -- Fill the table variable with the rows for your result set\n INSERT @tblResults\n SELECT\n tblShredded.colXmlItem.query('.') as XmlItem\n FROM\n @xmlListFormat.nodes('/child::*/child::*') as tblShredded(colXmlItem)\n\n RETURN \nEND\n\n--SELECT * FROM @tblResults\n\n</code>\n</pre>\n" }, { "answer_id": 6405312, "author": "Tao", "author_id": 74296, "author_profile": "https://Stackoverflow.com/users/74296", "pm_score": 0, "selected": false, "text": "<p>In case this is useful to anyone else out there looking for a \"generic\" solution, I created a CLR procedure that can take an Xml fragment as above and \"shred\" it into a tabular resultset, without you providing any additional information about the names or types of the columns, or customizing your call in any way for the given Xml fragment:</p>\n\n<p><a href=\"http://architectshack.com/ClrXmlShredder.ashx\" rel=\"nofollow\">http://architectshack.com/ClrXmlShredder.ashx</a></p>\n\n<p>There are of course some restrictions (the xml must be \"tabular\" in nature like this sample, the first row needs to contain all the elements/columns that will be supported, etc) - but I do hope it's a few steps ahead of what's available built-in.</p>\n" }, { "answer_id": 33355283, "author": "JohnLBevan", "author_id": 361842, "author_profile": "https://Stackoverflow.com/users/361842", "pm_score": 0, "selected": false, "text": "<p>Here's an alternate solution:</p>\n\n<pre><code>;with cte as \n(\n select id, name, addresses, addresses.value('count(/address/city)','int') cnt\n from @demo\n)\n, cte2 as\n(\n select id, name, addresses, addresses.value('((/address/city)[sql:column(\"cnt\")])[1]','nvarchar(256)') city, cnt-1 idx \n from cte \n where cnt &gt; 0\n\n union all\n\n select cte.id, cte.name, cte.addresses, cte.addresses.value('((/address/city)[sql:column(\"cte2.idx\")])[1]','nvarchar(256)'), cte2.idx-1 \n from cte2 \n inner join cte on cte.id = cte2.id and cte2.idx &gt; 0\n)\nselect id, name, city \nfrom cte2 \norder by id, city\n</code></pre>\n\n<p>FYI: I've posted another version of this SQL on the code review site here: <a href=\"https://codereview.stackexchange.com/questions/108805/select-field-in-an-xml-column-where-both-xml-and-table-contain-multiple-matches\">https://codereview.stackexchange.com/questions/108805/select-field-in-an-xml-column-where-both-xml-and-table-contain-multiple-matches</a></p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3645/" ]
I am selecting from a table that has an XML column using T-SQL. I would like to select a certain type of node and have a row created for each one. For instance, suppose I am selecting from a *people* table. This table has an XML column for *addresses*. The XML is formated similar to the following: ``` <address> <street>Street 1</street> <city>City 1</city> <state>State 1</state> <zipcode>Zip Code 1</zipcode> </address> <address> <street>Street 2</street> <city>City 2</city> <state>State 2</state> <zipcode>Zip Code 2</zipcode> </address> ``` How can I get results like this: **Name**         **City**         **State** Joe Baker   Seattle      WA Joe Baker   Tacoma     WA Fred Jones  Vancouver BC
Here is your solution: ``` /* TEST TABLE */ DECLARE @PEOPLE AS TABLE ([Name] VARCHAR(20), [Address] XML ) INSERT INTO @PEOPLE SELECT 'Joel', '<address> <street>Street 1</street> <city>City 1</city> <state>State 1</state> <zipcode>Zip Code 1</zipcode> </address> <address> <street>Street 2</street> <city>City 2</city> <state>State 2</state> <zipcode>Zip Code 2</zipcode> </address>' UNION ALL SELECT 'Kim', '<address> <street>Street 3</street> <city>City 3</city> <state>State 3</state> <zipcode>Zip Code 3</zipcode> </address>' SELECT * FROM @PEOPLE -- BUILD XML DECLARE @x XML SELECT @x = ( SELECT [Name] , [Address].query(' for $a in //address return <address street="{$a/street}" city="{$a/city}" state="{$a/state}" zipcode="{$a/zipcode}" /> ') FROM @PEOPLE AS people FOR XML AUTO ) -- RESULTS SELECT [Name] = T.Item.value('../@Name', 'varchar(20)'), street = T.Item.value('@street' , 'varchar(20)'), city = T.Item.value('@city' , 'varchar(20)'), state = T.Item.value('@state' , 'varchar(20)'), zipcode = T.Item.value('@zipcode', 'varchar(20)') FROM @x.nodes('//people/address') AS T(Item) /* OUTPUT*/ Name | street | city | state | zipcode ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Joel | Street 1 | City 1 | State 1 | Zip Code 1 Joel | Street 2 | City 2 | State 2 | Zip Code 2 Kim | Street 3 | City 3 | State 3 | Zip Code 3 ```
192,413
<p>I have a RichTextBox where I need to update the Text property frequently, but when I do so the RichTextBox "blinks" annoyingly as it refreshes all throughout a method call.</p> <p>I was hoping to find an easy way to temporarily suppress the screen refresh until my method is done, but the only thing I've found on the web is to override the WndProc method. I've employed this approach, but with some difficulty and side effects, and it makes debugging harder, too. It just seems like there's got to be a better way of doing this. Can someone point me to a better solution?</p>
[ { "answer_id": 192423, "author": "BKimmel", "author_id": 13776, "author_profile": "https://Stackoverflow.com/users/13776", "pm_score": -1, "selected": false, "text": "<p>Try this out:</p>\n\n<pre><code>myRichTextBox.SuspendLayout();\nDoStuff();\nmyRichTextBox.ResumeLayout();\n</code></pre>\n" }, { "answer_id": 192437, "author": "Howler", "author_id": 2871, "author_profile": "https://Stackoverflow.com/users/2871", "pm_score": 0, "selected": false, "text": "<p>Could you just store the Text into a string, do your manipulations on the string, and at the end of the method, store it back into the Text property?</p>\n" }, { "answer_id": 192461, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 2, "selected": false, "text": "<p>Found here: <a href=\"http://bytes.com/forum/thread276845.html\" rel=\"nofollow noreferrer\">http://bytes.com/forum/thread276845.html</a></p>\n\n<blockquote>\n <p>I ended up sending a WM_SETREDRAW via SendMessage to disable then reenable\n followed by an Invalidate() after I finished updating. That seemed to work.</p>\n</blockquote>\n\n<p>I've never tried this method. I have written an application with a RTB that has syntax highlighting and used the following in the RTB class:</p>\n\n<pre><code>protected override void WndProc(ref Message m)\n{\n if (m.Msg == paint)\n {\n if (!highlighting)\n {\n base.WndProc(ref m); // if we decided to paint this control, just call the RichTextBox WndProc\n }\n else\n {\n m.Result = IntPtr.Zero; // not painting, must set this to IntPtr.Zero if not painting otherwise serious problems.\n }\n }\n else\n {\n base.WndProc(ref m); // message other than paint, just do what you normally do.\n }\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 192499, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>I would suggest looking at <a href=\"http://msdn.microsoft.com/en-us/library/ms534869.aspx\" rel=\"nofollow noreferrer\">LockWindowUpdate</a></p>\n\n<pre>\n<code>\n[DllImport(\"user32.dll\", EntryPoint=\"LockWindowUpdate\", SetLastError=true,\nExactSpelling=true, CharSet=CharSet.Auto,\nCallingConvention=CallingConvention.StdCall)]\n</code></pre>\n" }, { "answer_id": 194500, "author": "JohnnyM", "author_id": 27109, "author_profile": "https://Stackoverflow.com/users/27109", "pm_score": 4, "selected": false, "text": "<p>I asked the original question, and the answer that worked best for me was BoltBait's use of SendMessage() with WM_SETREDRAW. It seems to have fewer side effects than the use of the WndProc method, and in my application performs twice as fast as LockWindowUpdate. </p>\n\n<p>Within my extended RichTextBox class, I just added these two methods, and I call them whenever I need to stop restart repainting while I'm doing some processing. If I were wanting to do this from outside of the RichTextBox class, I think it would work by just replacing \"this\" with the reference to your RichTextBox instance.</p>\n\n<pre><code> private void StopRepaint()\n {\n // Stop redrawing:\n SendMessage(this.Handle, WM_SETREDRAW, 0, IntPtr.Zero);\n // Stop sending of events:\n eventMask = SendMessage(this.Handle, EM_GETEVENTMASK, 0, IntPtr.Zero);\n }\n\n private void StartRepaint()\n {\n // turn on events\n SendMessage(this.Handle, EM_SETEVENTMASK, 0, eventMask);\n // turn on redrawing\n SendMessage(this.Handle, WM_SETREDRAW, 1, IntPtr.Zero);\n // this forces a repaint, which for some reason is necessary in some cases.\n this.Invalidate();\n }\n</code></pre>\n" }, { "answer_id": 26088349, "author": "puch4tek", "author_id": 1456212, "author_profile": "https://Stackoverflow.com/users/1456212", "pm_score": 4, "selected": false, "text": "<p>Here is complete and working example:</p>\n\n<pre><code> private const int WM_USER = 0x0400;\n private const int EM_SETEVENTMASK = (WM_USER + 69);\n private const int WM_SETREDRAW = 0x0b;\n private IntPtr OldEventMask; \n\n [DllImport(\"user32.dll\", CharSet=CharSet.Auto)]\n private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);\n\n public void BeginUpdate()\n {\n SendMessage(this.Handle, WM_SETREDRAW, IntPtr.Zero, IntPtr.Zero);\n OldEventMask = (IntPtr)SendMessage(this.Handle, EM_SETEVENTMASK, IntPtr.Zero, IntPtr.Zero);\n } \n\n public void EndUpdate()\n {\n SendMessage(this.Handle, WM_SETREDRAW, (IntPtr)1, IntPtr.Zero);\n SendMessage(this.Handle, EM_SETEVENTMASK, IntPtr.Zero, OldEventMask);\n }\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a RichTextBox where I need to update the Text property frequently, but when I do so the RichTextBox "blinks" annoyingly as it refreshes all throughout a method call. I was hoping to find an easy way to temporarily suppress the screen refresh until my method is done, but the only thing I've found on the web is to override the WndProc method. I've employed this approach, but with some difficulty and side effects, and it makes debugging harder, too. It just seems like there's got to be a better way of doing this. Can someone point me to a better solution?
I asked the original question, and the answer that worked best for me was BoltBait's use of SendMessage() with WM\_SETREDRAW. It seems to have fewer side effects than the use of the WndProc method, and in my application performs twice as fast as LockWindowUpdate. Within my extended RichTextBox class, I just added these two methods, and I call them whenever I need to stop restart repainting while I'm doing some processing. If I were wanting to do this from outside of the RichTextBox class, I think it would work by just replacing "this" with the reference to your RichTextBox instance. ``` private void StopRepaint() { // Stop redrawing: SendMessage(this.Handle, WM_SETREDRAW, 0, IntPtr.Zero); // Stop sending of events: eventMask = SendMessage(this.Handle, EM_GETEVENTMASK, 0, IntPtr.Zero); } private void StartRepaint() { // turn on events SendMessage(this.Handle, EM_SETEVENTMASK, 0, eventMask); // turn on redrawing SendMessage(this.Handle, WM_SETREDRAW, 1, IntPtr.Zero); // this forces a repaint, which for some reason is necessary in some cases. this.Invalidate(); } ```
192,432
<p>I've tried to use the new <a href="http://groovy.codehaus.org/Grape" rel="noreferrer">Groovy Grape</a> capability in Groovy 1.6-beta-2 but I get an error message;</p> <pre><code>unable to resolve class com.jidesoft.swing.JideSplitButton </code></pre> <p>from the Groovy Console (/opt/groovy/groovy-1.6-beta-2/bin/groovyConsole) when running the stock example;</p> <pre><code>import com.jidesoft.swing.JideSplitButton @Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)') public class TestClassAnnotation { public static String testMethod () { return JideSplitButton.class.name } } </code></pre> <p>I even tried running the grape command line tool to ensure the library is imported. Like this;</p> <pre><code> $ /opt/groovy/groovy-1.6-beta-2/bin/grape install com.jidesoft jide-oss </code></pre> <p>which does install the library just fine. How do I get the code to run/compile correctly from the groovyConsole?</p>
[ { "answer_id": 194403, "author": "shemnon", "author_id": 8020, "author_profile": "https://Stackoverflow.com/users/8020", "pm_score": 4, "selected": true, "text": "<p>There is still some kinks in working out the startup/kill switch routine. For Beta-2 do this in it's own script first:</p>\n\n<pre><code>groovy.grape.Grape.initGrape()\n</code></pre>\n\n<p>Another issue you will run into deals with the joys of using an unbounded upper range. Jide-oss from 2.3.0 onward has been compiling their code to Java 6 bytecodes, so you will need to either run the console in Java 6 (which is what you would want to do for Swing anyway) or set an upper limit on the ranges, like so</p>\n\n<pre><code>import com.jidesoft.swing.JideSplitButton\n\n@Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,2.3.0)')\npublic class TestClassAnnotation {\n public static String testMethod () {\n return JideSplitButton.class.name\n }\n}\n\nnew TestClassAnnotation().testMethod()\n</code></pre>\n" }, { "answer_id": 194439, "author": "Bob Herrmann", "author_id": 6580, "author_profile": "https://Stackoverflow.com/users/6580", "pm_score": 2, "selected": false, "text": "<p>Ok. Seems like this a short working demo (running from the groovyConsole)</p>\n\n<pre><code>groovy.grape.Grape.initGrape()\n@Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,2.3.0)')\npublic class UsedToExposeAnnotationToComplier {}\ncom.jidesoft.swing.JideSplitButton.class.name\n</code></pre>\n\n<p>When run it produces</p>\n\n<p>Result: \"com.jidesoft.swing.JideSplitButton\"</p>\n\n<p>Very cool!!</p>\n" }, { "answer_id": 473172, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Different example using latest RC-2 (note: Grab annotates createEmptyInts):</p>\n\n<pre><code>// create and use a primitive array\nimport org.apache.commons.collections.primitives.ArrayIntList\n\n@Grab(group='commons-primitives', module='commons-primitives', version='1.0')\ndef createEmptyInts() { new ArrayIntList() }\n\ndef ints = createEmptyInts()\nints.add(0, 42)\nassert ints.size() == 1\nassert ints.get(0) == 42\n</code></pre>\n" }, { "answer_id": 498908, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Another example (note: Grab annotates getHtml):</p>\n\n<pre><code>// find the PDF links in the Java 1.5.0 documentation\n@Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='0.9.7')\ndef getHtml() {\n def parser = new XmlParser(new org.ccil.cowan.tagsoup.Parser())\n parser.parse(\"http://java.sun.com/j2se/1.5.0/download-pdf.html\")\n}\nhtml.body.'**'[email protected](~/.*\\.pdf/).each{ println it }\n</code></pre>\n" }, { "answer_id": 498942, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Another example (note: <code>Grab</code> annotates <code>getFruit</code>):</p>\n\n<pre><code>// Google Collections example\nimport com.google.common.collect.HashBiMap\n@Grab(group='com.google.code.google-collections', module='google-collect', version='snapshot-20080530')\ndef getFruit() { [grape:'purple', lemon:'yellow', orange:'orange'] as HashBiMap }\nassert fruit.inverse().yellow == 'lemon'\n</code></pre>\n" }, { "answer_id": 1628995, "author": "Jim Morris", "author_id": 197091, "author_profile": "https://Stackoverflow.com/users/197091", "pm_score": 3, "selected": false, "text": "<p>I finally got it working for Groovy Shell (1.6.5, JVM: 1.6.0_13). This should be documented better.</p>\n\n<p>First at the command line...</p>\n\n<blockquote>\n <p>grape install org.codehaus.groovy.modules.http-builder http-builder 0.5.0-RC2</p>\n</blockquote>\n\n<p>Then in groovysh...</p>\n\n<pre><code>groovy:000&gt; import groovy.grape.Grape\ngroovy:000&gt; Grape.grab(group:'org.codehaus.groovy.modules.http-builder', module:'http-builder', version:'0.5.0-RC2')\ngroovy:000&gt; def http= new groovyx.net.http.HTTPBuilder('http://rovio')\n===&gt; groovyx.net.http.HTTPBuilder@91520\n</code></pre>\n\n<p>The @grab is better used in a file than the shell.</p>\n" }, { "answer_id": 20473287, "author": "Daniel Ribeiro", "author_id": 1790092, "author_profile": "https://Stackoverflow.com/users/1790092", "pm_score": 0, "selected": false, "text": "<p>The import statement must appear <b>after</b> the grabs.\n<br/>Ps. At least <b>one import</b> statement must exists after the grabs</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)')\nimport com.jidesoft.swing.JideSplitButton\npublic class TestClassAnnotation {\n public static String testMethod () {\n return JideSplitButton.class.name\n }\n}\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6580/" ]
I've tried to use the new [Groovy Grape](http://groovy.codehaus.org/Grape) capability in Groovy 1.6-beta-2 but I get an error message; ``` unable to resolve class com.jidesoft.swing.JideSplitButton ``` from the Groovy Console (/opt/groovy/groovy-1.6-beta-2/bin/groovyConsole) when running the stock example; ``` import com.jidesoft.swing.JideSplitButton @Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,)') public class TestClassAnnotation { public static String testMethod () { return JideSplitButton.class.name } } ``` I even tried running the grape command line tool to ensure the library is imported. Like this; ``` $ /opt/groovy/groovy-1.6-beta-2/bin/grape install com.jidesoft jide-oss ``` which does install the library just fine. How do I get the code to run/compile correctly from the groovyConsole?
There is still some kinks in working out the startup/kill switch routine. For Beta-2 do this in it's own script first: ``` groovy.grape.Grape.initGrape() ``` Another issue you will run into deals with the joys of using an unbounded upper range. Jide-oss from 2.3.0 onward has been compiling their code to Java 6 bytecodes, so you will need to either run the console in Java 6 (which is what you would want to do for Swing anyway) or set an upper limit on the ranges, like so ``` import com.jidesoft.swing.JideSplitButton @Grab(group='com.jidesoft', module='jide-oss', version='[2.2.1,2.3.0)') public class TestClassAnnotation { public static String testMethod () { return JideSplitButton.class.name } } new TestClassAnnotation().testMethod() ```
192,454
<p>I have TortoiseSVN set up to use KDiff3 as the conflict resolution tool (I find it shows more information useful to the merge than the built-in TortoiseMerge does).</p> <p>When I open a file with Tortoise's "Edit Conflicts" command it shows me the three files and I have to select "Merge->Merge Current File" manually. The problem is that KDiff3 saves the result to <code>source_file.working</code> instead of to <code>source_file</code>. So without doing a Save As, the real file with the conflict doesn't get modified. Is there a way around doing this manual Save As every time?</p> <p>I know this isn't strictly a programming question but it's about an ancillary process common enough to programmers that it should be useful here. I couldn't find the answer to this elsewhere.</p>
[ { "answer_id": 192558, "author": "Owen", "author_id": 4790, "author_profile": "https://Stackoverflow.com/users/4790", "pm_score": 3, "selected": false, "text": "<p>Turns out I just needed a more specific command line. I had it set simply to the path to <code>kdiff3.exe</code>, and hoped the default arguments passed from TortoiseSVN would be enough. Not so. Here's the one needed (the key being the <code>-o</code> argument):</p>\n\n<pre><code>C:\\Program Files\\KDiff3\\kdiff3.exe %base %theirs %mine -o %merged\n</code></pre>\n" }, { "answer_id": 200657, "author": "Milen A. Radev", "author_id": 15785, "author_profile": "https://Stackoverflow.com/users/15785", "pm_score": 6, "selected": true, "text": "<p>Mine is a bit longer:</p>\n\n<pre><code>\"C:\\Program Files\\KDiff3\\kdiff3.exe\" %base %mine %theirs -o %merged --L1 Base --L2 Mine --L3 Theirs\n</code></pre>\n" }, { "answer_id": 4963975, "author": "Carlos", "author_id": 612268, "author_profile": "https://Stackoverflow.com/users/612268", "pm_score": 3, "selected": false, "text": "<p>In case there's someone else like me, let me point out his is done in TortoiseSVN->Settings->Diff Viewer. I installed KDiff3 in Windows with Tortoise already installed and it got configured automatically. It took me some time to figure out where this needed to be done.</p>\n" }, { "answer_id": 54222275, "author": "lennoxGER", "author_id": 10607694, "author_profile": "https://Stackoverflow.com/users/10607694", "pm_score": 0, "selected": false, "text": "<p>I had the same problem, but could solve it without any command line:\nwhen I clicked \"Edit Conflicts\" kdiff3 opend up. \nAfter solving the conflict I simply clicked \"save\" and closed the kdiff3 window. \nAfter the window was closed I switched back to the SVN \"resolve confict\"- window and clicked resolved.\nThen the next conflict popped up.... </p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4790/" ]
I have TortoiseSVN set up to use KDiff3 as the conflict resolution tool (I find it shows more information useful to the merge than the built-in TortoiseMerge does). When I open a file with Tortoise's "Edit Conflicts" command it shows me the three files and I have to select "Merge->Merge Current File" manually. The problem is that KDiff3 saves the result to `source_file.working` instead of to `source_file`. So without doing a Save As, the real file with the conflict doesn't get modified. Is there a way around doing this manual Save As every time? I know this isn't strictly a programming question but it's about an ancillary process common enough to programmers that it should be useful here. I couldn't find the answer to this elsewhere.
Mine is a bit longer: ``` "C:\Program Files\KDiff3\kdiff3.exe" %base %mine %theirs -o %merged --L1 Base --L2 Mine --L3 Theirs ```
192,456
<p>I would like to set the log file name for a log4j and log4net appender to have the current date. We are doing Daily rollovers but the current log file does not have a date. The log file name format would be </p> <pre><code>logname.2008-10-10.log </code></pre> <p>Anyone know the best way for me to do this?</p> <p>edit: I forgot to mention that we would want to do this in log4net as well. Plus any solution would need to be usable in JBoss.</p>
[ { "answer_id": 192548, "author": "gedevan", "author_id": 20225, "author_profile": "https://Stackoverflow.com/users/20225", "pm_score": 7, "selected": true, "text": "<p>DailyRollingFileAppender is what you exactly searching for.</p>\n\n<pre><code>&lt;appender name=\"roll\" class=\"org.apache.log4j.DailyRollingFileAppender\"&gt;\n &lt;param name=\"File\" value=\"application.log\" /&gt;\n &lt;param name=\"DatePattern\" value=\".yyyy-MM-dd\" /&gt;\n &lt;layout class=\"org.apache.log4j.PatternLayout\"&gt; \n &lt;param name=\"ConversionPattern\" \n value=\"%d{yyyy-MMM-dd HH:mm:ss,SSS} [%t] %c %x%n %-5p %m%n\"/&gt;\n &lt;/layout&gt;\n &lt;/appender&gt;\n</code></pre>\n" }, { "answer_id": 192632, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 4, "selected": false, "text": "<p>I'm 99% sure that RollingFileAppender/DailyRollingFileAppender, while it gives you the date-rolling functionality you want, doesn't have any way to specify that the current log file should use the <code>DatePattern</code> as well.</p>\n\n<p>You might just be able to simply subclass RollingFileAppender (or DailyRollingFileAppender, I forget which is which in log4net) and modify the naming logic.</p>\n" }, { "answer_id": 192744, "author": "James A. N. Stauffer", "author_id": 6770, "author_profile": "https://Stackoverflow.com/users/6770", "pm_score": 4, "selected": false, "text": "<p>I have created an appender that will do that. <a href=\"http://stauffer.james.googlepages.com/DateFormatFileAppender.java\" rel=\"noreferrer\">http://stauffer.james.googlepages.com/DateFormatFileAppender.java</a></p>\n\n<pre><code>/*\n * Copyright (C) The Apache Software Foundation. All rights reserved.\n *\n * This software is published under the terms of the Apache Software\n * License version 1.1, a copy of which has been included with this\n * distribution in the LICENSE.txt file. */\n\npackage sps.log.log4j;\n\nimport java.io.IOException;\nimport java.io.File;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\nimport org.apache.log4j.*;\nimport org.apache.log4j.helpers.LogLog;\nimport org.apache.log4j.spi.LoggingEvent;\n\n/**\n * DateFormatFileAppender is a log4j Appender and extends \n * {@link FileAppender} so each log is \n * named based on a date format defined in the File property.\n *\n * Sample File: 'logs/'yyyy/MM-MMM/dd-EEE/HH-mm-ss-S'.log'\n * Makes a file like: logs/2004/04-Apr/13-Tue/09-45-15-937.log\n * @author James Stauffer\n */\npublic class DateFormatFileAppender extends FileAppender {\n\n /**\n * The default constructor does nothing.\n */\n public DateFormatFileAppender() {\n }\n\n /**\n * Instantiate a &lt;code&gt;DailyRollingFileAppender&lt;/code&gt; and open the\n * file designated by &lt;code&gt;filename&lt;/code&gt;. The opened filename will\n * become the ouput destination for this appender.\n */\n public DateFormatFileAppender (Layout layout, String filename) throws IOException {\n super(layout, filename, true);\n }\n\n private String fileBackup;//Saves the file pattern\n private boolean separate = false;\n\n public void setFile(String file) {\n super.setFile(file);\n this.fileBackup = getFile();\n }\n\n /**\n * If true each LoggingEvent causes that file to close and open.\n * This is useful when the file is a pattern that would often\n * produce a different filename.\n */\n public void setSeparate(boolean separate) {\n this.separate = separate;\n }\n\n protected void subAppend(LoggingEvent event) {\n if(separate) {\n try {//First reset the file so each new log gets a new file.\n setFile(getFile(), getAppend(), getBufferedIO(), getBufferSize());\n } catch(IOException e) {\n LogLog.error(\"Unable to reset fileName.\");\n }\n }\n super.subAppend(event);\n }\n\n\n public\n synchronized\n void setFile(String fileName, boolean append, boolean bufferedIO, int bufferSize)\n throws IOException {\n SimpleDateFormat sdf = new SimpleDateFormat(fileBackup);\n String actualFileName = sdf.format(new Date());\n makeDirs(actualFileName);\n super.setFile(actualFileName, append, bufferedIO, bufferSize);\n }\n\n /**\n * Ensures that all of the directories for the given path exist.\n * Anything after the last / or \\ is assumed to be a filename.\n */\n private void makeDirs (String path) {\n int indexSlash = path.lastIndexOf(\"/\");\n int indexBackSlash = path.lastIndexOf(\"\\\\\");\n int index = Math.max(indexSlash, indexBackSlash);\n if(index &gt; 0) {\n String dirs = path.substring(0, index);\n// LogLog.debug(\"Making \" + dirs);\n File dir = new File(dirs);\n if(!dir.exists()) {\n boolean success = dir.mkdirs();\n if(!success) {\n LogLog.error(\"Unable to create directories for \" + dirs);\n }\n }\n }\n }\n\n}\n</code></pre>\n" }, { "answer_id": 773871, "author": "Lars Corneliussen", "author_id": 11562, "author_profile": "https://Stackoverflow.com/users/11562", "pm_score": 4, "selected": false, "text": "<p>I don't know if it is possible in Java, but in .NET the property StaticLogFileName on RollingFileAppender gives you what you want. The default is true.</p>\n\n<pre><code>&lt;staticLogFileName value=\"false\"/&gt;\n</code></pre>\n\n<p>Full config: </p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;appender name=\"DefaultFileAppender\" type=\"log4net.Appender.RollingFileAppender\"&gt;\n &lt;file value=\"application\"/&gt;\n &lt;staticLogFileName value=\"false\"/&gt;\n &lt;appendToFile value=\"true\" /&gt;\n &lt;rollingStyle value=\"Date\" /&gt;\n &lt;datePattern value=\"yyyy-MM-dd&amp;quot;.log&amp;quot;\" /&gt;\n &lt;layout type=\"log4net.Layout.PatternLayout\"&gt;\n &lt;conversionPattern value=\"%date [%thread] %-5level %logger [%property{NDC}] - %message%newline\" /&gt;\n &lt;/layout&gt;\n&lt;/appender&gt;\n</code></pre>\n\n<p><code>&amp;quot;.log&amp;quot;</code> is for not letting the dateformat recognice the global date pattern 'g' in log.</p>\n" }, { "answer_id": 8888867, "author": "shinds", "author_id": 990216, "author_profile": "https://Stackoverflow.com/users/990216", "pm_score": 6, "selected": false, "text": "<p>Using log4j.properties file, and including <a href=\"http://logging.apache.org/log4j/extras/\" rel=\"noreferrer\">apache-log4j-extras</a> 1.1 in my POM with log4j 1.2.16</p>\n\n<pre><code>log4j.appender.LOGFILE=org.apache.log4j.rolling.RollingFileAppender\nlog4j.appender.LOGFILE.RollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy\nlog4j.appender.LOGFILE.RollingPolicy.FileNamePattern=/logs/application_%d{yyyy-MM-dd}.log\n</code></pre>\n" }, { "answer_id": 11226717, "author": "codder", "author_id": 1485653, "author_profile": "https://Stackoverflow.com/users/1485653", "pm_score": 2, "selected": false, "text": "<p>this example will be creating logger for each minute, if you want to change for each day change the <code>DatePattern</code> value.</p>\n\n<pre><code>&lt;appender name=\"ASYNC\" class=\"org.apache.log4j.DailyRollingFileAppender\"&gt;\n &lt;param name=\"File\" value=\"./applogs/logger.log\" /&gt;\n &lt;param name=\"Append\" value=\"true\" /&gt;\n &lt;param name=\"Threshold\" value=\"debug\" /&gt;\n &lt;appendToFile value=\"true\" /&gt;\n &lt;param name=\"DatePattern\" value=\"'.'yyyy_MM_dd_HH_mm\"/&gt;\n &lt;rollingPolicy class=\"org.apache.log4j.rolling.TimeBasedRollingPolicy\"&gt;\n &lt;param name=\"fileNamePattern\" value=\"./applogs/logger_%d{ddMMMyyyy HH:mm:ss}.log\"/&gt;\n &lt;param name=\"rollOver\" value=\"TRUE\"/&gt;\n &lt;/rollingPolicy&gt;\n &lt;layout class=\"org.apache.log4j.PatternLayout\"&gt;\n &lt;param name=\"ConversionPattern\" value=\"%d{ddMMMyyyy HH:mm:ss,SSS}^[%X{l4j_mdc_key}]^[%c{1}]^ %-5p %m%n\" /&gt;\n &lt;/layout&gt;\n&lt;/appender&gt;\n&lt;root&gt;\n &lt;level value=\"info\" /&gt;\n &lt;appender-ref ref=\"ASYNC\" /&gt;\n&lt;/root&gt;\n</code></pre>\n" }, { "answer_id": 15009009, "author": "romeara", "author_id": 1128981, "author_profile": "https://Stackoverflow.com/users/1128981", "pm_score": 2, "selected": false, "text": "<p>As a response to the two answers which mention DailyRollingFileAppender (sorry, I don't have enough rep to comment on them directly, and I think this needs to be mentioned), I would warn that unfortunately the developers of that class have documented that it exhibits synchronization and data loss, and recommend that alternatives should be pursued for new deployments.</p>\n\n<p><a href=\"http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/DailyRollingFileAppender.html\" rel=\"nofollow\">DailyRollingFileAppender JavaDoc</a></p>\n" }, { "answer_id": 21250314, "author": "SANN3", "author_id": 1173495, "author_profile": "https://Stackoverflow.com/users/1173495", "pm_score": 2, "selected": false, "text": "<p>You can set <a href=\"http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/FileAppender.html\" rel=\"nofollow\">FileAppender</a> dynamically</p>\n\n<pre><code>SimpleLayout layout = new SimpleLayout(); \nFileAppender appender = new FileAppender(layout,\"logname.\"+new Date().toLocaleString(),false);\nlogger.addAppender(appender); \n</code></pre>\n" }, { "answer_id": 51557735, "author": "rpajaziti", "author_id": 3657024, "author_profile": "https://Stackoverflow.com/users/3657024", "pm_score": 0, "selected": false, "text": "<p>Even if you use <code>DailyRollingFileAppender</code> like @gedevan suggested, you will still get <code>logname.log.2008-10-10</code> (After a day, because the previous day log will get archived and the date will be concatenated to it's filename).</p>\n<p>So if you want <em>.log</em> at the end, you'll have to do it like this on the <code>DatePattern</code>:</p>\n<p><code>log4j.appender.file.DatePattern='.'yyyy-MM-dd-HH-mm'.log'</code></p>\n" }, { "answer_id": 67695369, "author": "john ktejik", "author_id": 396483, "author_profile": "https://Stackoverflow.com/users/396483", "pm_score": 0, "selected": false, "text": "<p>You can do it programmatically like so:</p>\n<pre><code> String dateFile = LocalDate.now().toString() + &quot;.log&quot;;\n Enumeration enm = Logger.getRootLogger().getAllAppenders();\n Appender appender = null;\n while(enm.hasMoreElements()){\n appender = (Appender)enm.nextElement();\n String c = appender.getClass().toString();\n if(c.contains(&quot;FileAppender&quot;)){\n String f = ((FileAppender)appender).getFile();\n ((FileAppender)appender).setFile(f+dateFile);\n System.out.println(&quot;From:&quot;+f+&quot; to:&quot;+dateFile);\n }\n }\n</code></pre>\n" }, { "answer_id": 72253926, "author": "jimmybow", "author_id": 19124264, "author_profile": "https://Stackoverflow.com/users/19124264", "pm_score": 1, "selected": false, "text": "<p>just use TimeBasedRollingPolicy and don't use param name=&quot;File&quot;</p>\n<pre><code> &lt;appender name=&quot;pdi-execution-appender&quot; class=&quot;org.apache.log4j.rolling.RollingFileAppender&quot;&gt; \n &lt;!-- The active file to log to; this example is for Pentaho Server.--&gt;\n &lt;param name=&quot;Append&quot; value=&quot;true&quot; /&gt;\n &lt;param name=&quot;Threshold&quot; value=&quot;INFO&quot;/&gt;\n &lt;rollingPolicy class=&quot;org.apache.log4j.rolling.TimeBasedRollingPolicy&quot;&gt;\n &lt;!-- See javadoc for TimeBasedRollingPolicy --&gt;\n &lt;param name=&quot;FileNamePattern&quot; value=&quot;logs/ETL-LogFile.%d{yyyyMMdd}.log&quot; /&gt;\n &lt;/rollingPolicy&gt;\n &lt;layout class=&quot;org.apache.log4j.PatternLayout&quot;&gt;\n &lt;param name=&quot;ConversionPattern&quot; value='%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p [%t] %m'/&gt;\n &lt;/layout&gt;\n &lt;/appender&gt;\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/387361/" ]
I would like to set the log file name for a log4j and log4net appender to have the current date. We are doing Daily rollovers but the current log file does not have a date. The log file name format would be ``` logname.2008-10-10.log ``` Anyone know the best way for me to do this? edit: I forgot to mention that we would want to do this in log4net as well. Plus any solution would need to be usable in JBoss.
DailyRollingFileAppender is what you exactly searching for. ``` <appender name="roll" class="org.apache.log4j.DailyRollingFileAppender"> <param name="File" value="application.log" /> <param name="DatePattern" value=".yyyy-MM-dd" /> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d{yyyy-MMM-dd HH:mm:ss,SSS} [%t] %c %x%n %-5p %m%n"/> </layout> </appender> ```
192,539
<p>I have a .NET application that processes around 300,000 records in a batch import, and it takes a few seconds per record so I would like to parallelize this. In the following code, what's the difference between <code>ProcessWithAnsycDelegates()</code> and <code>ProcessWithThreadPool()</code>?</p> <pre><code>public class ResultNotification { public EventHandler event Success; public EventHandler event Fail; internal void Notify(bool sucess) {if (success) Success(); else Fail();} } public static class Processor { public ResultNotification ProcessWithAnsycDelegates(Record record) { var r = new ResultNotification(); Func&lt;Record,bool&gt; processRecord=new RecordProcessor().ProcessRecord; processRecord.BeginInvoke ( record ,ar =&gt; result.Notify(processRecord.EndInvoke(ar)) ,null); return r; } public ResultNotification ProcessWithThreadPool(Record r) { var r = new ResultNotification(); var rp = new RecordProcessor(); ThreadPool.QueueWorkUserItem(_=&gt;result.Notify(rp.ProcessRecord(r))); return r; } } </code></pre>
[ { "answer_id": 192580, "author": "chadmyers", "author_id": 10862, "author_profile": "https://Stackoverflow.com/users/10862", "pm_score": 4, "selected": true, "text": "<p>In this case, not a lot as they both use the threadpool under the hood. I'd say that the <code>QueueUserWorkItem()</code> is easier to read and see what's going on vs. <code>BeginInvoke()</code>.</p>\n<p>This link may help. It's older information, but still mostly applicable:\n<a href=\"https://jonskeet.uk/csharp/threads/threadpool.html\" rel=\"nofollow noreferrer\">https://jonskeet.uk/csharp/threads/threadpool.html</a></p>\n" }, { "answer_id": 194648, "author": "Thomas Bratt", "author_id": 15985, "author_profile": "https://Stackoverflow.com/users/15985", "pm_score": 3, "selected": false, "text": "<p>The literal answer to the question is that both use the threadpool, so the difference is not much if performance is the only consideration.</p>\n\n<p>If the question is really about getting the best performance, then it may help to know that using the threadpool does have issues. These include:</p>\n\n<ul>\n<li>Lock contention on the work queue</li>\n<li>Excessive context switching. If you have 2 CPUs and a sequence of work items then 25 threads don't really help. Better to have 2 threads, one for each CPU</li>\n</ul>\n\n<p>It might be worth investigating the TPL and PLINQ:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-gb/magazine/cc163329.aspx\" rel=\"nofollow noreferrer\">Parallel LINQ Running Queries On Multi-Core Processors</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-gb/magazine/cc163340.aspx\" rel=\"nofollow noreferrer\">Parallel Performance Optimize Managed Code For Multi-Core Machines</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-gb/magazine/cc817396.aspx\" rel=\"nofollow noreferrer\">Improved Support For Parallelism In The Next Version Of Visual Studio</a></li>\n</ul>\n\n<p>One example they give of the TPL in use is:</p>\n\n<pre><code>for (int i = 0; i &lt; 100; i++) { \n a[i] = a[i]*a[i]; \n}\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>Parallel.For(0, 100, delegate(int i) { \n a[i] = a[i]*a[i]; \n});\n</code></pre>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659/" ]
I have a .NET application that processes around 300,000 records in a batch import, and it takes a few seconds per record so I would like to parallelize this. In the following code, what's the difference between `ProcessWithAnsycDelegates()` and `ProcessWithThreadPool()`? ``` public class ResultNotification { public EventHandler event Success; public EventHandler event Fail; internal void Notify(bool sucess) {if (success) Success(); else Fail();} } public static class Processor { public ResultNotification ProcessWithAnsycDelegates(Record record) { var r = new ResultNotification(); Func<Record,bool> processRecord=new RecordProcessor().ProcessRecord; processRecord.BeginInvoke ( record ,ar => result.Notify(processRecord.EndInvoke(ar)) ,null); return r; } public ResultNotification ProcessWithThreadPool(Record r) { var r = new ResultNotification(); var rp = new RecordProcessor(); ThreadPool.QueueWorkUserItem(_=>result.Notify(rp.ProcessRecord(r))); return r; } } ```
In this case, not a lot as they both use the threadpool under the hood. I'd say that the `QueueUserWorkItem()` is easier to read and see what's going on vs. `BeginInvoke()`. This link may help. It's older information, but still mostly applicable: <https://jonskeet.uk/csharp/threads/threadpool.html>
192,549
<p>I have a controller method that returns a list for a drop down that gets rendered in a partial, but depending on where the partial is being used, the RJS template needs to be different. Can I pass a parameter to the controller that will determine which RJS gets used?</p> <p>Here is the controller method, it is very simple:</p> <pre><code>def services respond_to do |format| format.js { @type = HospitalCriteria.find_by_id(params[:type_id]) @services = @type.children.all } end end </code></pre> <p>And here is the rjs template the gets rendered automatically</p> <pre><code>page.replace_html 'select_service', :partial =&gt; 'hospital/services' page.replace_html 'select_condition', :partial =&gt; 'hospital/conditions' page.replace_html 'select_procedure', :partial =&gt; 'hospital/procedures' page &lt;&lt; 'if ($("chosenType") != null) {' page.replace_html 'chosenType', @type.name page.replace_html 'chosenService', 'Selected Service' page.replace_html 'chosenCondition', 'Selected Condition' page.replace_html 'chosenProcedure', 'Selected Procedure' page &lt;&lt; '}' </code></pre>
[ { "answer_id": 192867, "author": "Mike Breen", "author_id": 22346, "author_profile": "https://Stackoverflow.com/users/22346", "pm_score": 1, "selected": false, "text": "<p>something like:</p>\n\n<pre><code>if params[:use_alternate]\n render :template =&gt; alternate.rjs and return\nend\n</code></pre>\n" }, { "answer_id": 192910, "author": "danpickett", "author_id": 21788, "author_profile": "https://Stackoverflow.com/users/21788", "pm_score": 2, "selected": false, "text": "<p>I like Mike's response, but something to think about here from a design perspective:</p>\n\n<p>It sounds to me like this should be in the view layer - if the action is semantically the same, but the presentation is different, perhaps having two different rjs partials and doing something like below is more compliant with MVC?</p>\n\n<pre><code>if params[:use_alternate]\n render :partial =&gt; \"case_1.rjs\"\nelse\n render :partial =&gt; \"case_2.rjs\"\nend\n</code></pre>\n" }, { "answer_id": 193209, "author": "RichH", "author_id": 16779, "author_profile": "https://Stackoverflow.com/users/16779", "pm_score": 0, "selected": false, "text": "<p>To keep things clean, I'd have two controller methods that render the two different RJSs. I'd then set @type and @services in a common protected method that the two controller methods call.</p>\n\n<p>In my mind you are asking for something different in each case so call a different controller method. Passing in a flag to change the way the method works is just a hack and won't scale well when you have 3, 4 or 5 places. Even though you'll generate more code, it will be easier to maintain.</p>\n" }, { "answer_id": 197094, "author": "JasonOng", "author_id": 6048, "author_profile": "https://Stackoverflow.com/users/6048", "pm_score": 3, "selected": true, "text": "<p>What about placing the conditional logic in <strong>one</strong> rjs template?</p>\n\n<pre><code># services.rjs\n\nif @type == \"your conditions\"\n # your rjs updates\nelse\n # your other rjs updates\nend\n</code></pre>\n\n<p>This gives you a cleaner controller and saves you the headache of maintaining multiple rjs templates.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1486/" ]
I have a controller method that returns a list for a drop down that gets rendered in a partial, but depending on where the partial is being used, the RJS template needs to be different. Can I pass a parameter to the controller that will determine which RJS gets used? Here is the controller method, it is very simple: ``` def services respond_to do |format| format.js { @type = HospitalCriteria.find_by_id(params[:type_id]) @services = @type.children.all } end end ``` And here is the rjs template the gets rendered automatically ``` page.replace_html 'select_service', :partial => 'hospital/services' page.replace_html 'select_condition', :partial => 'hospital/conditions' page.replace_html 'select_procedure', :partial => 'hospital/procedures' page << 'if ($("chosenType") != null) {' page.replace_html 'chosenType', @type.name page.replace_html 'chosenService', 'Selected Service' page.replace_html 'chosenCondition', 'Selected Condition' page.replace_html 'chosenProcedure', 'Selected Procedure' page << '}' ```
What about placing the conditional logic in **one** rjs template? ``` # services.rjs if @type == "your conditions" # your rjs updates else # your other rjs updates end ``` This gives you a cleaner controller and saves you the headache of maintaining multiple rjs templates.
192,553
<p>I am currently in the process of making a new ASP.net MVC website, and find myself using Html.Encode all over the place, which is good practice, but gets pretty messy. I think a good way to clean this up would be if I could overload an operator to automatically do Html encoding. </p> <p>Previously:</p> <pre><code>&lt;%= Html.Encode( ViewData['username'] ) %&gt; </code></pre> <p>Would be equivalent to:</p> <pre><code>&lt;%=h ViewData['username'] %&gt; </code></pre> <p>Anyone have any ideas how I could do this, maybe using an extension method or something?</p>
[ { "answer_id": 192564, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": -1, "selected": false, "text": "<p><strong>NOTE: This is an ugly and untested hack, I don't think I'd ever do this</strong></p>\n\n<pre><code>public static String h (this System.Object o, System.Object viewData)\n{\n return Html.Encode(viewData);\n}\n</code></pre>\n\n<p>I'm not sure what type ViewData is, so I used Object here, it would be best to actually change the type in the real code.</p>\n\n<p>this works by hanging an extension method off System.Object, so it is always available on all types...ugly, but it may do the job:</p>\n\n<pre><code>&lt;%=h(ViewData['username']) %&gt;\n</code></pre>\n" }, { "answer_id": 192594, "author": "Wyatt", "author_id": 26626, "author_profile": "https://Stackoverflow.com/users/26626", "pm_score": 4, "selected": true, "text": "<p>It's not so clean as an operator overload, but I used the following extension method:</p>\n\n<pre><code>public static string Safe(this string sz)\n{\n return HttpUtility.HtmlEncode(sz);\n}\n</code></pre>\n\n<p>So in my aspx id do:</p>\n\n<pre><code>&lt;%= this.ViewData[\"username\"].Safe() %&gt;\n</code></pre>\n\n<p>Tacking the extra method onto the end of the expression just looks prettier to me than sending the value through a function.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24841/" ]
I am currently in the process of making a new ASP.net MVC website, and find myself using Html.Encode all over the place, which is good practice, but gets pretty messy. I think a good way to clean this up would be if I could overload an operator to automatically do Html encoding. Previously: ``` <%= Html.Encode( ViewData['username'] ) %> ``` Would be equivalent to: ``` <%=h ViewData['username'] %> ``` Anyone have any ideas how I could do this, maybe using an extension method or something?
It's not so clean as an operator overload, but I used the following extension method: ``` public static string Safe(this string sz) { return HttpUtility.HtmlEncode(sz); } ``` So in my aspx id do: ``` <%= this.ViewData["username"].Safe() %> ``` Tacking the extra method onto the end of the expression just looks prettier to me than sending the value through a function.
192,570
<p>The project I'm working on uses a window.onerror event handler to report user problems. I've noticed a single user that just cannot seem to load the Google Analytics script. Our site doesn't see a lot of traffic so I'm not sure how widespread this is, but so far it seems to just effect one user. </p> <p>His user agent is: "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.17) Gecko/20080829 Firefox/2.0.0.17".<br> The error message Firefox gives is: "Error loading script".</p> <p><strong>Additional note</strong>: The site references several other javascript files. However, the analytics reference is the only one to an external domain and the only script reference at the bottom of the page, just before the closing body tag.</p> <p>Has anybody else run across this, or have any idea what could be the issue? Thanks!</p>
[ { "answer_id": 192581, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 2, "selected": false, "text": "<p>This is a rather random guess, but I wonder if the user is using an add-on like NoScript to control script execution and is not allowing scripts from Google Analytics to run. I know this is possible because it's what I do :) I don't know if that would show up as the error you're seeing.</p>\n" }, { "answer_id": 252125, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I have a site with over 80 pages, all that employ JavaScript error trapping. My site serves well over 2000 pages a day and I get about ten \"Error loading script\" scripting errors each day from Firefox browsers. It is beginning to really annoy me and I am becoming convinced that it is a problem in Firefox.</p>\n\n<p>I can discount the NOSCRIPT suggestion because the script loads in the head of my pages where there are no NOSCRIPT tags.</p>\n\n<p>I can discount the 'external domain' suggestion because I have two sites that suffer this problem and in both cases the JS library files are located on the sites own server.</p>\n\n<p>I have carefully checked every library file and web page using JavaScript Lint and I have discovered scripting errors and questionable scripting techniques. All these problems have been corrected but this has not provided any sort of cure to the \"Error loading script\" problem.</p>\n\n<p>My pages do load several JavaScript library files that do not have this problem and the only difference is the size of the files. Most of the files are under 5KB but the problem file is 17KB.</p>\n\n<p>Could the size of the library file be the problem?</p>\n\n<p>Aagh!</p>\n" }, { "answer_id": 6702056, "author": "bxjx", "author_id": 373903, "author_profile": "https://Stackoverflow.com/users/373903", "pm_score": 0, "selected": false, "text": "<p>I'm sure this is long resolved.. but to anyone who stumbles across this page: this error is triggered by firefox when an external script fails to load (it's easy to find the code that triggers this in the source code). We were catching these errors on our site and it turned out that we were returning 404s for the script, so I suggest looking at your logs as one possibly source of this error.</p>\n" }, { "answer_id": 7686057, "author": "Karl Bartel", "author_id": 114926, "author_profile": "https://Stackoverflow.com/users/114926", "pm_score": 3, "selected": false, "text": "<p>This problem occurs when leaving a page in Firefox before all scripts have finished loading. So I assume that it is safe to ignore the error.</p>\n\n<p>You don't see this error in the Firefox error console, but you can make it visible by binding an alert to the window.onerror event. Then you will be able to see the alert box for a small amount of time and get the following error in the error console:</p>\n\n<pre><code>[11:35:57.428] uncaught exception: [Exception... \"prompt aborted by user\" nsresult: \"0x80040111 (NS_ERROR_NOT_AVAILABLE)\" location: \"JS frame :: resource:///components/nsPrompter.js :: openTabPrompt :: line 462\" data: no]\n</code></pre>\n\n<p>I'm using the following check to ignore this error in my onerror handler:</p>\n\n<pre><code>if (navigator.userAgent.search('Firefox') != -1 &amp;&amp; message === 'Error loading script') {\n // Firefox generates this error when leaving a page before all scripts have finished loading\n return;\n}\n</code></pre>\n" }, { "answer_id": 11197924, "author": "Stefaan", "author_id": 1303398, "author_profile": "https://Stackoverflow.com/users/1303398", "pm_score": 1, "selected": false, "text": "<p>We had the same issue and after examining our CDN logs, we discovered that Firefox triggers the onerror event when a script returns with HTTP status \"304 Not Modified\", so a cache hit. In fact, Firefox (tested with Firefox 12 at time of this writing), seems to trigger onerror event for all HTTP statuses except '200 Ok'. Other browsers behaved differently in our experiment: Chrome (19) triggered onerror only on '407 Proxy Authentication Required' and Opera (12) on 100, 101, 204, 4xx and 5xx.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1423/" ]
The project I'm working on uses a window.onerror event handler to report user problems. I've noticed a single user that just cannot seem to load the Google Analytics script. Our site doesn't see a lot of traffic so I'm not sure how widespread this is, but so far it seems to just effect one user. His user agent is: "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.17) Gecko/20080829 Firefox/2.0.0.17". The error message Firefox gives is: "Error loading script". **Additional note**: The site references several other javascript files. However, the analytics reference is the only one to an external domain and the only script reference at the bottom of the page, just before the closing body tag. Has anybody else run across this, or have any idea what could be the issue? Thanks!
This problem occurs when leaving a page in Firefox before all scripts have finished loading. So I assume that it is safe to ignore the error. You don't see this error in the Firefox error console, but you can make it visible by binding an alert to the window.onerror event. Then you will be able to see the alert box for a small amount of time and get the following error in the error console: ``` [11:35:57.428] uncaught exception: [Exception... "prompt aborted by user" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: resource:///components/nsPrompter.js :: openTabPrompt :: line 462" data: no] ``` I'm using the following check to ignore this error in my onerror handler: ``` if (navigator.userAgent.search('Firefox') != -1 && message === 'Error loading script') { // Firefox generates this error when leaving a page before all scripts have finished loading return; } ```
192,575
<p>How do I transfer the users of a vBulletin forum to a new installation of IceBB?</p>
[ { "answer_id": 192581, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 2, "selected": false, "text": "<p>This is a rather random guess, but I wonder if the user is using an add-on like NoScript to control script execution and is not allowing scripts from Google Analytics to run. I know this is possible because it's what I do :) I don't know if that would show up as the error you're seeing.</p>\n" }, { "answer_id": 252125, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I have a site with over 80 pages, all that employ JavaScript error trapping. My site serves well over 2000 pages a day and I get about ten \"Error loading script\" scripting errors each day from Firefox browsers. It is beginning to really annoy me and I am becoming convinced that it is a problem in Firefox.</p>\n\n<p>I can discount the NOSCRIPT suggestion because the script loads in the head of my pages where there are no NOSCRIPT tags.</p>\n\n<p>I can discount the 'external domain' suggestion because I have two sites that suffer this problem and in both cases the JS library files are located on the sites own server.</p>\n\n<p>I have carefully checked every library file and web page using JavaScript Lint and I have discovered scripting errors and questionable scripting techniques. All these problems have been corrected but this has not provided any sort of cure to the \"Error loading script\" problem.</p>\n\n<p>My pages do load several JavaScript library files that do not have this problem and the only difference is the size of the files. Most of the files are under 5KB but the problem file is 17KB.</p>\n\n<p>Could the size of the library file be the problem?</p>\n\n<p>Aagh!</p>\n" }, { "answer_id": 6702056, "author": "bxjx", "author_id": 373903, "author_profile": "https://Stackoverflow.com/users/373903", "pm_score": 0, "selected": false, "text": "<p>I'm sure this is long resolved.. but to anyone who stumbles across this page: this error is triggered by firefox when an external script fails to load (it's easy to find the code that triggers this in the source code). We were catching these errors on our site and it turned out that we were returning 404s for the script, so I suggest looking at your logs as one possibly source of this error.</p>\n" }, { "answer_id": 7686057, "author": "Karl Bartel", "author_id": 114926, "author_profile": "https://Stackoverflow.com/users/114926", "pm_score": 3, "selected": false, "text": "<p>This problem occurs when leaving a page in Firefox before all scripts have finished loading. So I assume that it is safe to ignore the error.</p>\n\n<p>You don't see this error in the Firefox error console, but you can make it visible by binding an alert to the window.onerror event. Then you will be able to see the alert box for a small amount of time and get the following error in the error console:</p>\n\n<pre><code>[11:35:57.428] uncaught exception: [Exception... \"prompt aborted by user\" nsresult: \"0x80040111 (NS_ERROR_NOT_AVAILABLE)\" location: \"JS frame :: resource:///components/nsPrompter.js :: openTabPrompt :: line 462\" data: no]\n</code></pre>\n\n<p>I'm using the following check to ignore this error in my onerror handler:</p>\n\n<pre><code>if (navigator.userAgent.search('Firefox') != -1 &amp;&amp; message === 'Error loading script') {\n // Firefox generates this error when leaving a page before all scripts have finished loading\n return;\n}\n</code></pre>\n" }, { "answer_id": 11197924, "author": "Stefaan", "author_id": 1303398, "author_profile": "https://Stackoverflow.com/users/1303398", "pm_score": 1, "selected": false, "text": "<p>We had the same issue and after examining our CDN logs, we discovered that Firefox triggers the onerror event when a script returns with HTTP status \"304 Not Modified\", so a cache hit. In fact, Firefox (tested with Firefox 12 at time of this writing), seems to trigger onerror event for all HTTP statuses except '200 Ok'. Other browsers behaved differently in our experiment: Chrome (19) triggered onerror only on '407 Proxy Authentication Required' and Opera (12) on 100, 101, 204, 4xx and 5xx.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5509/" ]
How do I transfer the users of a vBulletin forum to a new installation of IceBB?
This problem occurs when leaving a page in Firefox before all scripts have finished loading. So I assume that it is safe to ignore the error. You don't see this error in the Firefox error console, but you can make it visible by binding an alert to the window.onerror event. Then you will be able to see the alert box for a small amount of time and get the following error in the error console: ``` [11:35:57.428] uncaught exception: [Exception... "prompt aborted by user" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: resource:///components/nsPrompter.js :: openTabPrompt :: line 462" data: no] ``` I'm using the following check to ignore this error in my onerror handler: ``` if (navigator.userAgent.search('Firefox') != -1 && message === 'Error loading script') { // Firefox generates this error when leaving a page before all scripts have finished loading return; } ```
192,584
<p>I have a listbox that is databound to a Collection of objects. The listbox is configured to display an identifier property of each object. I would like to show a tooltip with information specific to the item within the listbox that is being hovered over rather than one tooltip for the listbox as a whole.</p> <p>I am working within WinForms and thanks to some helpful blog posts put together a pretty nice solution, which I wanted to share.</p> <p>I'd be interested in seeing if there's any other elegant solutions to this problem, or how this may be done in WPF.</p>
[ { "answer_id": 192654, "author": "Michael Lang", "author_id": 19452, "author_profile": "https://Stackoverflow.com/users/19452", "pm_score": 5, "selected": true, "text": "<p>There are two main sub-problems one must solve in order to solve this problem:</p>\n\n<ol>\n<li>Determine which item is being hovered over</li>\n<li>Get the MouseHover event to fire when the user has hovered over one item, then moved the cursor within the listbox and hovered over another item.</li>\n</ol>\n\n<p>The first problem is rather simple to solve. By calling a method like the following within your handler for MouseHover, you can determine which item is being hovered over:</p>\n\n<pre><code>private ITypeOfObjectsBoundToListBox DetermineHoveredItem()\n{\n Point screenPosition = ListBox.MousePosition;\n Point listBoxClientAreaPosition = listBox.PointToClient(screenPosition);\n\n int hoveredIndex = listBox.IndexFromPoint(listBoxClientAreaPosition);\n if (hoveredIndex != -1)\n {\n return listBox.Items[hoveredIndex] as ITypeOfObjectsBoundToListBox;\n }\n else\n {\n return null;\n }\n}\n</code></pre>\n\n<p>Then use the returned value to set the tool-tip as needed.</p>\n\n<p>The second problem is that normally the MouseHover event isn't fired again until the cursor has left the client area of the control and then come back.</p>\n\n<p>You can get around this by wrapping the <code>TrackMouseEvent</code> Win32API call.<br>\nIn the following code, the <code>ResetMouseHover</code> method wraps the API call to get the desired effect: reset the underlying timer that controls when the hover event is fired.</p>\n\n<pre><code>public static class MouseInput\n{\n // TME_HOVER\n // The caller wants hover notification. Notification is delivered as a \n // WM_MOUSEHOVER message. If the caller requests hover tracking while \n // hover tracking is already active, the hover timer will be reset.\n\n private const int TME_HOVER = 0x1;\n\n private struct TRACKMOUSEEVENT\n {\n // Size of the structure - calculated in the constructor\n public int cbSize;\n\n // value that we'll set to specify we want to start over Mouse Hover and get\n // notification when the hover has happened\n public int dwFlags;\n\n // Handle to what's interested in the event\n public IntPtr hwndTrack;\n\n // How long it takes for a hover to occur\n public int dwHoverTime;\n\n // Setting things up specifically for a simple reset\n public TRACKMOUSEEVENT(IntPtr hWnd)\n {\n this.cbSize = Marshal.SizeOf(typeof(TRACKMOUSEEVENT));\n this.hwndTrack = hWnd;\n this.dwHoverTime = SystemInformation.MouseHoverTime;\n this.dwFlags = TME_HOVER;\n }\n }\n\n // Declaration of the Win32API function\n [DllImport(\"user32\")]\n private static extern bool TrackMouseEvent(ref TRACKMOUSEEVENT lpEventTrack);\n\n public static void ResetMouseHover(IntPtr windowTrackingMouseHandle)\n {\n // Set up the parameter collection for the API call so that the appropriate\n // control fires the event\n TRACKMOUSEEVENT parameterBag = new TRACKMOUSEEVENT(windowTrackingMouseHandle);\n\n // The actual API call\n TrackMouseEvent(ref parameterBag);\n }\n}\n</code></pre>\n\n<p>With the wrapper in place, you can simply call <code>ResetMouseHover(listBox.Handle)</code> at the end of your MouseHover handler and the hover event will fire again even when the cursor stays within the control's bounds.</p>\n\n<p>I'm sure this approach, sticking all the code in the MouseHover handler must result in more MouseHover events firing than are really necessary, but it'll get the job done. Any improvements are more than welcome.</p>\n" }, { "answer_id": 853369, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I think the best option, since your databinding your listbox to objects, would be to use \na datatemplate. So you could do something like this:</p>\n\n<pre><code>&lt;ListBox Width=\"400\" Margin=\"10\" \n ItemsSource=\"{Binding Source={StaticResource myTodoList}}\"&gt;\n &lt;ListBox.ItemTemplate&gt;\n &lt;DataTemplate&gt;\n &lt;TextBlock Text=\"{Binding Path=TaskName}\" \n ToolTipService.ToolTip=\"{Binding Path=TaskName}\"/&gt;\n &lt;/DataTemplate&gt;\n &lt;/ListBox.ItemTemplate&gt;\n&lt;/ListBox&gt;\n</code></pre>\n\n<p>Of course you'd replace the ItemsSource binding with whatever your binding source is, and the binding Path parts with whatever public property of the objects in the list you actually want to display.\nMore details available on <a href=\"http://msdn.microsoft.com/en-us/library/ms742521.aspx\" rel=\"nofollow noreferrer\">msdn</a></p>\n" }, { "answer_id": 1275983, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Using title attribute, we can set tool tip for each list items in a list box.</p>\n\n<p>Loop this for all the items in a list box.</p>\n\n<pre><code>ListItem li = new ListItem(\"text\",\"key\");\nli.Attributes.Add(\"title\",\"tool tip text\");\n</code></pre>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 3029107, "author": "BSalita", "author_id": 317797, "author_profile": "https://Stackoverflow.com/users/317797", "pm_score": 0, "selected": false, "text": "<p>Here is a Style that creates a group of RadioButtons by using a ListBox. All is bound for MVVM-ing. MyClass contains two String properties: MyName and MyToolTip. This will display the list of RadioButtons including proper ToolTip-ing. Of interest to this thread is the Setter for ToolTip near bottom making this an all Xaml solution.</p>\n\n<p>Example usage:</p>\n\n<p>ListBox Style=\"{StaticResource radioListBox}\" ItemsSource=\"{Binding MyClass}\" SelectedValue=\"{Binding SelectedMyClass}\"/></p>\n\n<p>Style:</p>\n\n<pre><code> &lt;Style x:Key=\"radioListBox\" TargetType=\"ListBox\" BasedOn=\"{StaticResource {x:Type ListBox}}\"&gt;\n &lt;Setter Property=\"BorderThickness\" Value=\"0\" /&gt;\n &lt;Setter Property=\"Margin\" Value=\"5\" /&gt;\n &lt;Setter Property=\"Background\" Value=\"{x:Null}\" /&gt;\n &lt;Setter Property=\"ItemContainerStyle\"&gt;\n &lt;Setter.Value&gt;\n &lt;Style TargetType=\"ListBoxItem\" BasedOn=\"{StaticResource {x:Type ListBoxItem}}\"&gt;\n &lt;Setter Property=\"Template\"&gt;\n &lt;Setter.Value&gt;\n &lt;ControlTemplate TargetType=\"ListBoxItem\"&gt;\n &lt;Grid Background=\"Transparent\"&gt;\n &lt;RadioButton Focusable=\"False\" IsHitTestVisible=\"False\" IsChecked=\"{TemplateBinding IsSelected}\" Content=\"{Binding MyName}\"/&gt;\n &lt;/Grid&gt;\n &lt;/ControlTemplate&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n &lt;Setter Property=\"ToolTip\" Value=\"{Binding MyToolTip}\" /&gt;\n &lt;/Style&gt;\n &lt;/Setter.Value&gt;\n &lt;/Setter&gt;\n&lt;/Style&gt;\n</code></pre>\n" }, { "answer_id": 6848465, "author": "Michael", "author_id": 865925, "author_profile": "https://Stackoverflow.com/users/865925", "pm_score": 4, "selected": false, "text": "<p>Using the MouseMove event, you can keep track of the index of the item that the mouse is over and store this in a variable that keeps its value between MouseMoves. Every time MouseMove is triggered, it checks to see if the index has changed. If so, it disables the tooltip, changes the tooltip text for this control, then re-activates it.</p>\n\n<p>Below is an example where a single property of a Car class is shown in a ListBox, but then full information is shown when hovering over any one row. To make this example work, all you need is a ListBox called lstCars with a MouseMove event and a ToolTip text component called tt1 on your WinForm.</p>\n\n<p>Definition of the car class:</p>\n\n<pre><code> class Car\n {\n // Main properties:\n public string Model { get; set; }\n public string Make { get; set; }\n public int InsuranceGroup { get; set; }\n public string OwnerName { get; set; }\n // Read only property combining all the other informaiton:\n public string Info { get { return string.Format(\"{0} {1}\\nOwner: {2}\\nInsurance group: {3}\", Make, Model, OwnerName, InsuranceGroup); } }\n }\n</code></pre>\n\n<p>Form load event:</p>\n\n<pre><code> private void Form1_Load(object sender, System.EventArgs e)\n {\n // Set up a list of cars:\n List&lt;Car&gt; allCars = new List&lt;Car&gt;();\n allCars.Add(new Car { Make = \"Toyota\", Model = \"Yaris\", InsuranceGroup = 6, OwnerName = \"Joe Bloggs\" });\n allCars.Add(new Car { Make = \"Mercedes\", Model = \"AMG\", InsuranceGroup = 50, OwnerName = \"Mr Rich\" });\n allCars.Add(new Car { Make = \"Ford\", Model = \"Escort\", InsuranceGroup = 10, OwnerName = \"Fred Normal\" });\n\n // Attach the list of cars to the ListBox:\n lstCars.DataSource = allCars;\n lstCars.DisplayMember = \"Model\";\n }\n</code></pre>\n\n<p>The tooltip code (including creating the class level variable called hoveredIndex):</p>\n\n<pre><code> // Class variable to keep track of which row is currently selected:\n int hoveredIndex = -1;\n\n private void lstCars_MouseMove(object sender, MouseEventArgs e)\n {\n // See which row is currently under the mouse:\n int newHoveredIndex = lstCars.IndexFromPoint(e.Location);\n\n // If the row has changed since last moving the mouse:\n if (hoveredIndex != newHoveredIndex)\n {\n // Change the variable for the next time we move the mouse:\n hoveredIndex = newHoveredIndex;\n\n // If over a row showing data (rather than blank space):\n if (hoveredIndex &gt; -1)\n {\n //Set tooltip text for the row now under the mouse:\n tt1.Active = false;\n tt1.SetToolTip(lstCars, ((Car)lstCars.Items[hoveredIndex]).Info);\n tt1.Active = true;\n }\n }\n }\n</code></pre>\n" }, { "answer_id": 26881134, "author": "Satheesh ponugoti", "author_id": 4242026, "author_profile": "https://Stackoverflow.com/users/4242026", "pm_score": 0, "selected": false, "text": "<p>Using <code>onmouseover</code> you can iterate through each item of the list and can show the <code>ToolTip</code></p>\n\n<pre><code>onmouseover=\"doTooltipProd(event,'');\n\nfunction doTooltipProd(e,tipObj)\n{\n\n Tooltip.init();\n if ( typeof Tooltip == \"undefined\" || !Tooltip.ready ) {\n return;\n }\n mCounter = 1;\n for (m=1;m&lt;=document.getElementById('lobProductId').length;m++) {\n\n var mCurrent = document.getElementById('lobProductId').options[m];\n if(mCurrent != null &amp;&amp; mCurrent != \"null\") {\n if (mCurrent.selected) {\n mText = mCurrent.text;\n Tooltip.show(e, mText);\n }\n } \n } \n}\n</code></pre>\n" }, { "answer_id": 47886511, "author": "Shalom", "author_id": 9117042, "author_profile": "https://Stackoverflow.com/users/9117042", "pm_score": 2, "selected": false, "text": "<p>You can use this simple code that uses the onMouseMove event of ListBox in WinForms:</p>\n\n<pre><code>private void ListBoxOnMouseMove(object sender, MouseEventArgs mouseEventArgs)\n{\n var listbox = sender as ListBox;\n if (listbox == null) return;\n\n // set tool tip for listbox\n var strTip = string.Empty;\n var index = listbox.IndexFromPoint(mouseEventArgs.Location);\n\n if ((index &gt;= 0) &amp;&amp; (index &lt; listbox.Items.Count))\n strTip = listbox.Items[index].ToString();\n\n if (_toolTip.GetToolTip(listbox) != strTip)\n {\n _toolTip.SetToolTip(listbox, strTip);\n }\n}\n</code></pre>\n\n<p>Of course you will have to init the ToolTip object in the constructor or some init function:</p>\n\n<pre><code>_toolTip = new ToolTip\n{\n AutoPopDelay = 5000,\n InitialDelay = 1000,\n ReshowDelay = 500,\n ShowAlways = true\n};\n</code></pre>\n\n<p>Enjoy!</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19452/" ]
I have a listbox that is databound to a Collection of objects. The listbox is configured to display an identifier property of each object. I would like to show a tooltip with information specific to the item within the listbox that is being hovered over rather than one tooltip for the listbox as a whole. I am working within WinForms and thanks to some helpful blog posts put together a pretty nice solution, which I wanted to share. I'd be interested in seeing if there's any other elegant solutions to this problem, or how this may be done in WPF.
There are two main sub-problems one must solve in order to solve this problem: 1. Determine which item is being hovered over 2. Get the MouseHover event to fire when the user has hovered over one item, then moved the cursor within the listbox and hovered over another item. The first problem is rather simple to solve. By calling a method like the following within your handler for MouseHover, you can determine which item is being hovered over: ``` private ITypeOfObjectsBoundToListBox DetermineHoveredItem() { Point screenPosition = ListBox.MousePosition; Point listBoxClientAreaPosition = listBox.PointToClient(screenPosition); int hoveredIndex = listBox.IndexFromPoint(listBoxClientAreaPosition); if (hoveredIndex != -1) { return listBox.Items[hoveredIndex] as ITypeOfObjectsBoundToListBox; } else { return null; } } ``` Then use the returned value to set the tool-tip as needed. The second problem is that normally the MouseHover event isn't fired again until the cursor has left the client area of the control and then come back. You can get around this by wrapping the `TrackMouseEvent` Win32API call. In the following code, the `ResetMouseHover` method wraps the API call to get the desired effect: reset the underlying timer that controls when the hover event is fired. ``` public static class MouseInput { // TME_HOVER // The caller wants hover notification. Notification is delivered as a // WM_MOUSEHOVER message. If the caller requests hover tracking while // hover tracking is already active, the hover timer will be reset. private const int TME_HOVER = 0x1; private struct TRACKMOUSEEVENT { // Size of the structure - calculated in the constructor public int cbSize; // value that we'll set to specify we want to start over Mouse Hover and get // notification when the hover has happened public int dwFlags; // Handle to what's interested in the event public IntPtr hwndTrack; // How long it takes for a hover to occur public int dwHoverTime; // Setting things up specifically for a simple reset public TRACKMOUSEEVENT(IntPtr hWnd) { this.cbSize = Marshal.SizeOf(typeof(TRACKMOUSEEVENT)); this.hwndTrack = hWnd; this.dwHoverTime = SystemInformation.MouseHoverTime; this.dwFlags = TME_HOVER; } } // Declaration of the Win32API function [DllImport("user32")] private static extern bool TrackMouseEvent(ref TRACKMOUSEEVENT lpEventTrack); public static void ResetMouseHover(IntPtr windowTrackingMouseHandle) { // Set up the parameter collection for the API call so that the appropriate // control fires the event TRACKMOUSEEVENT parameterBag = new TRACKMOUSEEVENT(windowTrackingMouseHandle); // The actual API call TrackMouseEvent(ref parameterBag); } } ``` With the wrapper in place, you can simply call `ResetMouseHover(listBox.Handle)` at the end of your MouseHover handler and the hover event will fire again even when the cursor stays within the control's bounds. I'm sure this approach, sticking all the code in the MouseHover handler must result in more MouseHover events firing than are really necessary, but it'll get the job done. Any improvements are more than welcome.
192,628
<p>i've been tasked with re-organizing a pure HTML site into a CMS. if all goes well, the new site will eventually become the main URL, and the old domain will be phased out. the old domain has a decent enough page rank, and the company wishes to mitigate any loss of page rank for that. in looking over the options available, i've discovered a few things:</p> <ul> <li>it's better to use a 301 redirect when you're ready to make the switch (<a href="http://www.seroundtable.com/archives/007233.html" rel="nofollow noreferrer">source</a>).</li> <li>the current site does not have a sitemap, so adding one and submitting it may help their future page rank.</li> <li>i'll need to suggest to them that they contact people currently linking to them to update their links.</li> <li>the process for regaining an old page rank takes awhile, so plan on rebuilding links while we see if the new site is flexible enough to warrant switching over completely.</li> </ul> <p><strong>my question is</strong>: as a result of a move to a CMS driven site, the links to various pages will change to accommodate the new structure. will this be an issue for trying to maintain (or improve) the current page rank? what sort of methods are available to mitigate the issue of changing individual page URL's? <em>is there a preferable method beyond mapping individual pages to their new locations with 301 redirects? (the site has literally hundreds of pages, ugh...)</em></p> <pre><code>ex. http://domain.com/Messy_HTML_page_with_little_categorization.html -&gt; http://newdomain.com/nice/structured/pages.php </code></pre> <p>i realize this isn't strictly a programming question, however i felt the information could be useful to developers who are tasked with handling this sort of thing in addition to development of the site.</p> <p><strong>edit</strong>: additions in italics</p>
[ { "answer_id": 192679, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 4, "selected": true, "text": "<p>If you really truly want to ensure that page rank is not lost, you will want to replace the old content with something that performs a proper 301 redirect to the new location. With a 301 redirect the search spiders will know that the content is moved and the page rank typically carries over. It also helps external links.</p>\n\n<p>However, the down side is that after a certain period of time you just have to get rid of the old domains.</p>\n" }, { "answer_id": 192701, "author": "Eduardo Campañó", "author_id": 12091, "author_profile": "https://Stackoverflow.com/users/12091", "pm_score": 0, "selected": false, "text": "<p>You can make a handler for HTML files and map the old pages to the new structure with a 301 redirect.</p>\n" } ]
2008/10/10
[ "https://Stackoverflow.com/questions/192628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4853/" ]
i've been tasked with re-organizing a pure HTML site into a CMS. if all goes well, the new site will eventually become the main URL, and the old domain will be phased out. the old domain has a decent enough page rank, and the company wishes to mitigate any loss of page rank for that. in looking over the options available, i've discovered a few things: * it's better to use a 301 redirect when you're ready to make the switch ([source](http://www.seroundtable.com/archives/007233.html)). * the current site does not have a sitemap, so adding one and submitting it may help their future page rank. * i'll need to suggest to them that they contact people currently linking to them to update their links. * the process for regaining an old page rank takes awhile, so plan on rebuilding links while we see if the new site is flexible enough to warrant switching over completely. **my question is**: as a result of a move to a CMS driven site, the links to various pages will change to accommodate the new structure. will this be an issue for trying to maintain (or improve) the current page rank? what sort of methods are available to mitigate the issue of changing individual page URL's? *is there a preferable method beyond mapping individual pages to their new locations with 301 redirects? (the site has literally hundreds of pages, ugh...)* ``` ex. http://domain.com/Messy_HTML_page_with_little_categorization.html -> http://newdomain.com/nice/structured/pages.php ``` i realize this isn't strictly a programming question, however i felt the information could be useful to developers who are tasked with handling this sort of thing in addition to development of the site. **edit**: additions in italics
If you really truly want to ensure that page rank is not lost, you will want to replace the old content with something that performs a proper 301 redirect to the new location. With a 301 redirect the search spiders will know that the content is moved and the page rank typically carries over. It also helps external links. However, the down side is that after a certain period of time you just have to get rid of the old domains.