qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
218,911
<p>I have the classical table with expandable and collapsible records that if expanded show several subrecords (as new records in the same parent table, not some child div/child table). I am also using tablesorter and absolutely love it.</p> <p>The problem is that tablesorter isn't keeping expanded child records next to the parent records. It sorts them as if they were top level. So each time the table gets sorted by a column the child rows end up all over the place and not where I want them.</p> <p>Does anyone know of a good extension to tablesorter or specific configuration that enables tablesorter to keep child rows grouped together with the parent row even after sorting? Or do I have to give up tablesorter in favor of some other API or start the ugly process of writing my own widget? Should I avoid the css-based approach of hiding individual rows of the table to represent collapse rows?</p>
[ { "answer_id": 222579, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 1, "selected": false, "text": "$(\"tbody tr[class^='parent']\", table).each(function() {\n $(this).after($(\"tbody tr[class^='child\"+$(this).attr(\"class\").substring(6)+\"']\", table));\n});\n" }, { "answer_id": 12690263, "author": "Mottie", "author_id": 145346, "author_profile": "https://Stackoverflow.com/users/145346", "pm_score": 4, "selected": false, "text": "ccsChildRow" }, { "answer_id": 56116010, "author": "Evan Gertis", "author_id": 3937811, "author_profile": "https://Stackoverflow.com/users/3937811", "pm_score": 0, "selected": false, "text": "function lfDisplayProductInformation(id){\n\n if($(`[rel=\"child-${id}\"]`).attr(\"hidden\") === 'hidden'){\n $(`[rel=\"child-${id}\"]`).removeAttr('hidden')\n }\n else if(!$(`[rel=\"child-${id}`).attr(\"hidden\")){\n $(`[rel=\"child-${id}\"]`).attr(\"hidden\", true)\n }\n\n}\n\n$(\".tablesort\")\n.tablesorter({\n theme: 'blue',\n showProcessing : true\n})\n\n// assign the sortStart event\n.bind(\"sortStart\",function(e, t) {\n $(\"tr[rel^='parent']\").each(function() {\n var parentRow = $(this); \n var tag = (parentRow.attr('rel')).split(\"-\")[1];\n var childRow = $(`tr[rel=\"child-${tag}\"]`)\n if(!childRow.attr(\"hidden\")){\n childRow.attr(\"hidden\", true)\n }\n });\n\n})\n\n.bind(\"sortEnd\",function(e, t) {\n $(\"tr[rel^='parent']\").each(function() {\n var parentRow = $(this); \n var tag = (parentRow.attr('rel')).split(\"-\")[1];\n var childRow = $(`tr[rel=\"child-${tag}\"]`)\n childRow\n parentRow.after(childRow);\n });\n})\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2204759/" ]
218,912
<p>Is there a command like <code>cat</code> in linux which can return a specified quantity of characters from a file?</p> <p>e.g., I have a text file like:</p> <pre><code>Hello world this is the second line this is the third line </code></pre> <p>And I want something that would return the first 5 characters, which would be "hello".</p> <p>thanks</p>
[ { "answer_id": 218940, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": 9, "selected": true, "text": "head head -c 100 file # returns the first 100 bytes in the file\n head tail tail -c 100 file # returns the last 100 bytes in the file\n head head -c 200 file | tail -c 100\n" }, { "answer_id": 219188, "author": "fcw", "author_id": 14577, "author_profile": "https://Stackoverflow.com/users/14577", "pm_score": 6, "selected": false, "text": "dd skip=1234 count=5 bs=1\n dd count=5 bs=1\n dd count=5 bs=1 if=filename\n dd count=5 bs=1 2>&-\n dd count=5 bs=1 2>/dev/null\n" }, { "answer_id": 1083897, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "head -Line_number file_name | tail -1 |cut -c Num_of_chars\n head -5 tst.txt | tail -1 |cut -c 5-8\n tail -1" }, { "answer_id": 38144668, "author": "rowanthorpe", "author_id": 1964463, "author_profile": "https://Stackoverflow.com/users/1964463", "pm_score": 2, "selected": false, "text": "cut -c tr sed head cut [a-z][A-Z] [:upper:][:lower:] $ printf 'Πού μπορώ να μάθω σανσκριτικά;\\n' | \\\n$ head -c 1 | \\\n$ sed -e 's/[A-Z]/[a-z]/g'\n[[unreadable binary mess, or nothing if the terminal filtered it]]\n cut tr $ printf 'Πού μπορώ να μάθω σανσκριτικά;\\n' | \\\n$ cut -c 1 | \\\n$ tr '[:upper:]' '[:lower:]'\nπ\n cut -c X X sed -E -e '1 s/^(.{X}).*$/\\1/' -e q head -n 1 | grep -E -o '^.{X}' dd sed dd tr sed -E -e 's/[[:upper:]]/\\L&/g" }, { "answer_id": 46121408, "author": "Brad Parks", "author_id": 26510, "author_profile": "https://Stackoverflow.com/users/26510", "pm_score": 0, "selected": false, "text": "dd #!/usr/bin/env bash\n\nfunction show_help()\n{\n IT=\"\nextracts characters X to Y from stdin or FILE\nusage: X Y {FILE}\n\ne.g. \n\n2 10 /tmp/it => extract chars 2-10 from /tmp/it\nEOF\n \"\n echo \"$IT\"\n exit\n}\n\nif [ \"$1\" == \"help\" ]\nthen\n show_help\nfi\nif [ -z \"$1\" ]\nthen\n show_help\nfi\n\nFROM=$1\nTO=$2\nCOUNT=`expr $TO - $FROM + 1`\n\nif [ -z \"$3\" ]\nthen\n dd skip=$FROM count=$COUNT bs=1 2>/dev/null\nelse\n dd skip=$FROM count=$COUNT bs=1 if=$3 2>/dev/null \nfi\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2011/" ]
218,935
<p>I'm pretty sure one would do this using the os.plock(op) function, but I have no idea how. Also, if there's a better way, I'd be grateful to find out. Code snippets are very welcome. </p>
[ { "answer_id": 218943, "author": "Dan Lenski", "author_id": 20789, "author_profile": "https://Stackoverflow.com/users/20789", "pm_score": 3, "selected": false, "text": "popen() subprocess" }, { "answer_id": 218970, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 2, "selected": false, "text": "os.popen* os subprocess" }, { "answer_id": 219048, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 5, "selected": true, "text": "p1 = Popen([\"dmesg\"], stdout=PIPE)\np2 = Popen([\"grep\", \"hda\"], stdin=p1.stdout, stdout=PIPE)\noutput = p2.communicate()[0]\n from multiprocessing import Process, Pipe\n\ndef f(conn):\n conn.send([42, None, 'hello'])\n conn.close()\n\nif __name__ == '__main__':\n parent_conn, child_conn = Pipe()\n p = Process(target=f, args=(child_conn,))\n p.start()\n print parent_conn.recv() # prints \"[42, None, 'hello']\"\n p.join()\n" }, { "answer_id": 219066, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 3, "selected": false, "text": "from multiprocessing import Process, Pipe\n\ndef f(conn):\n conn.send([42, None, 'hello'])\n conn.close()\n\nif __name__ == '__main__':\n parent_conn, child_conn = Pipe()\n p = Process(target=f, args=(child_conn,))\n p.start()\n print parent_conn.recv() # prints \"[42, None, 'hello']\"\n p.join()\n" }, { "answer_id": 50854805, "author": "David Fraser", "author_id": 120398, "author_profile": "https://Stackoverflow.com/users/120398", "pm_score": 1, "selected": false, "text": "subprocess popen import mmap, os, tempfile\nfd, tmpfile = tempfile.mkstemp()\nos.write(fd, '\\x00' * mmap.PAGESIZE)\nos.lseek(fd, 0, os.SEEK_SET)\nchild_pid = os.fork()\nif child_pid:\n buf = mmap.mmap(fd, mmap.PAGESIZE, mmap.MAP_SHARED, mmap.PROT_READ)\n os.waitpid(child_pid, 0)\n child_message = buf.readline()\n print(child_message)\n os.close(fd)\nelse:\n buf = mmap.mmap(fd, mmap.PAGESIZE, mmap.MAP_SHARED, mmap.PROT_WRITE)\n buf.write('testing\\n')\n os.close(fd)\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
218,969
<p>I have a problem perplexing me to no end. When I run the following query against an access database:</p> <pre><code>SELECT * FROM PreferredSpacer INNER JOIN SpacerThickness ON PreferredSpacer.SpacerTypeID = SpacerThickness.SpacerTypeID ORDER BY PreferredSpacer.UnitTypeID DESC </code></pre> <p>(UnitTypeID field is a text type)</p> <p>The results do not come out sorted as a normal person would expect. They are all over the place with respect to the UnitTypeID field (There are entries starting with 'W' between entries starting with 'C' and 'M'). If I remove the join and just try to order the records in the PreferredSpacer table (which contains the UnitTypeID field) I get my expected results, so I must assume the join has something to do with it.</p> <p>At the same time however, I honestly can't imagine a tool as ubiquitus as access could have such a glaring issue with a fairly basic query. If I am doing something wrong -- however -- I am not able to see what it could be.</p> <p>Any assistance would be greatly appreciated. Thanks.</p>
[ { "answer_id": 219061, "author": "David Hay", "author_id": 17784, "author_profile": "https://Stackoverflow.com/users/17784", "pm_score": 0, "selected": false, "text": "SELECT PreferredSpacer.UnitTypeID\nFROM PreferredSpacer, SpacerThickness\nWHERE PreferredSpacer.SpacerTypeID = SpacerThickness.SpacerTypeID\nORDER BY PreferredSpacer.UnitTypeID DESC\n CPATA\nCPATA\nCFRSA\nCFRSA\nCFRSA\nCFRSA\nCFRSA\nCFDOT\nCFDOT\nCFDOT\nCFDOT\nCFDOT\nCFDOAVSL\nCFDOAVSL\nCFDOAVSL\nCFDOAVSL\nCFDOAVSL\nCFDOA\nCFDOA\nCFDOA\nCFDOA\nCFDOA\nCFDIAVSL\nCFDIAVSL\nCFDIAVSL\nCFDIAVSL\nCFDIAVSL\nCFDIA\nCFDIA\nCFDIA\nCFDIA\nCFDIA\nCFDAT\nCFDAT\nCFDAT\nCFDAT\nCFDAT\nCBPATA\nCBPATA\nCBPATA\nCBPATA\nCBPATA\nCBFRSA\nCBFRSA\nCBFRSA\nCBFRSA\nCBFRSA\nCAPURE\nCAPURE\nCAPURE\nCAPURE\nCAPURE\nCADGU\nCADGU\nCADGU\nCADGU\nCADGU\nCADGS\nCADGS\nCADGS\nCADGS\nCADGS\nCOTR\nCOTR\nCOTR\nCOTR\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17784/" ]
218,987
<p>I want to use Sharepoint with python (C-Python)</p> <p>Has anyone tried this before ?</p>
[ { "answer_id": 222242, "author": "Blauohr", "author_id": 22176, "author_profile": "https://Stackoverflow.com/users/22176", "pm_score": 3, "selected": false, "text": "import sys\n\n# we use suds -> https://fedorahosted.org/suds\nfrom suds import WebFault\nfrom suds.client import *\nimport urllib2\n\n# my 2 url conf\n# url_sharepoint,url_NTLM_authproxy \nimport myconfig as my \n\n# build url\nwsdl = '_vti_bin/SiteData.asmx?WSDL'\nurl = '/'.join([my.url_sharepoint,wsdl])\n\n\n# we need a NTLM_auth_Proxy -> http://ntlmaps.sourceforge.net/\n# follow instruction and get proxy running\nproxy_handler = urllib2.ProxyHandler({'http': my.url_NTLM_authproxy })\nopener = urllib2.build_opener(proxy_handler)\n\nclient = SoapClient(url, {'opener' : opener})\n\nprint client.wsdl\n" }, { "answer_id": 5403203, "author": "somewhatoff", "author_id": 672720, "author_profile": "https://Stackoverflow.com/users/672720", "pm_score": 4, "selected": true, "text": "\nfrom suds import WebFault\nfrom suds.client import *\nfrom suds.transport.https import WindowsHttpAuthenticated\n\n\nuser = r'SERVER\\user'\npassword = \"yourpassword\"\nurl = \"http://sharepointserver/_vti_bin/SiteData.asmx?WSDL\"\n\n\nntlm = WindowsHttpAuthenticated(username = user, password = password)\nclient = Client(url, transport=ntlm)\n\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22176/" ]
218,988
<p>I am attempting to pass information from a task created within a workflow to its corresponding task form. Prior to the CreateTask activity, I create an SPWorkflowTaskProperties and fill it with the usual info (title, assigned-to, etc). I also add some elements to the ExtendedProperties property. However, those custom properties never make it into the Task.</p> <p>I've tried setting the property key to:</p> <ul> <li>the Guid of one of my task' content type's fields;</li> <li>the internal name of one of my task' content type's fields;</li> <li>an unrelated name (in the hopes of getting the info into the task's properties instead of its fields).</li> </ul> <p>Nothing works. The task, once created, contains only the built-in field values I have set. None of values I explicitly added to the extended properties show up.</p> <p>The (simplified) sequence of my activities is as follows:</p> <ul> <li>PrepareTask. This is a custom activity that contains the SPWorkflowTaskProperties </li> <li>CreateTask. The task properties are bound to the one in the PrepareTask activity.</li> <li>OnTaskCreated. The task properties are bound to the one in the PrepareTask activity.</li> <li>While (task not complete) <ul> <li>OnTaskChanged</li> </ul></li> </ul> <p>I am using WSS 3.0 SP1 and an ASPX (NOT InfoPath) task form.</p>
[ { "answer_id": 580360, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<z:row xmlns:z=\"#RowsetSchema\" \n ows_Instructions=\"\" \n ows_Body=\"\"\n ows_Comments=\"\"\n ows_ApprovalStatus=\"\"\n/>\n ows_ ows" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5782/" ]
218,989
<p>We have inherited an ant build file but now need to deploy to both 32bit and 64bit systems.</p> <p>The non-Java bits are done with GNUMakefiles where we just call "uname" to get the info. Is there a similar or even easier way to mimic this with ant?</p>
[ { "answer_id": 219032, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 2, "selected": false, "text": "dist ant -Dbuild.target=32 dist\n ant -Dbuild.target=64 dist\n ${build.target} ${os.arch}" }, { "answer_id": 4709520, "author": "phatypus", "author_id": 578269, "author_profile": "https://Stackoverflow.com/users/578269", "pm_score": 4, "selected": false, "text": "<var name =\"os.bitness\" value =\"unknown\"/>\n<if>\n<os family=\"windows\"/>\n<then>\n <exec dir=\".\" executable=\"cmd\" outputproperty=\"command.ouput\">\n <arg line=\"/c SET ProgramFiles(x86)\"/>\n </exec>\n <if>\n <contains string=\"${command.ouput}\" substring=\"Program Files (x86)\"/>\n <then>\n <var name =\"os.bitness\" value =\"64\"/>\n </then>\n <else>\n <var name =\"os.bitness\" value =\"32\"/>\n </else>\n </if>\n</then>\n<elseif>\n <os family=\"unix\"/>\n <then>\n <exec dir=\".\" executable=\"/bin/sh\" outputproperty=\"command.ouput\">\n <arg line=\"/c uname -m\"/>\n </exec>\n <if>\n <contains string=\"${command.ouput}\" substring=\"_64\"/>\n <then>\n <var name =\"os.bitness\" value =\"64\"/>\n </then>\n <else>\n <var name =\"os.bitness\" value =\"32\"/>\n </else>\n </if>\n </then>\n</elseif>\n</if>\n\n<echo>OS bitness: ${os.bitness}</echo>\n" }, { "answer_id": 8975549, "author": "Luis Soeiro", "author_id": 24165, "author_profile": "https://Stackoverflow.com/users/24165", "pm_score": 3, "selected": false, "text": "<project name=\"FindArchitecture\" default=\"check-architecture\" basedir=\".\">\n\n <!-- Properties set: unix-like (if it is unix or linux), x64 (if it is 64-bits),\n register- size (32 or 64) -->\n <target name=\"check-architecture\" depends=\"check-family,check-register\" >\n <echo>Register size: ${register-size}</echo>\n <echo>OS Family: ${os-family}</echo>\n </target>\n\n <target name=\"check-family\" >\n <condition property=\"os-family\" value=\"unix\" else=\"windows\">\n <os family=\"unix\" />\n </condition>\n\n <condition property=\"unix\">\n <os family=\"unix\" />\n </condition>\n </target>\n\n <target name=\"check-register\" depends=\"reg-unix,reg-windows\">\n </target>\n\n <!-- Test under GNU/Linux -->\n <target name=\"reg-unix\" if=\"unix\">\n <exec dir=\".\" executable=\"uname\" outputproperty=\"result\">\n <arg line=\"-m\"/>\n </exec>\n\n <!-- String ends in 64 -->\n <condition property=\"x64\">\n <matches string=\"${result}\" pattern=\"^.*64$\"/>\n </condition>\n\n <condition property=\"register-size\" value=\"64\" else=\"32\">\n <isset property=\"x64\"/>\n </condition>\n </target>\n\n <!-- Test under MS/Windows-->\n <target name=\"reg-windows\" unless=\"unix\">\n <!-- 64 bit Windows versions have the variable \"ProgramFiles(x86)\" -->\n <exec dir=\".\" executable=\"cmd\" outputproperty=\"result\">\n <arg line=\"/c SET ProgramFiles(x86)\"/>\n </exec>\n\n <!-- String ends in \"Program Files (x86)\" -->\n <condition property=\"x64\">\n <matches string=\"${result}\" pattern=\"^.*=.*Program Files \\(x86\\)\"/>\n </condition>\n\n <condition property=\"register-size\" value=\"64\" else=\"32\">\n <isset property=\"x64\"/>\n </condition>\n </target> \n</project>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/218989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6525/" ]
219,009
<p>If I view the HTML generated by one of my Jasper reports in IE7 I see the following: </p> <pre><code>&lt;BR /&gt;&lt;BR /&gt; &lt;A name="JR_PAGE_ANCHOR_0_1"&gt; &lt;TABLE style="WIDTH: 1000px" cellSpacing="0" cellPadding="0" bgColor="#ffffff" border="0"&gt; &lt;-- table body omitted --&gt; &lt;/TABLE&gt; </code></pre> <p>The two BR tags are added via the JRHtmlExporterParameter.HTML_HEADER parameter. After these tags and before the beginning of the report table that there's an unclosed anchor tag that is generated by Jasper reports. The fact that this tag is not correctly closed is messing up the formatting of my report because IE is hyperlinking the entire report TABLE. I'm not using this anchor tag, so if I could prevent Jasper from generating it, that would solve my problem.</p> <p>Incidentally, this problem only occurs in IE, in Firefox everything works fine because the anchor tag is properly closed.</p> <p>Thanks in advance, Don</p>
[ { "answer_id": 219119, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "<br /> a" }, { "answer_id": 72798989, "author": "ebey", "author_id": 8712753, "author_profile": "https://Stackoverflow.com/users/8712753", "pm_score": 0, "selected": false, "text": " private final SimpleXlsxReportConfiguration xlsxReportConfiguration;\n JRAbstractExporter exporter;\n\n this.xlsxReportConfiguration = new SimpleXlsxReportConfiguration(); \n ...\n xlsxReportConfiguration.setIgnoreAnchors(true);\n ...\n\n exporter = new JRXlsxExporter();\n exporter.setConfiguration(xlsxReportConfiguration);\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
219,046
<p>I'm trying to construct a query that will include a column indicating whether or not a user has downloaded a document. I have a table called HasDownloaded with the following columns: id, documentID, memberID. Finding out whether a user has downloaded a <em>specific</em> document is easy; but I need to generate a query where the results will look like this:</p> <pre><code>name id ---------------------- abc NULL bbb 2 ccc 53 ddd NULL eee 13 </code></pre> <p>The ID isn't really important; what I'm interested in is whether the document has been downloaded (is it NULL or not).</p> <p>Here is my query:</p> <pre><code>SELECT Documents.name, HasDownloaded.id FROM Documents LEFT JOIN HasDownloaded ON HasDownloaded.documentID = Documents.id WHERE HasDownloaded.memberID = @memberID </code></pre> <p>The problem is, this will only return values if an entry exists for the specified user in the HasDownloaded table. I'd like to keep this simple and only have entries in HasDownloaded for documents that <em>have</em> been downloaded. So if user 1 has downloaded abc, bbb, and ccc, I still want ddd and eee to show up in the resulting table, just with the id as NULL. But the WHERE clause only gives me values for which entries exists.</p> <p>I'm not much of a SQL expert - is there an operator that will give me what I want here? Should I be taking a different approach? Or is this impossible?</p>
[ { "answer_id": 219053, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 6, "selected": true, "text": "SELECT Documents.name, HasDownloaded.id FROM Documents\nLEFT JOIN HasDownloaded ON HasDownloaded.documentID = Documents.id \n AND HasDownloaded.memberID = @memberID \n" }, { "answer_id": 219149, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "WHERE HasDownloaded.memberId IS NULL OR HasDownloaded.memberId = @memberId\n WHERE COALESCE(HasDownloaded.memberId, @memberId) = @memberId\n" }, { "answer_id": 219286, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 2, "selected": false, "text": "AND HasDownloaded.memberID = @memberID\n WHERE HasDownloaded.memberId IS NULL OR HasDownloaded.memberId = @memberId\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4965/" ]
219,055
<p>I'm trying to get some code working that a previous developer has written. Yep, he now left the company. :-(</p> <p>I have a JSON RPC call being made from the JS code. The JS all runs fine and the callback method gets an object back (not an error object).</p> <p>But the method on the Java class never gets hit. The smd method does get hit though.</p> <hr> <pre><code>public String smd() { return SUCCESS; // break point reaches here } @SMDMethod public void updateRowValueForField(String key, String value, String fieldname) { // We never get into this method. } </code></pre> <hr> <pre><code>&lt;package name="EntryBarRPC" namespace="/" extends="star-default"&gt; &lt;action name="ebToggleSelection" class="eboggleSelectionAction" method="smd"&gt; &lt;interceptor-ref name="jsonStack"&gt; &lt;param name="enableSMD"&gt;true&lt;/param&gt; &lt;/interceptor-ref&gt; &lt;result type="json"&gt; &lt;param name="enableSMD"&gt;true&lt;/param&gt; &lt;/result&gt; &lt;/action&gt; &lt;/package&gt; </code></pre> <hr> <p>I'm stumped as to why, or what I'm missing. I've read <a href="http://cwiki.apache.org/S2PLUGINS/json-plugin.html" rel="nofollow noreferrer">JSON plugin page</a> over and over.</p> <p>I think I just need another set of eyes.</p> <p>Note: no errors in the Tomcat console, no JS errors.</p> <p>Anyone got any clues? Cheers Jeff Porter</p>
[ { "answer_id": 219095, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 1, "selected": false, "text": "smd() updateRowValueForField()" }, { "answer_id": 219103, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 3, "selected": true, "text": "<s:url id=\"smdUrl\" namespace=\"/nodecorate\" action=\"SMDAction\" />\n<script type=\"text/javascript\">\n //load dojo RPC\n dojo.require(\"dojo.rpc.*\");\n\n //create service object(proxy) using SMD (generated by the json result)\n var service = new dojo.rpc.JsonService(\"${smdUrl}\");\n\n //function called when remote method returns\n var callback = function(bean) {\n alert(\"Price for \" + bean.type + \" is \" + bean.price);\n };\n\n //parameter\n var bean = {type: \"Mocca\"};\n\n //execute remote method\n var defered = service.doSomething(bean, 5);\n\n //attach callback to defered object\n defered.addCallback(callback);\n</script>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26778/" ]
219,079
<p>In ActivePerl, "ppm" installs a package from the Internet, "ppm install x.ppd" installs from a ppd file, but most CPAN packages are distributed as <em>.tar.gz</em></p> <p>How do you supply modules to a machine running ActivePerl that doesn't have an Internet connection? ("make" will probably not be available.)</p> <p>Update: an Internet connection can be used to download files and transfer them to the machine with a USB key, etc.</p>
[ { "answer_id": 219207, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 3, "selected": false, "text": "ppm install x.ppd\n" }, { "answer_id": 10831042, "author": "JB.", "author_id": 1214248, "author_profile": "https://Stackoverflow.com/users/1214248", "pm_score": 2, "selected": false, "text": "ppm.bat install MIME-Lite-3.028.ppmx\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219079", "https://Stackoverflow.com", "https://Stackoverflow.com/users/46478/" ]
219,089
<p>I'm looking for an abstract base class or master page solution that will prevent anyone from doing XSRF using both a token and ttl. Can anyone point me in the right direction?</p> <p>Edit: The ideal solution will leverage the cookie that the default membership provider sends down to the client.</p>
[ { "answer_id": 230746, "author": "Toran Billups", "author_id": 2701, "author_profile": "https://Stackoverflow.com/users/2701", "pm_score": 0, "selected": false, "text": " public class PreventXSRF : MasterPage\n {\n\n HttpCookie mCookie = null;\n FormsAuthenticationTicket mPreviousAuthenticationTicket = null;\n FormsAuthenticationTicket mNewAuthenticationTicket = null;\n\n public bool IsXSRF()\n {\n if ((Request.Cookies(\".ASPXAUTH\") != null)) {\n mCookie = Request.Cookies(\".ASPXAUTH\");\n //get the current auth ticket so we can verify the token (userData) matches the value of the hidden input\n mPreviousAuthenticationTicket = FormsAuthentication.Decrypt(mCookie.Value);\n }\n else {\n ///'the membership cookie does not exist so this is not an authenticated user\n return true;\n }\n\n //** ** **\n // verify the cookie value matches the viewstate value\n // if it does then verify the ttl is valid\n //** ** **\n\n if ((mPreviousAuthenticationTicket != null)) {\n if (mPreviousAuthenticationTicket.UserData == Token) {\n if ((TTL != null)) {\n if (Convert.ToDateTime(TTL).AddMinutes(5) < DateTime.Now()) {\n ///'the ttl has expired so this is not a valid form submit\n return true;\n }\n }\n else {\n //** ** **\n // ?? what about a hack that could exploit this when a user tries to BF\n // a value for the token and simply keeps the viewstate for ttl null ??\n //** ** **\n }\n }\n else {\n //** ** **\n // ?? I hit this when I navigate to another page in the app (GET)\n // in this event, it was hit because the cookie has a valid token\n // but the page is new so viewstate is not valid ... ??\n //** ** **\n ///'the cookie value does not match the form so this is not a valid form submit\n return true;\n }\n }\n else {\n ///'the authentication ticket does not exist so this is not a valid form submit\n return true;\n }\n\n //** ** **\n // if the code gets this far the form submit is 99.9% valid, so now we gen a new token\n // and set this new value on the auth cookie and reset the viewstate value\n // so it matches the cookie\n //** ** **\n\n //gen a new ttl and set the viewstate value\n TTL = GenerateTTL();\n //gen a new token and set the viewstate value\n Token = GenerateToken();\n\n if ((mPreviousAuthenticationTicket != null)) {\n //** ** **\n // create a new authticket using the current values + a custom token\n // we are forced to do this because the current cookie is read-only\n // ** ** **\n mNewAuthenticationTicket = new FormsAuthenticationTicket(mPreviousAuthenticationTicket.Version, mPreviousAuthenticationTicket.Name, mPreviousAuthenticationTicket.IssueDate, mPreviousAuthenticationTicket.Expiration, mPreviousAuthenticationTicket.IsPersistent, Token);\n }\n else {\n ///'TODO: if no auth ticket exists we need to return as this won't be valid\n }\n\n if ((mCookie != null)) {\n //** ** **\n // take the new auth ticket with the userdata set to the new token value\n // encrypt this, update the cookie, and finally apply this to the users machine\n //** ** **\n mCookie.Value = FormsAuthentication.Encrypt(mNewAuthenticationTicket);\n Response.Cookies.Add(mCookie);\n }\n else {\n ///'TODO: if no cookie exists we need to return as this won't be valid\n }\n\n //if we got this far without a return true, it must not be a xsrf exploit so return false\n return false;\n }\n\n private string GenerateToken()\n {\n RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();\n byte[] randBytes = new byte[32];\n random.GetNonZeroBytes(randBytes);\n return Convert.ToBase64String(randBytes);\n }\n\n private string GenerateTTL()\n {\n return DateTime.Now();\n }\n\n private string TTL {\n get { return ViewState(\"TTL\"); }\n set { ViewState(\"TTL\") = value; }\n }\n\n private string Token {\n get { return ViewState(\"Token\"); }\n set { ViewState(\"Token\") = value; }\n }\n\n }\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2701/" ]
219,096
<p>When my application opens too many windows the taskbar groups them into one button. Each window has its own icon, but the grouping icon is the default "unknown"-kind icon.</p> <p>How can I set the grouping icon?</p>
[ { "answer_id": 219128, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "[HKEY_LOCAL_MACHINE\\SOFTWARE\\Classes\\Applications\\explorer.exe]\n\"TaskbarGroupIcon\"=\"C:\\Windows\\Explorer.exe,13\"\n" }, { "answer_id": 3264434, "author": "Ajay", "author_id": 393799, "author_profile": "https://Stackoverflow.com/users/393799", "pm_score": 1, "selected": false, "text": "RegistryKey RegKey = Registry.CurrentUser.OpenSubKey(\n \"Software\\\\Classes\\\\Applications\\temp.exe\",true); \nRegKey.SetValue(\"TaskbarGroupIcon\", \"c:\\temp.ico\", RegistryValueKind.String);\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23372/" ]
219,109
<p>Obviously I could create a <code>Calendar</code> object with the date and use <code>get(DAY)</code> on it, but knowing Groovy, I would guess there is an easier, quicker way I just don't know about?</p> <p><strong>Answer</strong></p> <pre><code>(date1..date2).size() == 1 // true if two dates are on same calendar day </code></pre>
[ { "answer_id": 219133, "author": "Ruben", "author_id": 26919, "author_profile": "https://Stackoverflow.com/users/26919", "pm_score": 4, "selected": true, "text": "def today = new Date()\ndef yesterday = today-1\nassert (yesterday..today).size() == 2\n" }, { "answer_id": 35921172, "author": "Eli Willaert", "author_id": 6045722, "author_profile": "https://Stackoverflow.com/users/6045722", "pm_score": 1, "selected": false, "text": "date1 - date2 == 0 //true if two dates are on same calendar day\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
219,110
<p>I have a <a href="http://en.wikipedia.org/wiki/Bluehost" rel="noreferrer">Bluehost</a> account where I can run Python scripts as CGI. I guess it's the simplest CGI, because to run I have to define the following in <code>.htaccess</code>:</p> <pre><code>Options +ExecCGI AddType text/html py AddHandler cgi-script .py </code></pre> <p>Now, whenever I look up web programming with Python, I hear a lot about WSGI and how most frameworks use it. But I just don't understand how it all fits together, especially when my web server is given (Apache running at a host's machine) and not something I can really play with (except defining <code>.htaccess</code> commands).</p> <p>How are <a href="http://en.wikipedia.org/wiki/Web_Server_Gateway_Interface" rel="noreferrer">WSGI</a>, CGI, and the frameworks all connected? What do I need to know, install, and do if I want to run a web framework (say <a href="http://webpy.org/" rel="noreferrer">web.py</a> or <a href="http://en.wikipedia.org/wiki/CherryPy" rel="noreferrer">CherryPy</a>) on my basic CGI configuration? How to install WSGI support?</p>
[ { "answer_id": 505534, "author": "James Brady", "author_id": 29903, "author_profile": "https://Stackoverflow.com/users/29903", "pm_score": 6, "selected": false, "text": "def simple_app(environ, start_response):\n \"\"\"Simplest possible application object\"\"\"\n status = '200 OK'\n response_headers = [('Content-type','text/plain')]\n start_response(status, response_headers)\n return ['Hello world!\\n']\n" }, { "answer_id": 520194, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 9, "selected": true, "text": "mod_wsgi mod_python mod_wsgi mod_fastcgi mod_wsgi Apache -> mod_fastcgi -> FLUP (via FastCGI protocol) -> Django (via WSGI protocol)\n manage.py runfcgi" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
219,120
<p>I'm working on keyboard input for a very basic kernel that I'm developing and I'm completely stuck. I can't seem to find any information online that can show me the information I need to know.</p> <p>My kernel is running in protected mode right now, so I can't use the real mode keyboard routines without jumping into real mode and back, which I'm trying to avoid. I want to be able to access my keyboard from protected mode. Does anyone know how to do this? The only thing I have found so far is that it involves talking to the controller directly using in/out ports, but beyond that I'm stumped. This is, of course, is not something that comes up very often. Normally, Assembly tutorials assume you're running an operating system underneath.</p> <p>I'm very new to the x86 assembly, so I'm just looking for some good resources for working with the standard hardware from protected mode. I'm compiling the Assembly source code with NASM and linking it to the C source code compiled with DJGPP. Any suggestions?</p>
[ { "answer_id": 33234973, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 1, "selected": false, "text": "sudo apt-get install build-essential qemu\nsudo ln -s /usr/bin/qemu-system-i386 /usr/bin/qemu\ngit clone git://git.code.sf.net/p/oszur11/code oszur11\ncd oszur11/Chapter_06_Shell/04_Makepp\nmake qemu\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19521/" ]
219,135
<p>I have been reading carefully through the mediawiki documentation but I have not been able to find out how to create new groups. </p> <p>When I look at Special:Userrights, I see only 3 groups : Bots, Sysops, Bureaycrats</p> <p>I would like to create my own custom groups, so I can use some extensions like the <a href="http://www.mediawiki.org/wiki/Extension:Group_Based_Access_Control" rel="noreferrer">http://www.mediawiki.org/wiki/Extension:Group_Based_Access_Control</a>.</p> <p>Can someone tell me how it's done, or point me to some documentation?</p>
[ { "answer_id": 219213, "author": "jeph perro", "author_id": 28351, "author_profile": "https://Stackoverflow.com/users/28351", "pm_score": 1, "selected": false, "text": "$wgGroupPermissions['TomatoUsers']['read'] = true;\n$wgGroupPermissions['TomatoUsers']['edit'] = false;\n" }, { "answer_id": 223633, "author": "richardkmiller", "author_id": 41820, "author_profile": "https://Stackoverflow.com/users/41820", "pm_score": 7, "selected": true, "text": "$wgGroupPermissions['Trusted'] = $wgGroupPermissions['user'];\n$wgGroupPermissions['user' ]['edit'] = false;\n$wgGroupPermissions['Trusted']['edit'] = true;\n$wgGroupPermissions['sysop' ]['edit'] = true;\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219135", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28351/" ]
219,138
<p>I need to run a Linux CLI command and get its stdout output from C.</p> <p>I can use pipe() to create a pipe, then fork/exec, redirecting child's stdout descriptor into the pipe before calling exec(), and reading from the pipe in parent. Plus I'll need to wait on the child.</p> <p>Is there a simple call to do fork + redirect + exec + wait, like system() does fork + exec + wait, only system() doesn't do the redirect.</p> <p>There's popen(), which does fork + redirect + exec, but doesn't do wait, so I can't get exit status.</p>
[ { "answer_id": 219150, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 1, "selected": false, "text": "popen() pclose() popen() pclose()" }, { "answer_id": 219709, "author": "humble_guru", "author_id": 23961, "author_profile": "https://Stackoverflow.com/users/23961", "pm_score": 1, "selected": false, "text": " /* simply invoke a app, pipe output*/\n pipe = popen(buf, \"r\" );\n if (pipe == NULL ) {\n printf(\"invoking %s failed: %s\\n\", buf, strerror(errno));\n return 1;\n }\n\n waitfor(10);\n\n while(!feof(pipe) ) {\n if( fgets( buf, 128, pipe ) != NULL ) {\n printf(\"%s\\n\", buf );\n }\n }\n\n /* Close pipe */\n rc = pclose(pipe);\n" }, { "answer_id": 3156299, "author": "garagumu", "author_id": 161699, "author_profile": "https://Stackoverflow.com/users/161699", "pm_score": 2, "selected": false, "text": "g_spawn_sync() const char *argv[] = { \"your_command\", NULL };\nchar *output = NULL; // will contain command output\nGError *error = NULL;\nint exit_status = 0;\nif (!g_spawn_sync(NULL, argv, NULL, 0, NULL, NULL, \n &output, NULL, &exit_status, &error))\n{\n // handle error here\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23420/" ]
219,139
<p>I'm trying to use stl algorithm for_each without proliferating templates throughout my code. std::for_each wants to instantiate MyFunctor class by value, but it can't since its abstract. I've created a functor adapter class which passes a pointer around and then derefernces it when appropriate.</p> <p>My Question: </p> <p>Does the STL or Boost already have such an adapter class? I don't want to have to reinvent the wheel!</p> <pre><code> struct MyFunctor { virtual ~MyFunctor() {} virtual void operator()(int a) = 0; } namespace { template&lt;typename FunctorType, typename OperandType&gt; struct FunctorAdapter { FunctorAdapter(FunctorType* functor) : mFunctor(functor) {} void operator()(OperandType&amp; subject) { (*mFunctor)(subject); } FunctorType* mFunctor; }; } void applyToAll(MyFunctor &amp;f) { FunctorHelper&lt;MyFunctor, int&gt; tmp(&amp;f); std::for_each(myvector.begin(), myvector.end(), tmp); } </code></pre> <p>Cheers,</p> <p>Dave </p>
[ { "answer_id": 219199, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 3, "selected": false, "text": "functional #include <functional>\n\nusing namespace std;\nfor_each( vec.begin(), vec.end(), :mem_fun_ptr( &MyClass::f ) );\n mem_fun_ptr mem_fun mem_fun1_ptr mem_fun1 mem_fun1 this for_each( vec.begin(), vec.end(), bind2nd( mem_fun_ptr( &MyClass::f ), 1 ) );\n" }, { "answer_id": 219208, "author": "Dan", "author_id": 27816, "author_profile": "https://Stackoverflow.com/users/27816", "pm_score": 0, "selected": false, "text": "bind(functor_pointer,mem_fun1(&MyFunctor::operator());\n" }, { "answer_id": 219890, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "class MyClass\n{\n virtual void process(int number) = 0;\n};\nMyClass *instance = ...;\n\nfor_each( vec.begin(), vec.end(), binder1st(instance, mem_fun_ptr(&MyClass::process) );\n" }, { "answer_id": 220220, "author": "Aaron", "author_id": 14153, "author_profile": "https://Stackoverflow.com/users/14153", "pm_score": 3, "selected": true, "text": "// requires TR1 support from your compiler / standard library implementation\n#include <functional>\n\nvoid applyToAll(MyFunctor &f) {\n std::for_each(\n myvector.begin(), \n myvector.end(), \n std::tr1::ref(f) \n ); \n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219139", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1575281/" ]
219,151
<p>I want to create a WCF-service hosted in IIS6 and disable anonymous authentication in IIS. And don't use SSL.</p> <p>So only way I have is to use basicHttpBinging with <code>TransportCredentialOnly</code>, itsn't it?</p> <p>I create a virtual directory, set Windows Integrated Auth and uncheck "Enable Anonymous Access".</p> <p>Here's my web.config:</p> <pre><code>&lt;system.serviceModel&gt; &lt;bindings&gt; &lt;basicHttpBinding&gt; &lt;binding name="MyBinding"&gt; &lt;security mode="TransportCredentialOnly"&gt; &lt;transport clientCredentialType="Windows" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/basicHttpBinding&gt; &lt;/bindings&gt; &lt;services&gt; &lt;service name="Samples.ServiceFacadeService" behaviorConfiguration="ServiceFacadeServiceBehavior"&gt; &lt;endpoint address="" binding="basicHttpBinding" bindingName="MyBinding" contract="Samples.IServiceFacadeService"&gt; &lt;/endpoint&gt; &lt;/service&gt; &lt;/services&gt; &lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="ServiceFacadeServiceBehavior"&gt; &lt;serviceDebug includeExceptionDetailInFaults="true"/&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; &lt;/system.serviceModel&gt; </code></pre> <p>You can see that I even haven't included MEX-enpoint for metadata exchange. Just one endpoint and one binding for it with TransportCredentialOnly security.</p> <p>But when I tries to start service (invoking a method throught client proxy) I got such exception in the EventLog:</p> <blockquote> <p>Exception: System.ServiceModel.ServiceActivationException: The service '/wcftest/ServiceFacadeService.svc' cannot be activated due to an exception during compilation. The exception message is: Security settings for this service require 'Anonymous' Authentication but it is not enabled for the IIS application that hosts this service.. ---> System.NotSupportedException: Security settings for this service require 'Anonymous' Authentication but it is not enabled for the IIS application that hosts this service.</p> </blockquote> <p>I have no idea why my service require Anonymous auth? Why?</p>
[ { "answer_id": 219270, "author": "Sixto Saez", "author_id": 9711, "author_profile": "https://Stackoverflow.com/users/9711", "pm_score": 3, "selected": false, "text": "<services>\n <!-- Note: the service name must match the configuration name for the service implementation. -->\n <service name=\"MyNamespace.MyServiceType\" behaviorConfiguration=\"MyServiceTypeBehaviors\" >\n <!-- Add the following endpoint. -->\n <!-- Note: your service must have an http base address to add this endpoint. -->\n <endpoint contract=\"IMetadataExchange\" binding=\"mexHttpBinding\" address=\"mex\" />\n </service>\n</services>\n\n<behaviors>\n <serviceBehaviors>\n <behavior name=\"MyServiceTypeBehaviors\" >\n <!-- This disables it. -->\n <serviceMetadata httpGetEnabled=\"false\" />\n </behavior>\n </serviceBehaviors>\n</behaviors>\n" }, { "answer_id": 219516, "author": "Shrike", "author_id": 27703, "author_profile": "https://Stackoverflow.com/users/27703", "pm_score": 3, "selected": false, "text": "<endpoint address=\"\" binding=\"basicHttpBinding\" bindingName=\"MyBinding\"\n contract=\"Samples.IServiceFacadeService\">\n</endpoint>\n <endpoint address=\"\" binding=\"basicHttpBinding\" **bindingConfiguration**=\"MyBinding\"\n contract=\"Samples.IServiceFacadeService\">\n</endpoint>\n" }, { "answer_id": 4806721, "author": "wcfdude", "author_id": 590882, "author_profile": "https://Stackoverflow.com/users/590882", "pm_score": 1, "selected": false, "text": "[PrincipalPermission(SecurityAction.Demand, Role = \"MyADGroup\")]\npublic string SendMyMessage(string Message)\n{...}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27703/" ]
219,168
<p><a href="http://en.wikipedia.org/wiki/Literate_programming" rel="noreferrer">Literate programming</a> is a way of developing software where documentation comes first, then the coding. One writes the documentation of a code snippet, and then writes the implementation of the snippet. The visual appearance of the software source code would be a plain document like word, with code paragraphs in it. </p> <p>I am trying to convert the dev shop I work to use only literate programming, as it brings great advantages to code readability and maintenance. However, due to the lack of tools the LP usage is limited in the company. For example, the ideal way to program literate is to write a paragraph using word markup, and then insert a subparagraph with the implementation. But i cannot seem to find any good tools for VS200x to perform LP with. </p> <p>Ideally, such a tool would look just like Word 2007, but integrated into the IDE. When the coder sets the cursor on a code paragraph, it would have all the functionality provided just like we have now in our IDE. </p> <p>What are good tools for LP, with .NET and VS200x in particular?</p>
[ { "answer_id": 33870729, "author": "user5595141", "author_id": 5595141, "author_profile": "https://Stackoverflow.com/users/5595141", "pm_score": 1, "selected": false, "text": "% /* begin of literate program \n\\documentstyle{article}\n\\usepackage{listings}\n\n\\lstdefinitions here I do not remember the syntax. Here one can define \n a replacement for startcode*/ and /*endcode for spaces.\n\nmore definitions here\n\n\\begin{document}\nYour explanation including formulas like $s=c\\times\\sum_{i=0}^{i=N} x_i$ etc.\n\\begin{lstlising}\nstartcode*/\n\ns=0\nfor(i=0;i<=N;i++) s=s+x[i];\ns=c*s;\n\netc..\n\n/*endofcode\n\\end{lstlisting}\n\nMore explanation ...\n\\end{document} \n% end of literate program */\n % end of literate program */ \n % /* start of program\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219168", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29688/" ]
219,219
<p>Is it possible to to change a <code>&lt;span&gt;</code> tag (or <code>&lt;div&gt;</code>) to preformat its contents like a <code>&lt;pre&gt;</code> tag would using only CSS?</p>
[ { "answer_id": 219230, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 9, "selected": true, "text": "pre {\n display: block;\n unicode-bidi: embed;\n font-family: monospace;\n white-space: pre;\n}\n" }, { "answer_id": 219241, "author": "Pistos", "author_id": 28558, "author_profile": "https://Stackoverflow.com/users/28558", "pm_score": 6, "selected": false, "text": ".like-pre { white-space: pre; }\n" }, { "answer_id": 219242, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 3, "selected": false, "text": "white-space: pre\n" }, { "answer_id": 219254, "author": "Mr. Shiny and New 安宇", "author_id": 7867, "author_profile": "https://Stackoverflow.com/users/7867", "pm_score": 5, "selected": false, "text": "span {\n white-space: pre;\n font-family: monospace;\n display: block;\n}\n" }, { "answer_id": 15003581, "author": "Yanni", "author_id": 689782, "author_profile": "https://Stackoverflow.com/users/689782", "pm_score": 2, "selected": false, "text": "span {\n white-space: pre;\n font-family: monospace;\n display: block;\n unicode-bidi: embed\n}\n" }, { "answer_id": 30950709, "author": "Yesu Raj", "author_id": 896043, "author_profile": "https://Stackoverflow.com/users/896043", "pm_score": 1, "selected": false, "text": ".pre {\n\nwhite-space: pre-wrap;\nwhite-space: -moz-pre-wrap;\nwhite-space: -pre-wrap;\nwhite-space: -o-pre-wrap;\nword-wrap: break-word;\nline-height: 1.5; \nword-break: break-all;\nwhite-space: pre;\nwhite-space: pre\\9; /* IE7+ */\ndisplay: block;\n}\n" }, { "answer_id": 64872281, "author": "Christophe Le Besnerais", "author_id": 990193, "author_profile": "https://Stackoverflow.com/users/990193", "pm_score": 3, "selected": false, "text": "white-space: pre-wrap;\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1432/" ]
219,226
<p>Recently I have been studying recursion; how to write it, analyze it, etc. I have thought for a while that recurrence and recursion were the same thing, but some problems on recent homework assignments and quizzes have me thinking there are slight differences, that 'recurrence' is the way to describe a recursive program or function.</p> <p>This has all been very Greek to me until recently, when I realized that there is something called the 'master theorem' used to write the 'recurrence' for problems or programs. I've been reading through the wikipedia page, but, as usual, things are worded in such a way that I don't really understand what it's talking about. I learn much better with examples.</p> <p>So, a few questions: Lets say you are given this recurrence:</p> <blockquote> <p>r(n) = 2*r(n-2) + r(n-1);<br> r(1) = r(2) = 1</p> </blockquote> <p>Is this, in fact, in the form of the master theorem? If so, in words, what is it saying? If you were to be trying to write a small program or a tree of recursion based on this recurrence, what would that look like? Should I just try substituting numbers in, seeing a pattern, then writing pseudocode that could recursively create that pattern, or, since this may be in the form of the master theorem, is there a more straightforward, mathematical approach?</p> <p>Now, lets say you were asked to find the recurrence, T(n), for the number of additions performed by the program created from the previous recurrence. I can see that the base case would probably be T(1) = T(2) = 0, but I'm not sure where to go from there.</p> <p>Basically, I am asking how to go from a given recurrence to code, and the opposite. Since this looks like the master theorem, I'm wondering if there is a straightforward and mathematical way of going about it.</p> <p>EDIT: Okay, I've looked through some of my past assignments to find another example of where I'm asked, 'to find the recurrence', which is the part of this question I'm having the post trouble with.</p> <blockquote> <p>Recurrence that describes in the best way the number of addition operations in the following program fragment (when called with l == 1 and r == n)</p> </blockquote> <pre><code>int example(A, int l, int r) { if (l == r) return 2; return (A[l] + example(A, l+1, r); } </code></pre>
[ { "answer_id": 219238, "author": "David Koelle", "author_id": 2197, "author_profile": "https://Stackoverflow.com/users/2197", "pm_score": 1, "selected": false, "text": "function r(int n) \n{\n if (n == 2) return 1;\n if (n == 1) return 1;\n return 2 * r(n-2) + r(n-1); // I guess we're assuming n > 2\n}\n" }, { "answer_id": 219250, "author": "Elie", "author_id": 23249, "author_profile": "https://Stackoverflow.com/users/23249", "pm_score": 1, "selected": false, "text": "public int r(int input) {\n if (input == 1 || input == 2) {\n return 1;\n } else {\n return 2 * r(input - 2) + r(input -1)\n }\n}\n" }, { "answer_id": 3474202, "author": "Michael M. Adkins", "author_id": 417828, "author_profile": "https://Stackoverflow.com/users/417828", "pm_score": 2, "selected": false, "text": "r(n) = a*r(n-1) + b*r(n-2) + f(n)\n x^k - c[1]*x^k-1 - c[2]*x^k-2 - ... - c[k-1]*x - c[k] = 0\n x^2 - a*x - b = 0\n r(n) = a*r(n-1) + b*r(n-2)\n r(n) - a*r(n-1) - b*r(n-2) = 0\n if x[1]!=x[2]\n c[1]*x[1]^n + c[2]*x[2]^n\nelse\n c[1]*x[1]^n + n*c[2]*x[2]^n\n x = (-1 +- sqrt(-1^2 - 4(1)(-2)))/2(1)\n\n x[1] = ((-1 + 3)/2) = 1\n x[2] = ((-1 - 3)/2) = -2\n c[1](x[1])^n + c[2](x[2])^n\n c[1](1)^1 + c[2](-2)^1 = 1\nc[1](1)^2 + c[2](-2)^2 = 1\n [ 1 1 | 1 ]\n[ 1 2 | 1 ] \n int example(A, int l, int r) {\n if (l == r)\n return 2;\n return (A[l] + example(A, l+1, r);\n}\n int example(A, int l, int r) { => T(r) = 0\n if (l == r) => T(r) = 1\n return 2; => T(r) = 1\n return (A[l] + example(A, l+1, r); => T(r) = 1 + T(r-(l+1))\n}\n\nTotal: T(r) = 3 + T(r-(l+1))\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23323/" ]
219,243
<pre><code>function Submit_click() { if (!bValidateFields()) return; } function bValidateFields() { /// &lt;summary&gt;Validation rules&lt;/summary&gt; /// &lt;returns&gt;Boolean&lt;/returns&gt; ... } </code></pre> <p>So, when I type the call to my bValidateFields() function intellisence in Visual Studio doesn't show my comments. But according to <a href="http://weblogs.asp.net/scottgu/archive/2007/06/21/vs-2008-javascript-intellisense.aspx" rel="nofollow noreferrer">this</a> it should. Should it?</p>
[ { "answer_id": 219279, "author": "SaaS Developer", "author_id": 7215, "author_profile": "https://Stackoverflow.com/users/7215", "pm_score": 0, "selected": false, "text": "/// <reference>" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28098/" ]
219,245
<p>I'm looking for a way to transform a genuine string into it's hexadecimal value in SQL. I'm looking something that is Informix-friendly but I would obviously prefer something database-neutral </p> <p>Here is the select I am using now:</p> <pre><code>SELECT SomeStringColumn from SomeTable </code></pre> <p>Here is the select I would like to use: SELECT hex( SomeStringColumn ) from SomeTable</p> <p>Unfortunately nothing is that simple... Informix gives me that message: <em>Character to numeric conversion error</em></p> <p>Any idea?</p>
[ { "answer_id": 219310, "author": "stephenbayer", "author_id": 18893, "author_profile": "https://Stackoverflow.com/users/18893", "pm_score": 4, "selected": false, "text": "SELECT master.dbo.fn_varbintohexstr(CAST(SomeStringColumn AS varbinary)) \nFROM SomeTable\n SELECT master.dbo.fn_varbintohexstr(CAST(Addr1 AS VARBINARY)) AS Expr1\nFROM Customer\n SELECT hex(CAST(Addr1 AS VARBINARY)) AS Expr1\nFROM Customer\n" }, { "answer_id": 219321, "author": "Josh", "author_id": 2204759, "author_profile": "https://Stackoverflow.com/users/2204759", "pm_score": 0, "selected": false, "text": "select hex(cast SomeStringColumn as int)) from SomeTable\n" }, { "answer_id": 1637783, "author": "jhamm", "author_id": 103927, "author_profile": "https://Stackoverflow.com/users/103927", "pm_score": 3, "selected": false, "text": "select convert(varbinary, SomeStringColumn) from SomeTable\n" }, { "answer_id": 8929661, "author": "Boklucius", "author_id": 697489, "author_profile": "https://Stackoverflow.com/users/697489", "pm_score": 0, "selected": false, "text": "declare @hexstring varchar(max);\nset @hexstring = 'E0F0C0';\nselect cast('' as xml).value('xs:hexBinary( substring(sql:variable(\"@hexstring\"), sql:column(\"t.pos\")) )', 'varbinary(max)')\nfrom (select case substring(@hexstring, 1, 2) when '0x' then 3 else 0 end) as t(pos)\n" }, { "answer_id": 43771962, "author": "gusmundo", "author_id": 4762664, "author_profile": "https://Stackoverflow.com/users/4762664", "pm_score": 0, "selected": false, "text": "convert(varchar, convert(Varbinary(MAX), YOURSTRING),2)" }, { "answer_id": 67249360, "author": "Ben", "author_id": 21347, "author_profile": "https://Stackoverflow.com/users/21347", "pm_score": 0, "selected": false, "text": "select convert(varbinary, '0xa3c0', 1)\n select convert(varbinary, '0x' + RIGHT('00000000' + REPLACE('0xa3c','0x',''), 8), 1)\n" }, { "answer_id": 74224916, "author": "Евген Марчен", "author_id": 20350683, "author_profile": "https://Stackoverflow.com/users/20350683", "pm_score": 0, "selected": false, "text": "SUBSTRING(CONVERT(varbinary,Addr1 ) ,1,1) as Expr1\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219245", "https://Stackoverflow.com", "https://Stackoverflow.com/users/244/" ]
219,285
<p>Nowadays, we have tons of Javascript libraries per page in addition to the Javascript files we write ourselves. How do you manage them all? How do you minify them in an organized way? </p>
[ { "answer_id": 219333, "author": "pkaeding", "author_id": 4257, "author_profile": "https://Stackoverflow.com/users/4257", "pm_score": 1, "selected": false, "text": "/\n+--/javascript/\n +-- lib/\n +-- admin/\n +-- compnent1/\n +-- compnent2/\n" }, { "answer_id": 219348, "author": "Tom", "author_id": 20, "author_profile": "https://Stackoverflow.com/users/20", "pm_score": 3, "selected": false, "text": "+--root\n |--javascript\n |--lib\n |--prototype.js\n |--scriptaculous\n |--scriptaculous.js\n |--effects.js\n |--..\n |--myOwnScript.js\n |--myOwnScript2.js\n" }, { "answer_id": 219700, "author": "savetheclocktower", "author_id": 25720, "author_profile": "https://Stackoverflow.com/users/25720", "pm_score": 2, "selected": false, "text": "lib" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10352/" ]
219,323
<p>Here is a stripped down version of what I use to authenticate users, it works fine on my PHP v5.0.2/MySQL 4.0.21 server, but fails on my PHP v5.1.6/MySQL v5.0.45 server.</p> <p>In the code below, should I be aware of anything that might not be supported by the newer version of PHP &amp; MySQL? Global variables have been enabled.</p> <pre><code>&lt;?php if(!isset($HTTP_POST_VARS['username'])&amp;&amp;!isset($HTTP_POST_VARS['password'])) { //Visitor needs to enter a name and password ?&gt; &lt;h1&gt;Please Log In&lt;/h1&gt; This page is secret. &lt;form method="post" action="&lt;?php echo $PHP_SELF;?&gt;"&gt; &lt;table border="1"&gt; &lt;tr&gt; &lt;th&gt; Username &lt;/th&gt; &lt;td&gt; &lt;input type="text" name="username"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;th&gt; Password &lt;/th&gt; &lt;td&gt; &lt;input type="password" name="password"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="2" align="center"&gt; &lt;input type="submit" value="Log In"&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; &lt;?php } else { // connect to mysql include('../cgi-bin/db.php'); $username = $HTTP_POST_VARS['username']; $password = md5($HTTP_POST_VARS['password']); if(!$db) { echo 'Cannot connect to database.'; exit; } // select the appropriate database $mysql = mysql_select_db('quickwebcms'); if(!$mysql) { echo 'Cannot select database.'; exit; } // query the database to see if there is a record which matches $query = "select count(*) from auth where username = '$username' and password = '$password'"; $result = mysql_query( $query ); if(!$result) { echo 'Cannot run query.'; exit; } $count = mysql_result( $result, 0, 0 ); if ( $count &gt; 0 ) { // visitor's name and password combination are correct echo '&lt;h1&gt;Here it is!&lt;/h1&gt;'; echo 'I bet you are glad you can see this secret page.'; } else { // visitor's name and password combination are not correct echo '&lt;h1&gt;Go Away!&lt;/h1&gt;'; echo 'You are not authorized to view this resource.'; } } ?&gt; </code></pre>
[ { "answer_id": 219341, "author": "changelog", "author_id": 5646, "author_profile": "https://Stackoverflow.com/users/5646", "pm_score": 3, "selected": true, "text": "$HTTP_POST_VARS $_POST <?php // Enable displaying errors\nerror_reporting(E_ALL);\nini_set('display_errors', '1');\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
219,329
<p>I have inherited a django+fastcgi application which needs to be modified to perform a lengthy computation (up to half an hour or more). What I want to do is run the computation in the background and return a "your job has been started" -type response. While the process is running, further hits to the url should return "your job is still running" until the job finishes at which point the results of the job should be returned. Any subsequent hit on the url should return the cached result. </p> <p>I'm an utter novice at django and haven't done any significant web work in a decade so I don't know if there's a built-in way to do what I want. I've tried starting the process via subprocess.Popen(), and that works fine except for the fact it leaves a defunct entry in the process table. I need a clean solution that can remove temporary files and any traces of the process once it has finished.</p> <p>I've also experimented with fork() and threads and have yet to come up with a viable solution. Is there a canonical solution to what seems to me to be a pretty common use case? FWIW this will only be used on an internal server with very low traffic.</p>
[ { "answer_id": 397968, "author": "sastanin", "author_id": 25450, "author_profile": "https://Stackoverflow.com/users/25450", "pm_score": 2, "selected": false, "text": "myjob.py import sys\nfrom time import sleep\n\ni = 0\nwhile i < 1000:\n print 'myjob:', i \n i=i+1\n sleep(0.1)\n sys.stdout.flush()\n urls.py urlpatterns = patterns('',\n(r'^startjob/$', 'mysite.myapp.views.startjob'),\n(r'^showjob/$', 'mysite.myapp.views.showjob'),\n(r'^rmjob/$', 'mysite.myapp.views.rmjob'),\n)\n from tempfile import mkstemp\nfrom os import fdopen,unlink,kill\nfrom subprocess import Popen\nimport signal\n\ndef startjob(request):\n \"\"\"Start a new long running process unless already started.\"\"\"\n if not request.session.has_key('job'):\n # create a temporary file to save the resuls\n outfd,outname=mkstemp()\n request.session['jobfile']=outname\n outfile=fdopen(outfd,'a+')\n proc=Popen(\"python myjob.py\",shell=True,stdout=outfile)\n # remember pid to terminate the job later\n request.session['job']=proc.pid\n return HttpResponse('A <a href=\"/showjob/\">new job</a> has started.')\n\ndef showjob(request):\n \"\"\"Show the last result of the running job.\"\"\"\n if not request.session.has_key('job'):\n return HttpResponse('Not running a job.'+\\\n '<a href=\"/startjob/\">Start a new one?</a>')\n else:\n filename=request.session['jobfile']\n results=open(filename)\n lines=results.readlines()\n try:\n return HttpResponse(lines[-1]+\\\n '<p><a href=\"/rmjob/\">Terminate?</a>')\n except:\n return HttpResponse('No results yet.'+\\\n '<p><a href=\"/rmjob/\">Terminate?</a>')\n return response\n\ndef rmjob(request):\n \"\"\"Terminate the runining job.\"\"\"\n if request.session.has_key('job'):\n job=request.session['job']\n filename=request.session['jobfile']\n try:\n kill(job,signal.SIGKILL) # unix only\n unlink(filename)\n except OSError, e:\n pass # probably the job has finished already\n del request.session['job']\n del request.session['jobfile']\n return HttpResponseRedirect('/startjob/') # start a new one\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
219,338
<p>I'm using JQuery's jquery.corner.js to create rounded corners on some td tags, and they look fine in IE EXCEPT </p> <ol> <li>if you open a new tab and then come back to the page</li> <li>if you go to another tab, click a link, then come back to the page</li> <li>if you hover over a javascript-executing div / menu (I think).</li> </ol> <p>The rounded corners are replaced with horizontal lines, and text within the td tag is pushed down. Once the page is refreshed, however, the rendering is back to normal. In all cases it works perfectly in Firefox.</p> <p>Any ideas?</p> <p>For reference, the Javascript code I'm using is as follows (it's a MOSS 2007 page):</p> <pre><code>$(document).ready(function(){ $("table.ms-navheader td").corner("top"); }); </code></pre> <p>Here's a sample HTML page that displays the problem perfectly:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script type="text/javascript" src="jquery-1.2.6.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="jquery.corner.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; &lt;!-- $(document).ready(function() { $("div").corner("top"); $("td").corner(); }); //--&gt; &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;table&gt; &lt;tr&gt; &lt;td style="background-color: blue"&gt; TD that will be messed up. &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;div style="background-color: green"&gt; divs don't get messed up. &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>In the above code, the TD will be messed up once you open up a new tab, but not the div. I don't have much control over the HTML emitted by MOSS, otherwise I might have bitten the bullet and used DIVs here instead of a table.</p>
[ { "answer_id": 950410, "author": "Kris", "author_id": 22237, "author_profile": "https://Stackoverflow.com/users/22237", "pm_score": 0, "selected": false, "text": "$('.selected').css('background-color', '#3296C0');\n $('#top-nav li a').hover(function(){\n $(this).corners('top');\n });\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1943/" ]
219,360
<p>I've got a unfinished project that a developer just didn't finish and didn't leave any documentation about the installation process. I've downloaded the production directory to my windows machine (running InstantRails 2), I created the databases as required in the <code>database.yml</code> and I tried to run the <code>rake:db:migrate --trace</code> but I'm receiving the following error message:</p> <pre><code>(in D:/projects/broke2) ** Invoke db:migrate (first_time) ** Invoke environment (first_time) ** Execute environment ** Execute db:migrate rake aborted! uninitialized constant Admin D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:279:in `load_missing_constant' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:468:in `const_missing' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/dependencies.rb:480:in `const_missing' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/inflector.rb:285:in `constantize' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/inflector.rb:284:in `each' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/inflector.rb:284:in `constantize' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/string/inflections.rb:143:in `constantize' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:481:in `migrations' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/connection_adapters/mysql_adapter.rb:15:in `inject' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:465:in `each' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:465:in `inject' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:465:in `migrations' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:431:in `migrate' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:373:in `up' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/activerecord-2.1.1/lib/active_record/migration.rb:356:in `migrate' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rails-2.1.1/lib/tasks/databases.rake:99 D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:617:in `call' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:617:in `execute' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:612:in `each' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:612:in `execute' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:578:in `invoke_with_call_chain' D:/InstantRails-2.0-win/ruby/lib/ruby/1.8/monitor.rb:242:in `synchronize' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:571:in `invoke_with_call_chain' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:564:in `invoke' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2019:in `invoke_task' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `top_level' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `each' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1997:in `top_level' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1991:in `top_level' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1970:in `run' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:2036:in `standard_exception_handling' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/lib/rake.rb:1967:in `run' D:/InstantRails-2.0-win/ruby/lib/ruby/gems/1.8/gems/rake-0.8.3/bin/rake:31 D:/InstantRails-2.0-win/ruby/bin/rake:19:in `load' D:/InstantRails-2.0-win/ruby/bin/rake:19 </code></pre> <p>I'm a regular Rails developer (it's not my first app) but I never saw this error and I don't have a clue where to start to debug.</p>
[ { "answer_id": 219383, "author": "Chris Bunch", "author_id": 422, "author_profile": "https://Stackoverflow.com/users/422", "pm_score": 1, "selected": false, "text": "uninitialized constant Admin" }, { "answer_id": 219397, "author": "Luke Francl", "author_id": 17965, "author_profile": "https://Stackoverflow.com/users/17965", "pm_score": 3, "selected": true, "text": "rake db:migrate VERSION=1" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18642/" ]
219,368
<p>I got a little problem I can't figure out. I have a server side MarshalByRefObject that I'm trying to wrap a transparent proxy around on the client side. Here's the setup:</p> <pre><code>public class ClientProgram { public static void Main( string[] args ) { ITest test = (ITest)Activator.GetObject( typeof( ITest ), "http://127.0.0.1:8765/Test.rem" ); test = (ITest)new MyProxy( test ).GetTransparentProxy(); test.Foo(); } } public class MyProxy : RealProxy { private MarshalByRefObject _object; public MyProxy( ITest pInstance ) : base( pInstance.GetType() ) { _object = (MarshalByRefObject)pInstance; } public override IMessage Invoke( IMessage msg ) { return RemotingServices.ExecuteMessage( _object, (IMethodCallMessage)msg ); } } </code></pre> <p>The problem is that the call to RemotingServices.ExecuteMethod, an exception is thrown with the message "ExecuteMessage can be called only from the native context of the object.". Can anyone point out how to get this to work correctly? I need to inject some code before and after the method calls on remote objects. Cheers!</p>
[ { "answer_id": 219442, "author": "bh213", "author_id": 28912, "author_profile": "https://Stackoverflow.com/users/28912", "pm_score": 0, "selected": false, "text": "ITest test = (ITest)Activator.GetObject( typeof( ITest ), \"http://127.0.0.1:8765/Test.rem\" );\nRealProxy p2 = RemotingServices.GetRealProxy(test)\ntest = (ITest)new MyProxy( p2 ).GetTransparentProxy();\ntest.Foo();\n" }, { "answer_id": 219531, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "public class ClientProgram {\n public static void Main( string[] args ) {\n ITest test = (ITest)Activator.GetObject( typeof( ITest ), \"http://127.0.0.1:8765/Test.rem\" );\n ITest test2 = (ITest)new MyProxy( test ).GetTransparentProxy();\n test2.Foo();\n }\n }\n\npublic class MyProxy : RealProxy {\n\n private object _obj;\n\n public MyProxy( object pObj )\n : base( typeof( ITest ) ) {\n _obj = pObj;\n }\n\n public override IMessage Invoke( IMessage msg ) {\n RealProxy rp = RemotingServices.GetRealProxy( _obj );\n return rp.Invoke( msg );\n }\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
219,369
<p>I want to display some WPF elements near to the selected item of a ListView. How can I obtain the coordinates (screen or relative) of the selected ListViewItem? </p> <pre><code>&lt;ListView x:Name="TechSchoolListView" ClipToBounds="False" Width="Auto" Height="Auto" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Top" ItemTemplate="{DynamicResource TechSchoolDataTemplate}" ItemsSource="{Binding Path=TechSchoolResearchList, Mode=Default}" SelectedIndex="1" SelectedValue="{Binding Path=SelectedTechSchool, Mode=Default}" SelectionChanged="TechSchoolList_SelectionChanged" ItemContainerStyle="{DynamicResource TechSchoolItemContainerStyle}" ScrollViewer.CanContentScroll="False" ScrollViewer.VerticalScrollBarVisibility="Disabled" &gt; &lt;ListView.Background&gt; &lt;SolidColorBrush Color="{DynamicResource PanelBackgroundColor}"/&gt; &lt;/ListView.Background&gt; &lt;/ListView&gt; </code></pre>
[ { "answer_id": 219450, "author": "ChaosSpeeder", "author_id": 205962, "author_profile": "https://Stackoverflow.com/users/205962", "pm_score": 2, "selected": false, "text": " UIElement selectedContainer = (UIElement) TechSchoolListView.ItemContainerGenerator.ContainerFromIndex(TechSchoolListView.SelectedIndex);\n Point cursorPos = selectedContainer.TranslatePoint(new Point(selectedContainer.DesiredSize.Width, 0.0), Page);\n PanelCursor.Height = selectedContainer.DesiredSize.Height;\n PanelCursor.Margin = new Thickness(400, cursorPos.Y, 0.0, 0.0);\n" }, { "answer_id": 68728584, "author": "PWCoder", "author_id": 14960250, "author_profile": "https://Stackoverflow.com/users/14960250", "pm_score": 0, "selected": false, "text": "UIElement selectedContainer = (UIElement)(sender as \nListView).ItemContainerGenerator.ContainerFromIndex((sender as \nListView).SelectedIndex);\nPoint startPoint = selectedContainer.PointToScreen(new Point(0,0));\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/205962/" ]
219,381
<p>I'm in the process of refactoring a project. I've got an entire subfolder which is known to be broken. Is there any declarative way to exclude that folder from the compile temporarily while I test the refactoring thus far?</p> <p>I realize I could delete the folder, but I'd like to do this through configuration if possible.</p>
[ { "answer_id": 21044137, "author": "L.Barral", "author_id": 3004607, "author_profile": "https://Stackoverflow.com/users/3004607", "pm_score": 3, "selected": false, "text": "<PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \"> <ExcludeFoldersFromDeployment>FolderToExclude</ExcludeFoldersFromDeployment>\n <ExcludeFilesFromDeployment>File1.aspx;File2.aspx</ExcludeFilesFromDeployment>\n" }, { "answer_id": 44161608, "author": "OrangeKing89", "author_id": 959977, "author_profile": "https://Stackoverflow.com/users/959977", "pm_score": 1, "selected": false, "text": "1. Open Windows Explorer.\n2. Go to the physical folder of your website.\n3. Right click the file/folder which you want to exclude, and then select \"Properties\".\n4. Check the \"Hidden\" attribute.\n5. Click the \"Refresh\" button in the Visual Studio Solution Explorer\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
219,396
<p>I'm writing a mobile content adaptation plugin for a bespoke CMS in PHP. The CMS contains <code>&lt;img/&gt;</code> links to images with absolute URLs which are all 400 pixels wide and vary in height.</p> <p>I'd like to parse the HTML (which is stored in MySQL) and re-scale each image to a new width - this will vary according to the device. I'd also like to cache the images to prevent needlessly resizing them on-the-fly every time the page is loaded</p> <p>What's the best way for me to achieve this in PHP using either ImageMagick or GD? </p>
[ { "answer_id": 219407, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 2, "selected": false, "text": "<img src=\"/images/image.php?height=200&width=200&source=filename.jpg\" />\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
219,402
<p>I want to find a linux command that can return a part of the string. In most programming languages, it's the <code>substr()</code> function. Does bash have any command that can be used for this purpose. I want to be able to do something like this... <code>substr "abcdefg" 2 3</code> - prints <code>cde</code>.</p> <hr> <p>Subsequent similar question:</p> <ul> <li><a href="https://stackoverflow.com/questions/428109/extract-substring-in-bash">Extract substring in Bash</a></li> </ul>
[ { "answer_id": 219409, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 7, "selected": false, "text": "${parameter:offset}\n${parameter:offset:length}\n Substring Expansion. Expands to up to length characters of\n parameter starting at the character specified by offset.\n[...]\n bash cut" }, { "answer_id": 219416, "author": "Juanma", "author_id": 3730, "author_profile": "https://Stackoverflow.com/users/3730", "pm_score": 5, "selected": false, "text": "stringZ=abcABC123ABCabc\n# 0123456789.....\n# 0-based indexing.\n\necho ${stringZ:0:2} # prints ab\n" }, { "answer_id": 219418, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 4, "selected": false, "text": "${string:position:length}\n" }, { "answer_id": 219427, "author": "Toybuilder", "author_id": 22329, "author_profile": "https://Stackoverflow.com/users/22329", "pm_score": 9, "selected": true, "text": "cut echo \"abcdefg\" | cut -c3-5\n cde\n -cN-M N M" }, { "answer_id": 220464, "author": "camh", "author_id": 23744, "author_profile": "https://Stackoverflow.com/users/23744", "pm_score": 4, "selected": false, "text": "expr(1) expr substr <string> <start-index> <length>\n" }, { "answer_id": 8107620, "author": "ata", "author_id": 378193, "author_profile": "https://Stackoverflow.com/users/378193", "pm_score": 5, "selected": false, "text": "${parameter//substring/replacement}\n${parameter##remove_matching_prefix}\n${parameter%%remove_matching_suffix}\n ${parameter:offset}\n${parameter:offset:length}\n${parameter:offset:length}\n ${parameter:+use this if param is NOT null}\n${parameter:-use this if param is null}\n${parameter:=use this and assign to param if param is null}\n${parameter:?show this error if param is null}\n $(command substitution) man bash" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15595/" ]
219,420
<p>Working through some programming interview challenges I found online, I had to write an algorithm to reverse a const char * and return a pointer to a new char *. I think I have it, but to make it work properly I had to do some wonky stuff - basically having to account for the null-terminating character myself. Somehow I feel this is wrong, but I'm stumped, and I was wondering if someone could help me out:</p> <pre><code>char * reverse(const char * str) { int length = strlen(str); char * reversed_string = new char[length+1]; for(int i = 0; i &lt; length; ++i) { reversed_string[i] = str[(length-1) - i]; } //need to null terminate the string reversed_string[length] = '\0'; return reversed_string; } int main(int argc, char * argv[]) { char * rev_str = reverse("Testing"); cout &lt;&lt; "Your string reversed is this: " &lt;&lt; rev_str &lt;&lt; endl; delete rev_str; rev_str = 0; return 0; } </code></pre>
[ { "answer_id": 219432, "author": "nsayer", "author_id": 13757, "author_profile": "https://Stackoverflow.com/users/13757", "pm_score": 4, "selected": false, "text": "int length = strlen(string);\nfor(int i = 0; i < length/2; i++) {\n char c = string[i];\n string[i] = string[length - i];\n string[length - i] = c;\n}\n string[i] = string[i] ^ string[length - i];\nstring[length - i] = string[i] ^ string[length - i];\nstring[i] = string[i] ^ string[length - i];\n" }, { "answer_id": 219447, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 0, "selected": false, "text": "#include <algorithm>\n#include <iostream>\n#include <cstring>\n\nvoid reverse_string(char *str) { \n char *end = str + strlen(str) - 1;\n while (str < end) {\n std::iter_swap(str++, end--);\n }\n}\n\nint main() {\n char s[] = \"this is a test\";\n reverse_string(s);\n std::cout << \"[\" << s << \"]\" << std::endl;\n}\n" }, { "answer_id": 219449, "author": "Menkboy", "author_id": 29539, "author_profile": "https://Stackoverflow.com/users/29539", "pm_score": 3, "selected": false, "text": "if( string[0] )\n{\n char *end = string + strlen(string)-1;\n while( start < end )\n {\n char temp = *string;\n *string++ = *end;\n *end-- = temp;\n }\n}\n" }, { "answer_id": 219455, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "std::reverse <algorithm> char string str = \"Hello\";\nchar chx[] = \"Hello\";\n\nreverse(str.begin(), str.end());\nreverse(chx, chx + strlen(chx));\n\ncout << str << endl;\ncout << chx << endl;\n char string reverse_string(string const& old) {\n return string(old.rbegin(), old.rend());\n}\n\ncout << reverse_string(\"Hello\") << endl;\n" }, { "answer_id": 219478, "author": "Adam Ness", "author_id": 21973, "author_profile": "https://Stackoverflow.com/users/21973", "pm_score": 0, "selected": false, "text": "char *reverse( const char *source ) {\n int len = strlen( source );\n char *dest = new char[ len + 1 ];\n int i = 0;\n int j = len;\n while( j > 0 ) {\n dest[j--] = src[i++];\n }\n dest[i] = \\0;\n return dest;\n}\n" }, { "answer_id": 219560, "author": "JohnMcG", "author_id": 1674, "author_profile": "https://Stackoverflow.com/users/1674", "pm_score": 0, "selected": false, "text": "char* stringReverse(const char* sInput)\n{\n std::size_t nLen = strlen(sInput);\n std::stack<char> charStack;\n for(std::size_t i = 0; i < nLen; ++i)\n {\n charStack.push(sInput[i]);\n }\n char * result = new char[nLen + 1];\n std::size_t counter = 0;\n while (!charStack.empty())\n {\n result[counter++] = charStack.top();\n charStack.pop();\n }\n result[counter] = '\\0';\n return result;\n}\n" }, { "answer_id": 219638, "author": "agnul", "author_id": 6069, "author_profile": "https://Stackoverflow.com/users/6069", "pm_score": 2, "selected": false, "text": "char *reverse(const char *s) {\n size_t n = strlen(s);\n char *dest = new char[n + 1];\n char *d = (dest + n - 1);\n\n dest[n] = 0;\n while (*s) {\n *d-- = *s++\n }\n\n return dest;\n}\n" }, { "answer_id": 219673, "author": "plinth", "author_id": 20481, "author_profile": "https://Stackoverflow.com/users/20481", "pm_score": 2, "selected": false, "text": "char *dst = reversed_string + length;\n*dst-- = '\\0';\nwhile (*src) {\n *dst-- = *src++;\n}\n" }, { "answer_id": 219926, "author": "user23167", "author_id": 23167, "author_profile": "https://Stackoverflow.com/users/23167", "pm_score": 1, "selected": false, "text": "int length = strlen(string);\nfor(int i = 0; i < length/2; i++) {\n string[i] ^= string[length - i];\n string[length - i] ^= string[i];\n string[i] ^= string[length - i];\n}\n" }, { "answer_id": 220048, "author": "Fernando Miguélez", "author_id": 34880, "author_profile": "https://Stackoverflow.com/users/34880", "pm_score": 2, "selected": false, "text": "/* \n * reverse.c\n *\n * $20081020 23:33 fernando DOT miguelez AT gmail DOT com$\n */\n\n#include <stdint.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n#define MAX_CHARS 10 * 1024 * 1024\n\n/*\n * Borrowed from http://coding.derkeiler.com/Archive/Assembler/comp.lang.asm.x86/2007-03/msg00004.html\n * GNU Compiler syntax\n */\ninline uint32_t bswap(uint32_t val)\n{\n __asm__(\"bswap %0\" : \"=r\" (val) : \"0\" (val));\n return val;\n}\n\nchar * reverseAsm(const char * str)\n{\n int i;\n int length = strlen(str);\n int dwordLength = length/4;\n\n if(length % 4 != 0)\n {\n printf(\"Error: Input string length must be multiple of 4: %d\\n\", length); \n return NULL;\n }\n\n char * reversed_string = (char *) malloc(length+1);\n for(i = 0; i < dwordLength; i++)\n {\n *(((uint32_t *) reversed_string) + dwordLength - i - 1) = bswap(*(((uint32_t *) str) + i));\n }\n\n reversed_string[length] = '\\0';\n\n return reversed_string;\n}\n\nchar * reverse(const char * str)\n{\n int i;\n int length = strlen(str);\n char * reversed_string = (char *) malloc(length+1);\n\n for(i = 0; i < length; ++i)\n {\n reversed_string[i] = str[(length-1) - i];\n }\n\n //need to null terminate the string\n\n reversed_string[length] = '\\0';\n\n return reversed_string;\n}\n\nint main(void)\n{\n int i;\n char *reversed_str, *reversed_str2;\n clock_t start, total;\n char *str = (char *) malloc(MAX_CHARS+1);\n\n str[MAX_CHARS] = '\\0';\n\n srand(time(0));\n\n for(i = 0; i < MAX_CHARS; i++)\n {\n str[i] = 'A' + rand() % 26; \n }\n\n start = clock();\n reversed_str = reverse(str);\n total = clock() - start;\n if(reversed_str != NULL)\n {\n printf(\"Total clock ticks to reverse %d chars with pure C method: %d\\n\", MAX_CHARS, total); \n free(reversed_str);\n }\n start = clock();\n reversed_str2 = reverseAsm(str);\n total = clock() - start;\n if(reversed_str2 != NULL)\n {\n printf(\"Total clock ticks to reverse %d chars with ASM+C method: %d\\n\", MAX_CHARS, total); \n free(reversed_str2);\n }\n\n free(str);\n\n return 0;\n}\n fer@fernando /cygdrive/c/tmp$ ./reverse.exe\nTotal clock ticks to reverse 10485760 chars with pure C method: 221\nTotal clock ticks to reverse 10485760 chars with ASM+C method: 140\n" }, { "answer_id": 220096, "author": "Andrew Johnson", "author_id": 5109, "author_profile": "https://Stackoverflow.com/users/5109", "pm_score": 0, "selected": false, "text": "static inline void\nbyteswap (char *a, char *b)\n{\n *a = *a^*b;\n *b = *a^*b;\n *a = *a^*b;\n}\n\nvoid\nreverse (char *string)\n{\n char *end = string + strlen(string) - 1;\n\n while (string < end) {\n byteswap(string++, end--);\n }\n}\n" }, { "answer_id": 220125, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "int length = strlen(string);\nfor(int i = 0; i < length/2; i++) {\n string[i] ^= string[length - i] ^= string[i] ^= string[length - i];\n}\n" }, { "answer_id": 220620, "author": "mhawke", "author_id": 21945, "author_profile": "https://Stackoverflow.com/users/21945", "pm_score": 0, "selected": false, "text": "strlen() const char *" }, { "answer_id": 224532, "author": "Lodle", "author_id": 23339, "author_profile": "https://Stackoverflow.com/users/23339", "pm_score": 0, "selected": false, "text": "char * reverse(const char * str)\n{\n if (!str)\n return NULL;\n\n int length = strlen(str);\n char * reversed_string = new char[length+1];\n\n for(int i = 0; i < length/2; ++i)\n {\n reversed_string[i] = str[(length-1) - i];\n reversed_string[(length-1) - i] = str[i];\n }\n //need to null terminate the string\n reversed_string[length] = '\\0';\n\n return reversed_string;\n\n}\n" }, { "answer_id": 1540738, "author": "Marius", "author_id": 174650, "author_profile": "https://Stackoverflow.com/users/174650", "pm_score": 2, "selected": false, "text": "string[i] ^= string[length - i] ^= string[i] ^= string[length - i];\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
219,425
<p>Is contract to interface as object is to class?</p> <p>What is the need to differentiate identical things like this, from the code to the executing code? I sort of get the idea behind naming a class a class and the instantiated executing class an object, but overall, is that the only reason for these semi-redundant terms?</p>
[ { "answer_id": 219493, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 3, "selected": false, "text": "int" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29345/" ]
219,431
<p>during beta testing we discovered connection pooling error messages . Therefore I have been going through the code and closing down the SqlDataReader objects wherever they have been left unclosed. What I need to know is how to close a datareader (or if there is a need at all to close) that is specified in the SelectStatement attribute of the SqlDataSource or ObjectDataSource tags. Could there be connection leak if they are not handled?</p> <p>Thanks in advance !</p>
[ { "answer_id": 219490, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": false, "text": "SqlDataSource ObjectDataSource Close() using ObjectDataSource" }, { "answer_id": 220046, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": " using (SqlConnection connection = new SqlConnection(connectionString))\n {\n try\n {\n SqlCommand command = connection.CreateCommand();\n command.CommandText = ...\n\n connection.Open();\n using (SqlDataReader reader = command.ExecuteReader())\n {\n do\n {\n while (reader.Read())\n {\n ... handle each row ...\n }\n } while (reader.NextResult());\n }\n }\n catch (Exception ex)\n {\n ... error handling ...\n }\n finally\n {\n if (connection != null && connection.State == ConnectionState.Open)\n {\n connection.Close();\n }\n }\n }\n" }, { "answer_id": 220398, "author": "Aamir", "author_id": 262613, "author_profile": "https://Stackoverflow.com/users/262613", "pm_score": -1, "selected": false, "text": "SqlDataReader MySelectMethod(){\n SqlDataReader dr = null;\n try{\n dr = DBObject.GetDataReader();\n return dr;\n }\n finally{\n dr.Close();\n }\n}\n" }, { "answer_id": 1581703, "author": "Misha", "author_id": 7557, "author_profile": "https://Stackoverflow.com/users/7557", "pm_score": 2, "selected": false, "text": " using (var cmd = ... ))\n {\n using (var reader = (DbDataReader) cmd.ExecuteReader())\n {\n try\n {\n ConsumeData(reader); // may throw\n }\n catch(Exception)\n {\n cmd.Cancel();\n throw;\n }\n }\n }\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/262613/" ]
219,434
<p>What query can return the names of all the stored procedures in a SQL Server database</p> <p>If the query could exclude system stored procedures, that would be even more helpful.</p>
[ { "answer_id": 219440, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 1, "selected": false, "text": "select * \n from dbo.sysobjects\n where xtype = 'P'\n and status > 0\n" }, { "answer_id": 219441, "author": "Kevin", "author_id": 19038, "author_profile": "https://Stackoverflow.com/users/19038", "pm_score": 7, "selected": false, "text": "SELECT name, \n type\n FROM dbo.sysobjects\n WHERE (type = 'P')\n" }, { "answer_id": 219460, "author": "Mike", "author_id": 1573, "author_profile": "https://Stackoverflow.com/users/1573", "pm_score": 5, "selected": false, "text": "select * \n from information_schema.routines \n where routine_type = 'PROCEDURE'\n" }, { "answer_id": 219510, "author": "Dave_H", "author_id": 17109, "author_profile": "https://Stackoverflow.com/users/17109", "pm_score": 10, "selected": true, "text": "information_schema SELECT * \n FROM DatabaseName.INFORMATION_SCHEMA.ROUTINES\n WHERE ROUTINE_TYPE = 'PROCEDURE'\n SELECT * \n FROM [master].INFORMATION_SCHEMA.ROUTINES\n WHERE ROUTINE_TYPE = 'PROCEDURE' \n AND LEFT(ROUTINE_NAME, 3) NOT IN ('sp_', 'xp_', 'ms_')\n" }, { "answer_id": 219561, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "INFORMATION_SCHEMA SELECT *\n FROM sys.objects\n WHERE objectproperty(object_id, N'IsMSShipped') = 0\n AND objectproperty(object_id, N'IsProcedure') = 1\n" }, { "answer_id": 219565, "author": "cbeuker", "author_id": 15952, "author_profile": "https://Stackoverflow.com/users/15952", "pm_score": 3, "selected": false, "text": "select *\n from sys.procedures\n where is_ms_shipped = 0\n" }, { "answer_id": 12858086, "author": "NeverHopeless", "author_id": 751527, "author_profile": "https://Stackoverflow.com/users/751527", "pm_score": 3, "selected": false, "text": "select * from sys.all_objects where type='p' and is_ms_shipped=0\n" }, { "answer_id": 13698511, "author": "Reza Zendehboudi", "author_id": 1859377, "author_profile": "https://Stackoverflow.com/users/1859377", "pm_score": 0, "selected": false, "text": "Use [YourDataBase]\n\nEXEC sp_tables @table_type = \"'PROCEDURE'\" \nEXEC sp_tables @table_type = \"'TABLE'\"\nEXEC sp_tables @table_type = \"'VIEW'\" \n SELECT * FROM information_schema.tables\nSELECT * FROM information_schema.VIEWS\n" }, { "answer_id": 21876363, "author": "Narendra Sharma", "author_id": 3243879, "author_profile": "https://Stackoverflow.com/users/3243879", "pm_score": 4, "selected": false, "text": "SELECT * FROM sys.procedures\n" }, { "answer_id": 27623196, "author": "LostCajun", "author_id": 4389023, "author_profile": "https://Stackoverflow.com/users/4389023", "pm_score": 1, "selected": false, "text": "use << database name >>\ngo\n\ndeclare @aQuery nvarchar(1024);\ndeclare @spName nvarchar(64);\ndeclare allSP cursor for\nselect p.name from sys.procedures p where p.type_desc = 'SQL_STORED_PROCEDURE' order by p.name;\nopen allSP;\nfetch next from allSP into @spName;\nwhile (@@FETCH_STATUS = 0)\nbegin\n set @aQuery = 'sp_helptext [Extract.' + @spName + ']';\n exec sp_executesql @aQuery;\n fetch next from allSP;\nend;\nclose allSP;\ndeallocate allSP;\n" }, { "answer_id": 27842463, "author": "HaveNoDisplayName", "author_id": 2686013, "author_profile": "https://Stackoverflow.com/users/2686013", "pm_score": 1, "selected": false, "text": "Select * \nFROM sys.procedures where [type] = 'P' \n AND is_ms_shipped = 0 \n AND [name] not like 'sp[_]%diagram%'\n" }, { "answer_id": 27919038, "author": "MovGP0", "author_id": 601990, "author_profile": "https://Stackoverflow.com/users/601990", "pm_score": 4, "selected": false, "text": "SELECT name, type\nFROM dbo.sysobjects\nWHERE type IN (\n 'P', -- stored procedures\n 'FN', -- scalar functions \n 'IF', -- inline table-valued functions\n 'TF' -- table-valued functions\n)\nORDER BY type, name\n" }, { "answer_id": 40074774, "author": "The_Coder", "author_id": 5142270, "author_profile": "https://Stackoverflow.com/users/5142270", "pm_score": 1, "selected": false, "text": "select specific_name\nfrom information_schema.routines\nwhere routine_type = 'PROCEDURE';\n" }, { "answer_id": 42396905, "author": "Ardalan Shahgholi", "author_id": 2063547, "author_profile": "https://Stackoverflow.com/users/2063547", "pm_score": 4, "selected": false, "text": " SELECT \n *\n FROM sys.procedures;\n SELECT \n * \n FROM information_schema.routines \n WHERE ROUTINE_TYPE = 'PROCEDURE' \n CREATE TABLE #ListOfSPs \n (\n DBName varchar(100), \n [OBJECT_ID] INT,\n SPName varchar(100)\n )\n\n EXEC sp_msforeachdb 'USE [?]; INSERT INTO #ListOfSPs Select ''?'', Object_Id, Name FROM sys.procedures'\n\n SELECT \n * \n FROM #ListOfSPs\n" }, { "answer_id": 42489206, "author": "BaffledBill", "author_id": 4462742, "author_profile": "https://Stackoverflow.com/users/4462742", "pm_score": 2, "selected": false, "text": "use <<databasename>>\ngo\n\ndeclare @aQuery nvarchar(1024);\ndeclare @spName nvarchar(64);\ndeclare allSP cursor for\n select p.name \n from sys.procedures p \n where p.type_desc = 'SQL_STORED_PROCEDURE' \n and LEFT(p.name,3) NOT IN ('sp_','xp_','ms_')\n order by p.name;\nopen allSP;\nfetch next from allSP into @spName;\nwhile (@@FETCH_STATUS = 0)\nbegin\n set @aQuery = 'sp_helptext [' + @spName + ']';\n exec sp_executesql @aQuery;\n fetch next from allSP into @spName;\nend;\nclose allSP;\ndeallocate allSP;\n" }, { "answer_id": 45021288, "author": "Lorena Pita", "author_id": 5307277, "author_profile": "https://Stackoverflow.com/users/5307277", "pm_score": 3, "selected": false, "text": "select name,type,type_desc\nfrom sys.objects\nwhere type in ('V','P')\norder by name,type\n" }, { "answer_id": 48549349, "author": "Ray Koren", "author_id": 4352494, "author_profile": "https://Stackoverflow.com/users/4352494", "pm_score": 3, "selected": false, "text": "SELECT SPECIFIC_NAME \nFROM YOUR_DB_NAME.information_schema.routines \nWHERE routine_type = 'PROCEDURE'\n" }, { "answer_id": 49272619, "author": "Chandan Ravandur N", "author_id": 9490070, "author_profile": "https://Stackoverflow.com/users/9490070", "pm_score": 0, "selected": false, "text": "select * from DatabaseName.INFORMATION_SCHEMA.ROUTINES where routine_type = 'PROCEDURE'\n\nselect * from DatabaseName.INFORMATION_SCHEMA.ROUTINES where routine_type ='procedure' and left(ROUTINE_NAME,3) not in('sp_', 'xp_', 'ms_')\n\n\n SELECT name, type FROM dbo.sysobjects\n WHERE (type = 'P')\n" }, { "answer_id": 51018866, "author": "Mohsen", "author_id": 1970972, "author_profile": "https://Stackoverflow.com/users/1970972", "pm_score": 2, "selected": false, "text": "SELECT o. object_id,o.name AS name,o.type_desc,m.definition,schemas.name scheamaName\nFROM sys.sql_modules m \n INNER JOIN sys.objects o ON m.object_id=o.OBJECT_ID\n INNER JOIN sys.schemas ON schemas.schema_id = o.schema_id\n WHERE [TYPE]='p'\n" }, { "answer_id": 53813524, "author": "user1556937", "author_id": 1556937, "author_profile": "https://Stackoverflow.com/users/1556937", "pm_score": 0, "selected": false, "text": "USE DBNAME\n\nselect ROUTINE_NAME from information_schema.routines \nwhere routine_type = 'PROCEDURE'\n\n\nGO \n" }, { "answer_id": 55048379, "author": "Alexandru-Codrin Panaite", "author_id": 10293835, "author_profile": "https://Stackoverflow.com/users/10293835", "pm_score": 1, "selected": false, "text": "select sch.name As [Schema], obj.name AS [Stored Procedure], code.definition AS [Code] from sys.objects as obj\n join sys.sql_modules as code on code.object_id = obj.object_id\n join sys.schemas as sch on sch.schema_id = obj.schema_id\n where obj.type = 'P'\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
219,470
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/53629/history-of-changes-to-a-particular-line-of-code-in-subversion">History of changes to a particular line of code in Subversion?</a> </p> </blockquote> <p>Using SVN and/or Tortoise SVN (or any other SVN tool, really), is it possible to view the history for a specific line of a file?</p> <p>Recently I've had several occurrences of coming across a line in a file and wanting to find the log entry associated with its creation (either to determine how old the line of code was, or to get a larger context for why it was added).</p> <p>Right now I'm doing this by hand. I can display the log for the file, go back a ways, and see if the line in question is present. If it is, I go back further. If it isn't, I go look at a more recent revision. Repeat until the revision where the change was made is found.</p> <p>Needless to say, this process is awkward at best, especially for particularly old files. Does anyone know of an automated method of accomplishing this?</p>
[ { "answer_id": 219471, "author": "Menkboy", "author_id": 29539, "author_profile": "https://Stackoverflow.com/users/29539", "pm_score": 1, "selected": true, "text": "svn blame" }, { "answer_id": 219513, "author": "heckj", "author_id": 19477, "author_profile": "https://Stackoverflow.com/users/19477", "pm_score": 2, "selected": false, "text": "svn blame -r REV#" }, { "answer_id": 219613, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 1, "selected": false, "text": "svn annotate svn blame" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16911/" ]
219,475
<p>I'm working with a client that needs to generate millions of the alphanumeric codes used in magazine scratch-off cards, bottlecap prizes, and so on. They have to be short enough to print on a cap, they want to make sure that ambiguous characters like 1 and I, 0 and O, etc. are not included, and they have to be explicitly stored for future use -- we can't just have an algorithm that determines 'validity' when someone tries to redeem one. Finally, they want to make sure that the codes are randomly distributed inside of a large "code space" so that people can't just guess additional codes by walking through the alphabet.</p> <p>Are there any pointers towards reasonably efficient algorithms for generating these kinds of code sets? I've scratched a few out on the back of an envelope, but this problem smells like a trap for the unwary.</p>
[ { "answer_id": 219557, "author": "ojrac", "author_id": 20760, "author_profile": "https://Stackoverflow.com/users/20760", "pm_score": 5, "selected": true, "text": "$last = null;\nwhile ($current = getnext()) {\n if ($last == $current) {\n push($toDelete, $current);\n }\n $last = $current;\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19411/" ]
219,482
<p>If anyone has experience using Oracle text (<code>CTXSYS.CONTEXT</code>), I'm wondering how to handle user input when the user wants to search for names that may contain an apostrophe.</p> <p>Escaping the ' seems to work in some cases, but not for 's at the end of the word - s is in the list of stop words, and so seems to get removed.</p> <p>We currently change simple query text (i.e. anything that's just letters) to <code>%text%</code>, for example: </p> <pre><code>contains(field, :text) &gt; 0 </code></pre> <p>A search for <strong>O'Neil</strong> works, but <strong>Joe's</strong> doesn't.</p> <p>Has anyone using Oracle Text dealt with this issue?</p>
[ { "answer_id": 41787290, "author": "Dima Korobskiy", "author_id": 534217, "author_profile": "https://Stackoverflow.com/users/534217", "pm_score": 1, "selected": false, "text": "PARAMETERS('STOPLIST ctxsys.empty_stoplist') \\ {input}" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4782/" ]
219,519
<p>What I'm looking for is a basic equivalent of JavaScript's <code>Array::join()</code> whereby you pass in a separator character and uses that in its return string of all the subscripts. I could certainly write my own function using a <code>StringBuilder</code> or whatnot, but there <em>must</em> be something built into the .NET BCL.</p> <p>EDIT: Array of <em>anything</em>, not necessarily <code>string</code> or <code>char</code>. I'd prefer the method to simply call <code>ToString()</code> on each subscript <code>object</code>. <code>String.Join()</code> is great except that you pass it an array of strings.</p>
[ { "answer_id": 219521, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": true, "text": "String.Join() char sep = GetSeparatorChar();\nobject[] toJoin = GetToJoin();\nstring joined = toJoin.Aggregate((x,y) => x.ToString()+sep.ToString()+y.ToString());\n" }, { "answer_id": 219526, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 0, "selected": false, "text": "\nchar sep = GetSeparatorChar();\nstring[] toJoin = GetToJoin();\nstring joined = toJoin.Aggregate((x,y) => x+sep.ToString()+y);\n" }, { "answer_id": 219567, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "IEnumerable<string> string[]" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9642/" ]
219,525
<p>I remember working on a project with a group of developers and they always wanted static html text to be inside of an out tag (<code>&lt;c:out value="words" /&gt;</code>). I don't remember why this was the case.</p> <p>Is this really a best practice when building jsp pages? What are the advantages/disadvantages of such an approach?</p>
[ { "answer_id": 219546, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 2, "selected": false, "text": "c:out <c:out value=\"Hello ${user.firstName} ${user.lastName}\"/>\n" }, { "answer_id": 219657, "author": "MetroidFan2002", "author_id": 8026, "author_profile": "https://Stackoverflow.com/users/8026", "pm_score": 5, "selected": true, "text": "${dynamic} c:out HTML <> c:out" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17337/" ]
219,530
<p>I've been searching around and haven't found any reference to tools that can create Safari's webarchive format.</p> <p>Does anyone have pointers to code for creating this format, or at least a format reference documentation?</p> <p>Ideally I'd like to build a tool that takes a directory and splits out a webarchive, for loading into a iPhone.</p>
[ { "answer_id": 238676, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 4, "selected": true, "text": ".webarchive Mac-PropertyList" }, { "answer_id": 3334276, "author": "Ortwin Gentz", "author_id": 235297, "author_profile": "https://Stackoverflow.com/users/235297", "pm_score": 2, "selected": false, "text": "textutil -convert webarchive whatever.html\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2846/" ]
219,547
<p>I have a python script that is a http-server: <a href="http://paste2.org/p/89701" rel="nofollow noreferrer">http://paste2.org/p/89701</a>, when benchmarking it against ApacheBench (ab) with a concurrency level (-c switch) that is lower then or equal to the value i specified in the socket.listen()-call in the sourcecode everything works fine, but as soon as put the concurrency level in apache bench above the value in the socket.listen()-call performance drops through the floor, some example:</p> <ul> <li>socket.listen(<strong>10</strong>) and ab -n 50 -c <strong>10</strong> <a href="http://localhost/" rel="nofollow noreferrer">http://localhost/</a> = <strong>1200req/s</strong></li> <li>socket.listen(<strong>10</strong>) and ab -n 50 -c <strong>11</strong> <a href="http://localhost/" rel="nofollow noreferrer">http://localhost/</a> = <strong>40req/s</strong></li> <li>socket.listen(<strong>100</strong>) and ab -n 5000 -c <strong>100</strong> <a href="http://localhost/" rel="nofollow noreferrer">http://localhost/</a> = <strong>1000req/s</strong></li> <li>socket.listen(<strong>100</strong>) and ab -n 5000 -c <strong>101</strong> <a href="http://localhost/" rel="nofollow noreferrer">http://localhost/</a> = <strong>32req/s</strong></li> </ul> <p>Nothing changes in the code between the two calls, I can’t figure out what is wrong - been at this problem for one day now. Also note that: The multiplexing version of the same code (I wrote to compare to the threaded version) works FINE no matter what socket.listen() is set to or what the concurrency (-c switch) in apache is set to.</p> <p><em>I've spent a day on IRC/python docs, posted on comp.lang.python and on my blog - I can't find ANYONE that even has an idea what could be wrong. Help me!</em></p>
[ { "answer_id": 219671, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 4, "selected": true, "text": "import thread, socket, Queue\n\nconnections = Queue.Queue()\nnum_threads = 10\nbacklog = 10\n\ndef request():\n while 1:\n conn = connections.get()\n data = ''\n while '\\r\\n\\r\\n' not in data:\n data += conn.recv(4048)\n conn.sendall('HTTP/1.1 200 OK\\r\\n\\r\\nHello World')\n conn.close()\n\nif __name__ == '__main__':\n for _ in range(num_threads):\n thread.start_new_thread(request, ())\n\n acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n acceptor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n acceptor.bind(('', 1234))\n acceptor.listen(backlog)\n while 1:\n conn, addr = acceptor.accept()\n connections.put(conn)\n ab -n 10000 -c 10 http://127.0.0.1:1234/ --> 8695.03 [#/sec]\nab -n 10000 -c 11 http://127.0.0.1:1234/ --> 8529.41 [#/sec]\n" }, { "answer_id": 219824, "author": "Florian Bösch", "author_id": 19435, "author_profile": "https://Stackoverflow.com/users/19435", "pm_score": 2, "selected": false, "text": "import socket, Queue, select\n\nclass Request(object):\n def __init__(self, conn):\n self.conn = conn\n self.fileno = conn.fileno\n self.perform = self._perform().next\n\n def _perform(self):\n data = self.conn.recv(4048)\n while '\\r\\n\\r\\n' not in data:\n msg = self.conn.recv(4048)\n if msg:\n data += msg\n yield\n else:\n break\n reading.remove(self)\n writing.append(self)\n\n data = 'HTTP/1.1 200 OK\\r\\n\\r\\nHello World'\n while data:\n sent = self.conn.send(data)\n data = data[sent:]\n yield\n writing.remove(self)\n self.conn.close()\n\nclass Acceptor:\n def __init__(self):\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n sock.bind(('', 1234))\n sock.listen(10)\n self.sock = sock\n self.fileno = sock.fileno\n\n def perform(self):\n conn, addr = self.sock.accept()\n reading.append(Request(conn))\n\nif __name__ == '__main__':\n reading = [Acceptor()]\n writing = list()\n\n while 1:\n readable, writable, error = select.select(reading, writing, [])\n for action in readable + writable:\n try: action.perform()\n except StopIteration: pass\n ab -n 10000 -c 10 http://127.0.0.1:1234/ --> 16822.13 [#/sec]\nab -n 10000 -c 11 http://127.0.0.1:1234/ --> 15704.41 [#/sec]\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219547", "https://Stackoverflow.com", "https://Stackoverflow.com/users/452521/" ]
219,559
<p>I have a table of data, and I allow people to add meta data to that table.</p> <p>I give them an interface that allows them to treat it as though they're adding extra columns to the table their data is stored in, but I'm actually storing the data in another table.</p> <pre><code>Data Table DataID Data Meta Table DataID MetaName MetaData </code></pre> <p>So if they wanted a table that stored the data, the date, and a name, then I'd have the data in the data table, and the word "Date" in metaname, and the date in MetaData, and another row in the meta table with "Name" in metaname and the name in metadata. </p> <p>I now need a query that takes the information from these tables and presents it as though coming from a single table with the two additional columns "Data" and "Name" so to the customer it would look like there's a single table with their custom columns:</p> <pre><code>MyTable Data Date Name </code></pre> <p>Or, in other words, how do I go from here:</p> <pre><code>Data Table DataID Data 1 Testing! 2 Hello, World! Meta Table DataID MetaName MetaData 1 Date 20081020 1 Name adavis 2 Date 20081019 2 Name mdavis </code></pre> <p>To here:</p> <pre><code>MyTable Data Date Name Testing! 20081020 adavis Hello, World! 20081019 mdavis </code></pre> <p>Years ago when I did this in MySQL using PHP, I did two queries, the first to get the extra meta data, the second to join them all together. I'm hoping that modern databases have alternate methods of dealing with this.</p> <p>Related to option 3 of <a href="https://stackoverflow.com/questions/218848/design-decision-dynamically-adding-data-question#218872">this question</a>.</p> <p>-Adam</p>
[ { "answer_id": 219578, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 1, "selected": false, "text": "SELECT DataTable.Data AS Data, MetaTable.MetaData AS Date, MetaTable.MetaName AS Name\nFROM DataTable, MetaTable\nWHERE DataTable.DataID = MetaTable.DataID\n" }, { "answer_id": 219580, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "SQL SELECT [Data Table].*\n ,[MyTable Date].MetaData\n ,[MyTable Name].MetaData\nFROM [Data Table]\nLEFT JOIN [MyTable] AS [MyTable Date]\n ON [MyTable Date].DataID = [Data Table].DataID\n AND [MyTable Date].MetaName = 'Date'\nLEFT JOIN [MyTable] AS [MyTable Name]\n ON [MyTable Name].DataID = [Data Table].DataID\n AND [MyTable Name].MetaName = 'Name'\n DECLARE @sql AS varchar(max)\nDECLARE @select_list AS varchar(max)\nDECLARE @join_list AS varchar(max)\nDECLARE @CRLF AS varchar(2)\nDECLARE @Tab AS varchar(1)\n\nSET @CRLF = CHAR(13) + CHAR(10)\nSET @Tab = CHAR(9)\n\nSELECT @select_list = COALESCE(@select_list, '')\n + @Tab + ',[MyTable_' + PIVOT_CODE + '].[MetaData]' + @CRLF\n ,@join_list = COALESCE(@join_list, '')\n + 'LEFT JOIN [MyTable] AS [MyTable_' + PIVOT_CODE + ']' + @CRLF\n + @Tab + 'ON [MyTable_' + PIVOT_CODE + '].DataID = [DataTable].DataID' + @CRLF\n + @Tab + 'AND [MyTable_' + PIVOT_CODE + '].MetaName = ''' + PIVOT_CODE + '''' + @CRLF\nFROM (\n SELECT DISTINCT MetaName AS PIVOT_CODE\n FROM [MyTable]\n) AS PIVOT_CODES\n\nSET @sql = 'SELECT [DataTable].*' + @CRLF\n + @select_list\n + 'FROM [DataTable]' + @CRLF\n + @join_list\nPRINT @sql\n--EXEC (@sql)\n CASE" }, { "answer_id": 219601, "author": "Jeff Fritz", "author_id": 29156, "author_profile": "https://Stackoverflow.com/users/29156", "pm_score": 3, "selected": true, "text": "DECLARE @Data TABLE (\n DataID INT IDENTITY(1,1) PRIMARY KEY,\n Data VARCHAR(MAX)\n)\n\nDECLARE @Meta TABLE (\n DataID INT ,\n MetaName VARCHAR(MAX),\n MetaData VARCHAR(MAX)\n)\n\nINSERT INTO @Data\nSELECT 'Data'\n\nINSERT INTO @Meta\nSELECT 1, 'Date', CAST(GetDate() as VARCHAR(20))\nUNION\nSELECT 1, 'Name', 'Joe Test'\n\nSELECT * FROM @Data\n\nSELECT * FROM @Meta\n\nSELECT \n D.DataID,\n D.Data,\n MAX(CASE MetaName WHEN 'Date' THEN MetaData ELSE NULL END) as Date,\n MAX(CASE MetaName WHEN 'Name' THEN MetaData ELSE NULL END) as Name\nFROM\n @Meta M\nJOIN @Data D ON M.DataID = D.DataID \nGROUP BY\n D.DataID,\n D.Data\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
219,569
<p>I need to store a url in a MySQL table. What's the best practice for defining a field that will hold a URL with an undetermined length?</p>
[ { "answer_id": 219579, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 5, "selected": false, "text": "VARCHAR(512) TEXT CLOB VARCHAR" }, { "answer_id": 219582, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 4, "selected": false, "text": "varchar(max) varchar(65535)" }, { "answer_id": 13950357, "author": "sohaiby", "author_id": 1837838, "author_profile": "https://Stackoverflow.com/users/1837838", "pm_score": 2, "selected": false, "text": "varchar (65535)" }, { "answer_id": 25731768, "author": "brokethebuildagain", "author_id": 1235702, "author_profile": "https://Stackoverflow.com/users/1235702", "pm_score": 4, "selected": false, "text": "TEXT VARCHAR VARCHAR VARCHAR(500) safe.mn http://stackoverflow.com/q/219569/1235702 stackoverflow.com/q/21956... http://ex.ampl/e1234" }, { "answer_id": 34352863, "author": "Flavio Tordini", "author_id": 927729, "author_profile": "https://Stackoverflow.com/users/927729", "pm_score": 4, "selected": false, "text": "VARCHAR(512) CHARACTER SET 'ascii' COLLATE 'ascii_general_ci' NOT NULL\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22325/" ]
219,570
<p>I was asked for a comprehensive breakdown on space used within a specific database. I know I can use <em>sys.dm_db_partition_stats</em> in SQL Server 2005 to figure out how much space each <em>table</em> in a database is using, but is there any way to determine the individual and total size of the <em>stored procedures</em> in a database? (Short of opening each one and counting the characters, of course.)</p> <p>Total space used by stored procs is not likely to be significant (compared to actual <em>data</em>), but with hundreds of them, it could add up.</p>
[ { "answer_id": 219675, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 2, "selected": false, "text": "--create a temp table to hold the data\ncreate table ##sptext (sptext varchar(1000))\ngo\n\n--generate the code to insert the full text of your sprocs\nselect 'insert into ##sptext (sptext) exec sp_helptext '''+specific_name+''';'\nfrom information_schema.routines \nwhere routine_type = 'PROCEDURE'\ngo\n\n/*Copy the output back to your query analyzer and run it*/\n\n--now sum the results \nselect sum(len(sptext))\nfrom ##sptext\n" }, { "answer_id": 219740, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 5, "selected": true, "text": ";WITH ROUTINES AS (\n -- CANNOT use INFORMATION_SCHEMA.ROUTINES because of 4000 character limit\n SELECT o.type_desc AS ROUTINE_TYPE\n ,o.[name] AS ROUTINE_NAME\n ,m.definition AS ROUTINE_DEFINITION\n FROM sys.sql_modules AS m\n INNER JOIN sys.objects AS o\n ON m.object_id = o.object_id\n)\nSELECT SUM(LEN(ROUTINE_DEFINITION))\nFROM ROUTINES\n" }, { "answer_id": 41878293, "author": "StuKay", "author_id": 7084741, "author_profile": "https://Stackoverflow.com/users/7084741", "pm_score": 2, "selected": false, "text": "SELECT Type,\n SUM(Chars) SizeChars,\n SUM(Bytes) SizeBytes,\n SUM(Bytes) / 1024. SizeKB,\n CAST(SUM(Bytes) / 1024 AS VARCHAR) + '.' + CAST(SUM(Bytes) % 1024 AS VARCHAR) SizeKBRemBytes\nFROM\n(\nSELECT o.type_desc Type, \n LEN(sm.definition) Chars,\n DATALENGTH(sm.definition) Bytes\n FROM sys.sql_modules sm\n JOIN sys.objects o ON sm.object_id = o.object_id\n) x\nGROUP BY Type\nORDER BY Type\n" }, { "answer_id": 56776691, "author": "Konstantin Taranov", "author_id": 2298061, "author_profile": "https://Stackoverflow.com/users/2298061", "pm_score": 2, "selected": false, "text": "/*\n<documentation>\n <summary>Count size in bytes veiws, triggers, procedures and function in database.</summary>\n <returns>1 data set: RoutinType, SUM LENGTH of objects, SUM DATALENGTH.</returns>\n <issues>No</issues>\n <author>Cade Roux</author>\n <created>2008-10-20</created>\n <modified>2019-06-26 by Konstantin Taranov</modified>\n <version>1.0</version>\n <sourceLink>https://github.com/ktaranov/sqlserver-kit/blob/master/Scripts/Objects_Size_In_Database.sql</sourceLink>\n <originalLink>https://stackoverflow.com/a/219740/2298061</originalLink>\n</documentation>\n*/\n\nSET NOCOUNT ON;\nSET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;\n\nWITH CTE_Routine AS (\n /* Can not use INFORMATION_SCHEMA.ROUTINES because of 4000 character limit */\n SELECT o.type_desc AS RoutineType\n , o.[name] AS RoutineName\n , m.[definition] AS RoutineDefinition\n FROM sys.sql_modules AS m \n INNER JOIN sys.objects AS o ON m.object_id = o.object_id\n)\nSELECT RoutineType\n , SUM(LEN(RoutineDefinition)) AS RoutineLen\n /* DATALENGTH for counting trailing space in the end of objects definitions */\n , SUM(DATALENGTH(RoutineDefinition)) / 2 AS RoutineDatalength\nFROM CTE_Routine\nGROUP BY RoutineType;\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21398/" ]
219,581
<p>I'm looking to add a tooltip to each row in a bound datagrid in vb.net winforms. How can this be done?</p>
[ { "answer_id": 219771, "author": "Ricardo Villamil", "author_id": 19314, "author_profile": "https://Stackoverflow.com/users/19314", "pm_score": 2, "selected": true, "text": "System.Windows.Forms.ToolTip formToolTip = new System.Windows.Forms.ToolTip();\nformToolTip .SetToolTip(item, \"Row Tooltip\");\n item" }, { "answer_id": 278498, "author": "Russ", "author_id": 32772, "author_profile": "https://Stackoverflow.com/users/32772", "pm_score": 0, "selected": false, "text": "row.cells[indexof].ToolTipText= \"tootip here\".\n foreach (DataGridViewCell cell in row.Cells)\n {\n cell.ToolTipText = \"tooltip here\";\n }\n" }, { "answer_id": 1198722, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "If TypeOf control Is TabControl Then\n For Each control1 In control.Controls\n If TypeOf control1 Is TabPage Then\n strControlText = fnGetLanguage(control1.Text)\n End If\n For Each control2 In control1.Controls\n If TypeOf control2 Is label Then\n strControlText = control2.Text\n ' strToolTipText = ToolTip.GetToolTip(control2)\n If strControlText.Contains(\"*\") Then\n strDizi = Split(strControlText, \" \")\n strControlText = fnGetLanguage(strDizi(0))\n Else\n strControlText = fnGetLanguage(control2.Text)\n End If\n ElseIf TypeOf control2 Is DataGridView Then\n For i = 0 To control2.ColumnCount - 1\n strControlText = control2.Columns(i).HeaderText\n strControlText = fnGetLanguage(strControlText)\n Next\n ElseIf TypeOf control2 Is ComboBox Then\n strControlText = control2.Text\n 'strToolTipText = ToolTip.GetToolTip(control2)\n If control2.DataSource Is Nothing Then\n For i = 0 To control2.Items.Count - 1\n strControlText = control2.Items(i)\n strControlText = fnGetLanguage(strControlText)\n Next\n Else\n For i = 0 To control2.Items.Count - 1\n strControlText = control2.Items(i).ToString\n strControlText = fnGetLanguage(strControlText)\n Next\n End If\n End If\n Next\n Next\nEnd If\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3259/" ]
219,585
<p>Is there a way to include all the jar files within a directory in the classpath?</p> <p>I'm trying <code>java -classpath lib/*.jar:. my.package.Program</code> and it is not able to find class files that are certainly in those jars. Do I need to add each jar file to the classpath separately? </p>
[ { "answer_id": 219663, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<path id=\"base.class.path\">\n <pathelement path=\"${resources.dir}\"/>\n <fileset dir=\"${extensions.dir}\" includes=\"*.jar\" />\n <fileset dir=\"${lib.dir}\" includes=\"*.jar\"/>\n</path>\n" }, { "answer_id": 219706, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 6, "selected": false, "text": "myapp.jar Manifest.mf java -jar myapp.jar jar lib Manifest-Version: 1.0\nImplementation-Title: myapp\nImplementation-Version: 1.0.1\nClass-Path: lib/dep1.jar lib/dep2.jar\n" }, { "answer_id": 219801, "author": "basszero", "author_id": 287, "author_profile": "https://Stackoverflow.com/users/287", "pm_score": 10, "selected": false, "text": "\" * *.jar java -cp \"Test.jar;lib/*\" my.package.MainClass java -cp \"Test.jar:lib/*\" my.package.MainClass : ; bash lib java -cp \"$(printf %s: lib/*.jar)\" -jar * .jar .JAR foo/* * * foo;foo/* foo/*;foo foo foo foo/* foo foo/bar foo/baz foo a.jar b.jar c.jar foo/* foo/a.jar;foo/b.jar;foo/c.jar java.class.path CLASSPATH -classpath -cp Class-Path jar-manifest" }, { "answer_id": 344818, "author": "ParseTheData", "author_id": 36268, "author_profile": "https://Stackoverflow.com/users/36268", "pm_score": 2, "selected": false, "text": "setenv CLASSPATH /User/username/newfolder/jarfile.jar:jarfile2.jar:jarfile3.jar:.\n" }, { "answer_id": 1275467, "author": "davorp", "author_id": 41939, "author_profile": "https://Stackoverflow.com/users/41939", "pm_score": 8, "selected": false, "text": "java -cp \"Test.jar;lib/*\" my.package.MainClass\n java -cp \"Test.jar;lib/*.jar\" my.package.MainClass\n *.jar java -cp \"Test.jar:lib/*\" my.package.MainClass\n" }, { "answer_id": 1960268, "author": "Alexey", "author_id": 126529, "author_profile": "https://Stackoverflow.com/users/126529", "pm_score": 2, "selected": false, "text": "java -cp \"target\\\\*;target\\\\dependency\\\\*\" my.package.Main\n" }, { "answer_id": 2394082, "author": "Navi", "author_id": 287727, "author_profile": "https://Stackoverflow.com/users/287727", "pm_score": 5, "selected": false, "text": "-Djava.ext.dirs=jarDirectory" }, { "answer_id": 4073636, "author": "prakash", "author_id": 494130, "author_profile": "https://Stackoverflow.com/users/494130", "pm_score": 4, "selected": false, "text": "javac -cp libs/* -verbose -encoding UTF-8 src/mypackage/*.java -d build/classes\n" }, { "answer_id": 8595267, "author": "Pops", "author_id": 122607, "author_profile": "https://Stackoverflow.com/users/122607", "pm_score": 6, "selected": false, "text": "java -classpath lib/*:. my.package.Program * *.jar -cp /classes;/jars/* CLASSPATH -cp -classpath Class-Path" }, { "answer_id": 9265429, "author": "rvernica", "author_id": 418730, "author_profile": "https://Stackoverflow.com/users/418730", "pm_score": 5, "selected": false, "text": "java -classpath \"lib/*:.\" my.package.Program\n java -classpath \"lib/a*.jar:.\" my.package.Program\njava -classpath \"lib/a*:.\" my.package.Program\njava -classpath \"lib/*.jar:.\" my.package.Program\njava -classpath lib/*:. my.package.Program\n" }, { "answer_id": 12891240, "author": "SANN3", "author_id": 1173495, "author_profile": "https://Stackoverflow.com/users/1173495", "pm_score": 5, "selected": false, "text": "java -cp \"/lib/*;\" sample\n java -cp \"/lib/*:\" sample\n" }, { "answer_id": 17377968, "author": "Matt S.", "author_id": 155631, "author_profile": "https://Stackoverflow.com/users/155631", "pm_score": 2, "selected": false, "text": "opt1: \"Extract required libraries into generated JAR\"\nopt2: \"Package required libraries into generated JAR\"\nopt3: \"Copy required libraries into a sub-folder next to the generated JAR\"\n /theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile.jar\n/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/SomeOtherJar01.jar\n/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/SomeOtherJar02.jar\n/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/SomeOtherJar03.jar\n/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/SomeOtherJar04.jar\n java -classpath \"/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/*\" -jar /theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile.jar package.path_to.the_class_with.your_main.TheClassWithYourMain\n java -classpath \"/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile.jar;/theFully/qualifiedPath/toYourChosenDir/fooBarTheJarFile_lib/*\" somepackages.inside.yourJar.leadingToTheMain.TheClassWithYourMain\n cd /theFully/qualifiedPath/toYourChosenDir/;\nBREAKS: java -cp \"fooBarTheJarFile_lib/*\" package.path_to.the_class_with.your_main.TheClassWithYourMain \nBREAKS: java -cp \".;fooBarTheJarFile_lib/*\" package.path_to.the_class_with.your_main.TheClassWithYourMain \nBREAKS: java -cp \".;fooBarTheJarFile_lib/*\" -jar package.path_to.the_class_with.your_main.TheClassWithYourMain \nWORKS: java -cp \".;fooBarTheJarFile_lib/*\" -jar fooBarTheJarFile.jar package.path_to.the_class_with.your_main.TheClassWithYourMain \n" }, { "answer_id": 18793968, "author": "Jake Toronto", "author_id": 1930619, "author_profile": "https://Stackoverflow.com/users/1930619", "pm_score": 3, "selected": false, "text": "java -cp \"somewhere/*;\"" }, { "answer_id": 27435495, "author": "Evgeni Sergeev", "author_id": 1143274, "author_profile": "https://Stackoverflow.com/users/1143274", "pm_score": 3, "selected": false, "text": "$ javac -cp '.;c:\\Programs\\COMSOL44\\plugins\\*' Reclaim.java\n $ javac -cp 'c:\\Programs\\COMSOL44\\plugins\\*' Reclaim.java\njavac: invalid flag: c:\\Programs\\COMSOL44\\plugins\\com.comsol.aco_1.0.0.jar\nUsage: javac <options> <source files>\nuse -help for a list of possible options\n $ echo './*'\n./*\n echo javac -cp com.comsol.aco_1.0.0.jar $ javac -version\njavac 1.7.0\n" }, { "answer_id": 29936380, "author": "Mindaugas K.", "author_id": 4512086, "author_profile": "https://Stackoverflow.com/users/4512086", "pm_score": 2, "selected": false, "text": " > mvn clean install\n\n > java -cp \"webapp/target/webapp-1.17.0-SNAPSHOT/WEB-INF/lib/tool-jar-1.17.0-SNAPSHOT.jar;webapp/target/webapp-1.17.0-SNAPSHOT/WEB-INF/lib/*\" com.xx.xx.util.EncryptorUtils param1 param2\n" }, { "answer_id": 38053543, "author": "Sreesankar", "author_id": 1729234, "author_profile": "https://Stackoverflow.com/users/1729234", "pm_score": 2, "selected": false, "text": " libDir2Scan4jars=\"../test\";cp=\"\"; for j in `ls ${libDir2Scan4jars}/*.jar`; do if [ \"$j\" != \"\" ]; then cp=$cp:$j; fi; done; echo $cp| cut -c2-${#cp} > .tmpCP.tmp; export tmpCLASSPATH=`cat .tmpCP.tmp`; if [ \"$tmpCLASSPATH\" != \"\" ]; then echo .; echo \"classpath set, you can now use ~> java -cp \\$tmpCLASSPATH\"; echo .; else echo .; echo \"Error please check libDir2Scan4jars path\"; echo .; fi; \n" }, { "answer_id": 38130048, "author": "Girdhar Singh Rathore", "author_id": 5115670, "author_profile": "https://Stackoverflow.com/users/5115670", "pm_score": 1, "selected": false, "text": "CLASSPATH=${ORACLE_HOME}/jdbc/lib/ojdbc6.jar:${ORACLE_HOME}/jdbc/lib/ojdbc14.jar:${ORACLE_HOME}/jdbc/lib/nls_charset12.jar; \nCLASSPATH=$CLASSPATH:/export/home/gs806e/tops/jconn2.jar:.;\nexport CLASSPATH\n" }, { "answer_id": 38444175, "author": "Wender", "author_id": 2070363, "author_profile": "https://Stackoverflow.com/users/2070363", "pm_score": 5, "selected": false, "text": " java -cp file.jar;dir/* my.app.ClassName\n java -cp file.jar:dir/* my.app.ClassName\n ; :" }, { "answer_id": 55154206, "author": "vkrams", "author_id": 727495, "author_profile": "https://Stackoverflow.com/users/727495", "pm_score": 1, "selected": false, "text": "JDK1.8 javac -classpath \"C:\\My Jars\\sdk\\lib\\*\" c:\\programs\\MyProgram.java java -classpath \"C:\\My Jars\\sdk\\lib\\*;c:\\programs\" MyProgram javac -classpath \"/home/guestuser/My Jars/sdk/lib/*\" MyProgram.java java -classpath \"/home/guestuser/My Jars/sdk/lib/*:/home/guestuser/programs\" MyProgram" }, { "answer_id": 58784144, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 2, "selected": false, "text": ".jar cd pwd -classpath : * main my_app.jar main App com.example java -classpath my_app.jar:* com.example.App\n" }, { "answer_id": 65926518, "author": "kellogs", "author_id": 243827, "author_profile": "https://Stackoverflow.com/users/243827", "pm_score": 0, "selected": false, "text": "java c:\\projects\\CloudMirror>java Javaside -cp \"jna-5.6.0.jar;.\\\"\nError: Unable to initialize main class Javaside\nCaused by: java.lang.NoClassDefFoundError: com/sun/jna/Callback\n c:\\projects\\CloudMirror>java -cp \"jna-5.6.0.jar;.\\\" Javaside\nException in thread \"main\" java.lang.UnsatisfiedLinkError: Unable\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13435/" ]
219,590
<p>What is the best way to localize a collection (IEnumerable)? From the BL I retrieve a collection of entities which still need to localized, I figured I write a method which extends the IEnumerable and returns the localized list. </p> <p>How can i get the code underneath working? Any ideas? Maybe better options? </p> <pre><code>public static IEnumerable Localize(this IEnumerable items, CultureInfo cultureInfo) { foreach(string item in items) { /*Error underneath, cannot assign to item*/ item = ResourceHelper.GetString(item, cultureInfo); } return (items); } </code></pre>
[ { "answer_id": 219611, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": false, "text": "public static IEnumerable<string> Localize(this IEnumerable<string> items, CultureInfo culture)\n{\n foreach (string item in items)\n {\n yield return ResourceHelper.GetString(item,culture);\n }\n}\n" }, { "answer_id": 219727, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "public static IEnumerable<string> Localize(this IEnumerable<string> items, CultureInfo cultureInfo)\n{\n List<string> newItems = new List<string>();\n foreach(string item in items)\n {\n newItems.Add( ResourceHelper.GetString(item, cultureInfo) );\n }\n return newItems;\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27857/" ]
219,594
<p>I'm wondering what the best way is to have a "if all else fails catch it".</p> <p>I mean, you're handling as much exceptions as possible in your application, but still there are bound to be bugs, so I need to have something that catches all unhandled exceptions so I can collect information and store them in a database or submit them to a web service.</p> <p>Does the AppDomain.CurrentDomain.UnhandledException event capture everything? Even if the application is multithreaded?</p> <p>Side note: Windows Vista exposes native API functions that allow any application to recover itself after a crash... can't think of the name now... but I'd rather not use it, as many of our users are still using Windows XP.</p>
[ { "answer_id": 219607, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 4, "selected": false, "text": "Application_Error Global.asax MyApplication_UnhandledException ApplicationEvents" }, { "answer_id": 219703, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 3, "selected": false, "text": "AppDomain.CurrentDomain.UnhandledException Application.ThreadException Application_Error" }, { "answer_id": 886887, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 0, "selected": false, "text": "try \n{\n CallTheCodeThatMightThrowException()\n }\ncatch (Exception ex)\n{\n System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace ();\n Utils.ErrorHandler.Trap ( ref objUser, st, ex );\n} //eof catch\n using System;\nusing log4net; //or another logging platform\n\nnamespace GenApp.Utils\n{\n public class ErrorHandler\n {\n public static void Trap ( Bo.User objUser, ILog logger, System.Diagnostics.StackTrace st, Exception ex )\n {\n if (ex is NullReferenceException)\n { \n //do stuff for this ex type\n } //eof if\n\n if (ex is System.InvalidOperationException) \n {\n //do stuff for this ex type\n } //eof if\n\n if (ex is System.IndexOutOfRangeException) \n {\n //do stuff for this ex type\n } //eof if\n\n if (ex is System.Data.SqlClient.SqlException)\n {\n //do stuff for this ex type\n } //eof if\n\n if (ex is System.FormatException)\n {\n //do stuff for this ex type\n } //eof if\n\n if (ex is Exception)\n {\n //do stuff for this ex type\n } //eof catch\n\n } //eof method \n\n }//eof class \n} //eof namesp\n" }, { "answer_id": 1055954, "author": "bohdan_trotsenko", "author_id": 58768, "author_profile": "https://Stackoverflow.com/users/58768", "pm_score": 6, "selected": true, "text": "class Program\n{\n void Run()\n {\n AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);\n\n Console.WriteLine(\"Press enter to exit.\");\n\n do\n {\n (new Thread(delegate()\n {\n throw new ArgumentException(\"ha-ha\");\n })).Start();\n\n } while (Console.ReadLine().Trim().ToLowerInvariant() == \"x\");\n\n\n Console.WriteLine(\"last good-bye\");\n }\n\n int r = 0;\n\n void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)\n {\n Interlocked.Increment(ref r);\n Console.WriteLine(\"handled. {0}\", r);\n Console.WriteLine(\"Terminating \" + e.IsTerminating.ToString());\n\n Thread.CurrentThread.IsBackground = true;\n Thread.CurrentThread.Name = \"Dead thread\"; \n\n while (true)\n Thread.Sleep(TimeSpan.FromHours(1));\n //Process.GetCurrentProcess().Kill();\n }\n\n static void Main(string[] args)\n {\n Console.WriteLine(\"...\");\n (new Program()).Run();\n }\n}\n" }, { "answer_id": 1482364, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 0, "selected": false, "text": "Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);\n Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28149/" ]
219,604
<p>How would you convert a parapraph to hex notation, and then back again into its original string form?</p> <p>(C#)</p> <p>A side note: would putting the string into hex format shrink it the most w/o getting into hardcore shrinking algo's?</p>
[ { "answer_id": 219619, "author": "Corey Goldberg", "author_id": 16148, "author_profile": "https://Stackoverflow.com/users/16148", "pm_score": 1, "selected": false, "text": "public string ConvertToHex(string asciiString)\n{\n string hex = \"\";\n foreach (char c in asciiString)\n {\n int tmp = c;\n hex += String.Format(\"{0:x2}\", (uint)System.Convert.ToUInt32(tmp.ToString()));\n }\n return hex;\n}\n" }, { "answer_id": 219620, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Text;\n\npublic class Hex\n{\n static void Main()\n {\n string original = \"The quick brown fox jumps over the lazy dog.\";\n\n byte[] binary = Encoding.UTF8.GetBytes(original);\n string hex = BytesToHex(binary);\n Console.WriteLine(\"Hex: {0}\", hex);\n byte[] backToBinary = HexToBytes(hex);\n\n string restored = Encoding.UTF8.GetString(backToBinary);\n Console.WriteLine(\"Restored: {0}\", restored);\n }\n\n private static readonly char[] HexChars = \"0123456789ABCDEF\".ToCharArray();\n\n public static string BytesToHex(byte[] data)\n {\n StringBuilder builder = new StringBuilder(data.Length*2);\n foreach(byte b in data)\n {\n builder.Append(HexChars[b >> 4]);\n builder.Append(HexChars[b & 0xf]);\n }\n return builder.ToString();\n }\n\n public static byte[] HexToBytes(string text)\n {\n if ((text.Length & 1) != 0)\n {\n throw new ArgumentException(\"Invalid hex: odd length\");\n }\n byte[] ret = new byte[text.Length/2];\n for (int i=0; i < text.Length; i += 2)\n {\n ret[i/2] = (byte)(ParseNybble(text[i]) << 4 | ParseNybble(text[i+1]));\n }\n return ret;\n }\n\n private static int ParseNybble(char c)\n {\n if (c >= '0' && c <= '9')\n {\n return c-'0';\n }\n if (c >= 'A' && c <= 'F')\n {\n return c-'A'+10;\n }\n if (c >= 'a' && c <= 'f')\n {\n return c-'A'+10;\n }\n throw new ArgumentOutOfRangeException(\"Invalid hex digit: \" + c);\n }\n}\n" }, { "answer_id": 1065167, "author": "Hafthor", "author_id": 4489, "author_profile": "https://Stackoverflow.com/users/4489", "pm_score": 0, "selected": false, "text": "static byte[] HexToBinary(string s) {\n byte[] b = new byte[s.Length / 2];\n for (int i = 0; i < b.Length; i++)\n b[i] = Convert.ToByte(s.Substring(i * 2, 2), 16);\n return b;\n}\nstatic string BinaryToHex(byte[] b) {\n StringBuilder sb = new StringBuilder(b.Length * 2);\n for (int i = 0; i < b.Length; i++)\n sb.Append(Convert.ToString(256 + b[i], 16).Substring(1, 2));\n return sb.ToString();\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
219,628
<p>I used to have a custom preferences class for my applications. For my next hobby project i wanted to switch to the Preferences API. But the put and get functions require a default value and i do not want to spread default values all over the source files. Even though my project is small i can not imagine changing default values all over the source code. How do you guys use the api? I am thinking of wrapping the preferences api in another class but then what is the point of using the API because it only takes away the burden of saving the file to disk, which isn't that hard using serialization? Am i missing the point?</p>
[ { "answer_id": 8429583, "author": "Kareem", "author_id": 1087529, "author_profile": "https://Stackoverflow.com/users/1087529", "pm_score": 2, "selected": false, "text": "AbstractPreferences" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29742/" ]
219,637
<p>The code is,</p> <pre><code>set VAR=before if "%VAR%" == "before" ( set VAR=after; echo %VAR% ) </code></pre> <p>What will the preceding Windows .bat file code segment display? Why? (i.e. why doesn't it behave as you might first think)?</p>
[ { "answer_id": 219658, "author": "Sean Sexton", "author_id": 22357, "author_profile": "https://Stackoverflow.com/users/22357", "pm_score": 3, "selected": true, "text": "set VAR=before\n\nif \"%VAR%\" == \"before\" (\n\n set VAR=after;\n\n echo !VAR!\n\n)\n" }, { "answer_id": 219667, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 0, "selected": false, "text": "%VAR% (...) set VAR=before\n\nif \"before\" == \"before\" (\n\nset VAR=after;\n\necho before\n\n)\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22357/" ]
219,668
<p>I'm looking for best practices to integrate log4net to SharePoint for web request, feature activation and all timer stuff. </p> <p>I have several subprojects in my farm, and I would like to have only one Log4Net.config file.</p> <p><strong>[Edit]</strong><br> Not only I need to configure log4net for the web application, which is easy to do (I use global.asax, and a log4net.config file, so I can modify log settings withtout reloading the webapp), but I also need to log asynchronous events:</p> <ul> <li>Event Handler (like ItemAdded)</li> <li>Timer Jobs</li> <li>...</li> </ul>
[ { "answer_id": 222646, "author": "Alex Angas", "author_id": 6651, "author_profile": "https://Stackoverflow.com/users/6651", "pm_score": 1, "selected": false, "text": "<configuration ...>\n ...\n <configSections>\n <section name=\"log4net\" type=\"log4net.Config.Log4NetConfigurationSectionHandler,log4net\" />\n </configSections>\n <log4net configSource=\"log4Net.config\">\n ...\n</configuration>\n" }, { "answer_id": 1767221, "author": "TheCodeKing", "author_id": 215057, "author_profile": "https://Stackoverflow.com/users/215057", "pm_score": 3, "selected": false, "text": "[assembly: log4net.Config.XmlConfigurator(ConfigFile = \n @\"C:\\Program Files\\Common Files\\Microsoft Shared\\\" + \n @\"Web Server Extensions\\12\\CONFIG\\log4net.config\", Watch = true)]\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22970/" ]
219,684
<p>Could someone please explain the best way to connect to an Interbase 7.1 database using .NET/C#?</p> <p>The application will be installed on many end user computers so the less "add-ons" that I will have to package with my application the better.</p>
[ { "answer_id": 26587576, "author": "Rick cf", "author_id": 2320107, "author_profile": "https://Stackoverflow.com/users/2320107", "pm_score": 0, "selected": false, "text": "connectionstring1 = \"DriverName=Interbase;Database=\" + database + \";User_Name=\" + userid + \";Password=\" + password;\nconnectionstring1 = connectionstring1 + \";SQLDialect=3;MetaDataAssemblyLoader=Borland.Data.TDBXInterbaseMetaDataCommandFactory,Borland.Data.DbxReadOnlyMetaData,Version=11.0.5000.0,Culture=neutral,\";\nconnectionstring1 = connectionstring1 + \"PublicKeyToken=91d62ebb5b0d1b1b;GetDriverFunc=getSQLDriverINTERBASE;LibraryName=dbxint30.dll;VendorLib=GDS32.DLL\";\n\nconnectionstring2 = “User_Name=\"+userid+\";Password=\"+password+\";Database=\"+database+\";ServerType=0;Charset=NONE;LibraryName=.\\\\dbxint.dll;VendorLib=GDS32.DLL;GetDriverFunc=getSQLDriverINTERBASE;SQLDialect=3\";\n\n\nGlobalObjects.dbconn = (TAdoDbxConnection)TAdoDbxInterBaseProviderFactory.Instance.CreateConnection();\n\nGlobalObjects.database = databasepath;\nGlobalObjects.dbconn.ConnectionString = connectionstring1; //or connectionstring2\nGlobalObjects.dbconn.Open();\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
219,716
<p>A cross join performs a cartesian product on the tuples of the two sets.</p> <pre><code>SELECT * FROM Table1 CROSS JOIN Table2 </code></pre> <p>Which circumstances render such an SQL operation particularly useful?</p>
[ { "answer_id": 219758, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 8, "selected": true, "text": "select \n size,\n color\nfrom\n sizes CROSS JOIN colors\n select\n hour,\n minute\nfrom\n hours CROSS JOIN minutes\n select\n specId,\n month\nfrom\n reports CROSS JOIN months\n MINUS WHERE" }, { "answer_id": 54937085, "author": "HankerPL", "author_id": 2800785, "author_profile": "https://Stackoverflow.com/users/2800785", "pm_score": 1, "selected": false, "text": "CREATE TABLE BL_GRP_01 (GR_1 text);\nCREATE TABLE RH_VAL_01 (RH_VAL text);\nINSERT INTO BL_GRP_01 VALUES ('A'), ('B'), ('AB'), ('O');\nINSERT INTO RH_VAL_01 VALUES ('+'), ('-');\n\nSELECT CONCAT(x.GR_1, y.RH_val)\n FROM BL_GRP_01 x\n CROSS JOIN RH_VAL_01 y\nORDER BY CONCAT(x.GR_1, y.RH_VAL);\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27765/" ]
219,719
<p>SQL databases seem to be the cornerstone of most software. However, it seems optimized for textual data. In fact when doing any queries involving numerical data, integers specifically, it seems inefficient that the numbers are getting converted to text and then back to native formats both ways between the application and the database. This same inefficiency seems to apply to BLOB data as well. My understanding is that even with something like Linq to SQL, this two way conversion is occuring in the background.</p> <p>Are there general ways to bypass this overhead with SQL? Are there certain database management systems that handle this more efficiently than others (ie, with non-standard extensions/API's)?</p> <p>Clarification. In the following select statement, the list of numbers after IN could be more easily passed as a raw array of int, but there seems to be no way of achieving that optimization level.</p> <pre><code>SELECT foo FROM bar WHERE baz IN (23, 34, 45, 9854004, ...) </code></pre>
[ { "answer_id": 219750, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 1, "selected": false, "text": "stmt = conn.Prepare(\"SELECT * FROM TABLE where x in (?, ?, ?)\");\nstmt.SetInt(0, x);\nstmt.SetInt(1, y);\nstmt.SetInt(2, z);\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1892/" ]
219,770
<p>In Visual Studio, I often use objects only for RAII purposes. For example:</p> <pre><code>ScopeGuard close_guard = MakeGuard( &amp;close_file, file ); </code></pre> <p>The whole purpose of <em>close_guard</em> is to make sure that the file will be close on function exit, it is not used anywhere else. However, Visual Studio gives me a warning that a "<em>local variable is initialized but not referenced</em>". I want to turn this warning off for this specific case.</p> <p>How do you deal with this kind of situation? Visual Studio thinks that this object is useless, but this is wrong since it has a non-trivial destructor.</p> <p>I wouldn't want to use a <em>#pragma warning</em> directive for this since it would turn off this warning even for legitimate reasons.</p>
[ { "answer_id": 219791, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 4, "selected": true, "text": "#pragma warning #pragma warning #pragma warning( push )\n#pragma warning( disable : 4705 ) // replace 4705 with warning number\n\nScopeGuard close_guard = MakeGuard( &close_file, file );\n\n#pragma warning( pop )\n ScopeGuard close_guard = MakeGuard( &close_file, file );\nclose_guard;\n #define #define UNUSED_VAR(VAR) VAR\n...\nScopeGuard close_guard = MakeGuard( &close_file, file );\nUNUSED_VAR(close_guard);\n" }, { "answer_id": 219792, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 2, "selected": false, "text": "static_cast<void>(close_guard);\n" }, { "answer_id": 219795, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 1, "selected": false, "text": "#pragma warning(push)\n#pragma warning(disable:XXXX)\nyour code here;\n#pragma warning(pop)\n #pragma warning(disable:XXXX)\nyour code here;\n#pragma warning(default:XXXX)\n UNREFERENCED_PARAMETER(close_guard);" }, { "answer_id": 219796, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "#define UNUSED(x) x\n ScopeGuard close_guard = MakeGuard( &close_file, file );\nUNUSED(close_guard);\n" }, { "answer_id": 219809, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "\nclass Test\n{\npublic:\n ~Test(void) { printf(\"destructor\\n\"); }\n};\n\nTest foo(void) { return Test(); }\n\nint main(void)\n{\n Test t = foo();\n printf(\"moo\\n\");\n\n return 0;\n}\n" }, { "answer_id": 220280, "author": "ididak", "author_id": 28888, "author_profile": "https://Stackoverflow.com/users/28888", "pm_score": 2, "selected": false, "text": "#define SCOPE_GUARD(guard, fn, param) \\\n ScopeGuard guard = MakeGuard(fn, param); \\\n static_cast<void>(guard)\n SCOPE_GUARD(g1, &file_close, file1);\nSCOPE_GUARD(g2, &file_close, file2);\n __LINE__ __func__" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9936/" ]
219,776
<p>I wanna get the Timedate value from another page using request.querystring and then use it an query to compare and pull up the matching datas. The function for the query in linq is:</p> <pre><code> protected void User_Querytime() { DataClasses2DataContext dc1 = new DataClasses2DataContext(); String Data = Request.QueryString["TimeOfMessage"]; var query7 = from u in dc1.syncback_logs where u.TimeOfMessage = Data orderby u.TimeOfMessage descending select u; GridView1.DataSource = query7; GridView1.DataBind(); } </code></pre> <p>Here the "Request.QueryString["TimeOfMessage"]" which i get is DateTime (ex:8/25/2008 9:07:19 AM). I wanted to compare it against the "u.TimeOfMessage" in database and pull up the matching records. </p> <p>When I use todatetime function to convert from string to datetime ,the value returned is bool and hence not able to compare it against the "Timeofmessage" which is datetime format in database. Can anyone help me in this?</p>
[ { "answer_id": 219805, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": true, "text": "DateTime when = DateTime.Parse(data);\nDateTime when = DateTime.ParseExact(data);\nDateTime when = Convert.ToDateTime(data);\n" }, { "answer_id": 263888, "author": "Christoph", "author_id": 34464, "author_profile": "https://Stackoverflow.com/users/34464", "pm_score": 0, "selected": false, "text": "Dim DateText = Request.QueryString(\"date\")\nDim MyDate As DateTime = Nothing\nIf DateTime.TryParse(DateText, MyDate) Then\n '--Date was passed correctly\nEnd If\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
219,783
<p>I can't seems to change the default color of the required field validator. In the source it is:</p> <pre><code>&lt;span class="required"&gt;*&lt;/span&gt; &lt;asp:RequiredFieldValidator ID="valReq_txtTracks" runat="server" ControlToValidate="txtTracks" Display="Dynamic" /&gt; </code></pre> <p>Here's what I have in my .skin file:</p> <pre><code>&lt;asp:RequiredFieldValidator runat="server" CssClass="error-text" ErrorMessage="required" /&gt; </code></pre> <p>In the rendered source I see:</p> <pre><code>&lt;span class="required"&gt;*&lt;/span&gt; &lt;span id="ctl00_ctl00_cphContent_cphContent_valReq_txtTracks" class="error-text" style="color:Red;display:none;"&gt;required&lt;/span&gt; </code></pre> <p>Notice the "style=color:Red;". That needs to go. I can't override it with a css-class because it's inline CSS. What should I do?</p>
[ { "answer_id": 219794, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 2, "selected": false, "text": "<asp:RequiredFieldValidator runat=\"server\" \n CssClass=\"error-text\"\n style=\"\"\n ErrorMessage=\"required\" />\n" }, { "answer_id": 501372, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "!important .form_error\n{\n font: bold 15px arial black,arial,verdana,helvetica !important; \n color: #ff0000 !important;\n}\n" }, { "answer_id": 6838471, "author": "Eric", "author_id": 371596, "author_profile": "https://Stackoverflow.com/users/371596", "pm_score": 3, "selected": false, "text": "ForeColor = Color.Empty" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12252/" ]
219,788
<p>I have a large (700kb) Flex .swf file representing the main file of a site. </p> <p>For performance testing I wanted to try and move it off to Amazon S3 hosting (which i have already done with certain videos and large files). </p> <p>I went ahead and did that, and updated the html page to reference the remote .swf.</p> <p>It turns out that Flash will load any resources relative to the .swf file accessing the resource - no matter what the root of the html page is. So my resources are now being loaded from the remote site (where they don't exist).</p> <p>There are two obvious things I could do : * copy all my resources remotely (not ready for this since i'm just testing now) * add in some layer of abstraction to every URL that the .swf accesses to derive a new path.</p> <p>I really want to flick a switch and say 'load everything relative to [original server]'.</p> <p>Does such a thing exist or am I stuck loading everythin from the remote machine unless I fully qualify every path?</p> <p>i want to avoid anything 'hacky' like : subclass Image and hack the path there</p>
[ { "answer_id": 220518, "author": "fenomas", "author_id": 10651, "author_profile": "https://Stackoverflow.com/users/10651", "pm_score": 0, "selected": false, "text": "base base base flashvars" }, { "answer_id": 221028, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 1, "selected": false, "text": "foo.load('/like/this/image.jpg')\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219788", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24727/" ]
219,798
<h2>I'm looking to add some lookup lists in the database, but I want them to be easy localizable (SQL 2005, ADO.NET)</h2> <p>This would include:</p> <ul> <li>Easy Management of multiple languages at the same time</li> <li>Easy Retrieval of values from the database</li> <li>Fallback language (in case the selected language is missing)</li> </ul> <p>I was thinking about having a table that would store the multi-language lookup-list (using for different languages the same id) and use a function that would return the value of the look-up list - by receiving the ID and the Language.</p> <p>One of the pitfalls would be that i have to manually add a language parameter to every query that uses the lookup list.</p> <p>I'm looking into a solution that would let me send the parameter as a "session/global variable", or that would send the parameter automatically with the sql query, and the function to retrieve it by itself (either to attach the parameter automatically, either to be able to read the parameter).</p> <p>The solution can look something like this, but I don't mind if it is different, as long as it doesn't give the parameter explicitly to the Query (pseudocode):</p> <blockquote> <pre><code>1. Send the language using "the method" 2. Execute Query 3. Get the localized results </code></pre> </blockquote> <p>Clarification:</p> <ol> <li><p>Normally the query would look like this (remember using the lookup function):</p> <p><code>SELECT .., GetLookupList1(lookup_ID, language), .. FROM TABLE</code></p></li> </ol> <p>The GetLookupList1 is a user defined function that retrieves the lookup value for a lookup table. By using this function, the SQL Code is easier to read and maintain.</p> <p>The body of the function would be something like:</p> <pre><code>SELECT @result = LookupValue FROM LookupTable1 WHERE ID=@Lookup_ID and Language=@lang RETURN @result </code></pre> <ol start="2"> <li><p>What I want is to be able to remove the language parameter from the function to some kind of a static variable, available only for the current connection/statement/command, so the query would look like</p> <p><code>SELECT .., GetLookupList1(lookup_ID), .. FROM TABLE</code></p></li> </ol>
[ { "answer_id": 219871, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 2, "selected": false, "text": "MessageToken DisplayText LangCode\nfirewood Fire wood en\nfirewood Bois de chauffage fr\n Select DisplayText from (some table) where MessageToken = 'firewood' and LangId = 'en'\n" }, { "answer_id": 223381, "author": "Corbin March", "author_id": 7625, "author_profile": "https://Stackoverflow.com/users/7625", "pm_score": 2, "selected": false, "text": "declare @languagein varchar(30), @contextin varbinary(128),\n @languageout varchar(30), @contextout varbinary(128)\n\nselect @languagein = 'ro-RO'\nselect @contextin = cast(@languagein as varbinary(128))\nset context_info @contextin\n\n--do whatever you like here: queries, stored procs. \n--context_info stays 'ro-RO' for the duration of the session/connection\n\nselect @contextout = context_info()\nset @languageout = replace(cast(@contextout as varchar(30)),0x00, '')\nprint @languageout\n SELECT COALESCE(langregion.LookupValue, lang.LookupValue, fallback.LookupValue) LookupVal\nFROM LookupTable1 fallback\nLEFT OUTER JOIN LookupTable1 lang \n ON lang.ID = fallback.ID AND lang.Lang = @language\nLEFT OUTER JOIN LookupTable1 langregion \n ON langregion.ID = fallback.ID AND langregion.Lang = @languagewithregion\nWHERE fallback.ID = @Lookup_ID\nAND fallback.Lang = @defaultlanguage\n" }, { "answer_id": 232650, "author": "Bogdan Maxim", "author_id": 23795, "author_profile": "https://Stackoverflow.com/users/23795", "pm_score": 0, "selected": false, "text": "SET CONTEXT_INFO" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219798", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23795/" ]
219,808
<p>I am completely new to LINQ in C#/.NET. I understand that I could use it to convert a DataSet into an Array/List, am I able to go in the opposite direction?</p> <p>I'm using NPlot to generate a graph of captured prices, which are stored in a List, where PriceInformation is a class containing two public doubles and a DateTime. </p> <p>Any suggestions very welcome.</p>
[ { "answer_id": 219877, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 4, "selected": true, "text": "//extension method to convert my type to an object array.\npublic static object[] ToObjectArray(this MyClass theSource)\n{\n object[] result = new object[3];\n result[0] = theSource.FirstDouble;\n result[1] = theSource.SecondDouble;\n result[2] = theSource.TheDateTime;\n\n return result;\n}\n\n\n//some time later, new up a dataTable, set it's columns, and then...\n\nDataTable myTable = new DataTable()\n\nDataColumn column1 = new DataColumn();\ncolumn1.DataType = GetType(\"System.Double\");\ncolumn1.ColumnName = \"FirstDouble\";\nmyTable.Add(column1);\n\nDataColumn column2 = new DataColumn();\ncolumn2.DataType = GetType(\"System.Double\");\ncolumn2.ColumnName = \"SecondDouble\";\nmyTable.Add(column2);\n\nDataColumn column3 = new DataColumn();\ncolumn3.DataType = GetType(\"System.DateTime\");\ncolumn3.ColumnName = \"TheDateTime\";\nmyTable.Add(column3);\n\n// ... Each Element becomes an array, and then a row\nMyClassList.ForEach(x => myTable.Rows.Add(x.ToObjectArray());\n" }, { "answer_id": 220155, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 1, "selected": false, "text": "MyObjectType foreach( MyObjectType value in myList )\n{\n dataContext.MyObkectTypes.InsertOnSubmit(value);\n}\ndataContext.SubmitChanges();\n List<MyObjectType> string xml = CreateInsertXml( myList );\ndataContext.usp_MyObjectsBulkInsertXml(xml);\n -- XML is expected in the following format:\n--\n-- <List>\n-- <Item>\n-- <PlotID>1234</PlotID>\n-- <XValue>2.4</SmsNumber> \n-- <YValue>3.2</ContactID>\n-- <ResultDate>12 Mar 2008</ResultDate>\n-- </Item>\n-- <Item>\n-- <PlotID>3241</PlotID>\n-- <XValue>1.4</SmsNumber> \n-- <YValue>5.2</ContactID>\n-- <ResultDate>3 Mar 2008</ResultDate>\n-- </Item>\n-- </List>\n\nCREATE PROCEDURE [dbo].usp_MyObjectsBulkInsertXml\n(\n @MyXML XML\n)\nAS\n\nDECLARE @DocHandle INT\nEXEC sp_xml_preparedocument @DocHandle OUTPUT, @MyXML\n\nINSERT INTO MyTable (\n PlotID,\n XValue,\n YValue,\n ResultDate\n) \nSELECT\n X.PlotID,\n X.XValue,\n X.YValue,\n X.ResultDate\nFROM OPENXML(@DocHandle, N'/List/Item', 2)\nWITH (\n PlotID INT,\n XValue FLOAT,\n YValue FLOAT,\n ResultDate DATETIME\n) X\n\nEXEC sp_xml_removedocument @DocHandle\n\nGO\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25462/" ]
219,815
<p>I've seen some very good questions on Stack Overflow concerning delegates, events, and the .NET implementation of these two features. One question in particular, "<a href="https://stackoverflow.com/questions/213638/how-do-c-events-work-behind-the-scenes#213651">How do C# Events work behind the scenes?</a>", produced a great answer that explains some subtle points very well. </p> <p>The answer to the above question makes this point:</p> <blockquote> <p>When you declare a field-like event ... the compiler generates the methods and a private field (of the same type as the delegate). Within the class, when you refer to ElementAddedEvent you're referring to the field. Outside the class, you're referring to the field</p> </blockquote> <p>An MSDN article linked from the same question ("<a href="http://msdn.microsoft.com/en-us/library/aa664455.aspx" rel="nofollow noreferrer">Field-like events</a>") adds:</p> <blockquote> <p>The notion of raising an event is precisely equivalent to invoking the delegate represented by the event — thus, there are no special language constructs for raising events.</p> </blockquote> <p>Wanting to examine further, I built a test project in order to view the IL that an event and a delegate are compiled to:</p> <pre><code>public class TestClass { public EventHandler handler; public event EventHandler FooEvent; public TestClass() { } } </code></pre> <p>I expected the delegate field <code>handler</code> and the event <code>FooEvent</code> to compile to roughly the same IL code, with some additional methods to wrap access to the compiler-generated <code>FooEvent</code> field. But the IL generated wasn't quite what I expected: </p> <pre><code>.class public auto ansi beforefieldinit TestClass extends [mscorlib]System.Object { .event [mscorlib]System.EventHandler FooEvent { .addon instance void TestClass::add_FooEvent(class [mscorlib]System.EventHandler) .removeon instance void TestClass::remove_FooEvent(class [mscorlib]System.EventHandler) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Constructor IL hidden } .field private class [mscorlib]System.EventHandler FooEvent .field public class [mscorlib]System.EventHandler handler } </code></pre> <p>Since events are nothing more than delegates with compiler-generated <code>add</code> and <code>remove</code> methods, I didn't expect to see events treated as anything more than that in IL. But the add and remove methods are defined in a section that begins <code>.event</code>, not <code>.method</code> as normal methods are. </p> <p>My ultimate questions are: if events are implemented simply as delegates with accessor methods, what is the point of having a <code>.event</code> IL section? Couldn't they be implemented in IL without this by using <code>.method</code> sections? Is <code>.event</code> equivalent to <code>.method</code>? </p>
[ { "answer_id": 219835, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": ".field public string Foo // public field\n.property instance string Bar // public property\n{\n .get instance string MyType::get_Bar()\n .set instance void MyType::set_Bar(string)\n}\n // only one instance field no matter how many events;\n// very useful if we expect most events to be unsubscribed\nprivate EventHandlerList events = new EventHandlerList();\nprotected EventHandlerList Events {\n get { return events; } // usually lazy\n}\n\n// this code repeated per event\nprivate static readonly object FooEvent = new object();\npublic event EventHandler Foo\n{\n add { Events.AddHandler(FooEvent, value); }\n remove { Events.RemoveHandler(FooEvent, value); }\n}\nprotected virtual void OnFoo()\n{\n EventHandler handler = Events[FooEvent] as EventHandler;\n if (handler != null) handler(this, EventArgs.Empty);\n}\n private Bar wrappedObject; // via ctor\npublic event EventHandler SomeEvent\n{\n add { wrappedObject.SomeOtherEvent += value; }\n remove { wrappedObject.SomeOtherEvent -= value; }\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28350/" ]
219,827
<p>I am trying to fill a form in a php application from a C# client (Outlook addin). I used Fiddler to see the original request from within the php application and the form is transmitted as a multipart/form. Unfortunately .Net does not come with native support for this type of forms (WebClient has only a method for uploading a file). Does anybody know a library or has some code to achieve this? I want to post different values and additionally (but only sometimes) a file.</p> <p>Thanks for your help, Sebastian</p>
[ { "answer_id": 220015, "author": "dnolan", "author_id": 29086, "author_profile": "https://Stackoverflow.com/users/29086", "pm_score": 6, "selected": true, "text": "public class PostData\n{\n\n private List<PostDataParam> m_Params;\n\n public List<PostDataParam> Params\n {\n get { return m_Params; }\n set { m_Params = value; }\n }\n\n public PostData()\n {\n m_Params = new List<PostDataParam>();\n\n // Add sample param\n m_Params.Add(new PostDataParam(\"email\", \"MyEmail\", PostDataParamType.Field));\n }\n\n\n /// <summary>\n /// Returns the parameters array formatted for multi-part/form data\n /// </summary>\n /// <returns></returns>\n public string GetPostData()\n {\n // Get boundary, default is --AaB03x\n string boundary = ConfigurationManager.AppSettings[\"ContentBoundary\"].ToString();\n\n StringBuilder sb = new StringBuilder();\n foreach (PostDataParam p in m_Params)\n {\n sb.AppendLine(boundary);\n\n if (p.Type == PostDataParamType.File)\n {\n sb.AppendLine(string.Format(\"Content-Disposition: file; name=\\\"{0}\\\"; filename=\\\"{1}\\\"\", p.Name, p.FileName));\n sb.AppendLine(\"Content-Type: text/plain\");\n sb.AppendLine();\n sb.AppendLine(p.Value); \n }\n else\n {\n sb.AppendLine(string.Format(\"Content-Disposition: form-data; name=\\\"{0}\\\"\", p.Name));\n sb.AppendLine();\n sb.AppendLine(p.Value);\n }\n }\n\n sb.AppendLine(boundary);\n\n return sb.ToString(); \n }\n}\n\npublic enum PostDataParamType\n{\n Field,\n File\n}\n\npublic class PostDataParam\n{\n\n\n public PostDataParam(string name, string value, PostDataParamType type)\n {\n Name = name;\n Value = value;\n Type = type;\n }\n\n public string Name;\n public string FileName;\n public string Value;\n public PostDataParamType Type;\n}\n HttpWebRequest oRequest = null;\noRequest = (HttpWebRequest)HttpWebRequest.Create(oURL.URL);\noRequest.ContentType = \"multipart/form-data\"; \noRequest.Method = \"POST\";\nPostData pData = new PostData();\n\nbyte[] buffer = encoding.GetBytes(pData.GetPostData());\n\n// Set content length of our data\noRequest.ContentLength = buffer.Length;\n\n// Dump our buffered postdata to the stream, booyah\noStream = oRequest.GetRequestStream();\noStream.Write(buffer, 0, buffer.Length);\noStream.Close();\n\n// get the response\noResponse = (HttpWebResponse)oRequest.GetResponse();\n" }, { "answer_id": 359222, "author": "jumoel", "author_id": 1555170, "author_profile": "https://Stackoverflow.com/users/1555170", "pm_score": 4, "selected": false, "text": "HttpWebRequest oRequest = null;\noRequest = (HttpWebRequest)HttpWebRequest.Create(\"http://you.url.here\");\noRequest.ContentType = \"multipart/form-data; boundary=\" + PostData.boundary;\noRequest.Method = \"POST\";\nPostData pData = new PostData();\nEncoding encoding = Encoding.UTF8;\nStream oStream = null;\n\n/* ... set the parameters, read files, etc. IE:\n pData.Params.Add(new PostDataParam(\"email\", \"example@example.com\", PostDataParamType.Field));\n pData.Params.Add(new PostDataParam(\"fileupload\", \"filename.txt\", \"filecontents\" PostDataParamType.File));\n*/\n\nbyte[] buffer = encoding.GetBytes(pData.GetPostData());\n\noRequest.ContentLength = buffer.Length;\n\noStream = oRequest.GetRequestStream();\noStream.Write(buffer, 0, buffer.Length);\noStream.Close();\n\nHttpWebResponse oResponse = (HttpWebResponse)oRequest.GetResponse();\n public class PostData\n{\n // Change this if you need to, not necessary\n public static string boundary = \"AaB03x\";\n\n private List<PostDataParam> m_Params;\n\n public List<PostDataParam> Params\n {\n get { return m_Params; }\n set { m_Params = value; }\n }\n\n public PostData()\n {\n m_Params = new List<PostDataParam>();\n }\n\n /// <summary>\n /// Returns the parameters array formatted for multi-part/form data\n /// </summary>\n /// <returns></returns>\n public string GetPostData()\n {\n StringBuilder sb = new StringBuilder();\n foreach (PostDataParam p in m_Params)\n {\n sb.AppendLine(\"--\" + boundary);\n\n if (p.Type == PostDataParamType.File)\n {\n sb.AppendLine(string.Format(\"Content-Disposition: file; name=\\\"{0}\\\"; filename=\\\"{1}\\\"\", p.Name, p.FileName));\n sb.AppendLine(\"Content-Type: application/octet-stream\");\n sb.AppendLine();\n sb.AppendLine(p.Value);\n }\n else\n {\n sb.AppendLine(string.Format(\"Content-Disposition: form-data; name=\\\"{0}\\\"\", p.Name));\n sb.AppendLine();\n sb.AppendLine(p.Value);\n }\n }\n\n sb.AppendLine(\"--\" + boundary + \"--\");\n\n return sb.ToString();\n }\n}\n\npublic enum PostDataParamType\n{\n Field,\n File\n}\n\npublic class PostDataParam\n{\n public PostDataParam(string name, string value, PostDataParamType type)\n {\n Name = name;\n Value = value;\n Type = type;\n }\n\n public PostDataParam(string name, string filename, string value, PostDataParamType type)\n {\n Name = name;\n Value = value;\n FileName = filename;\n Type = type;\n }\n\n public string Name;\n public string FileName;\n public string Value;\n public PostDataParamType Type;\n}\n" }, { "answer_id": 526261, "author": "Anthony", "author_id": 5599, "author_profile": "https://Stackoverflow.com/users/5599", "pm_score": 0, "selected": false, "text": " public static class WebHelpers\n {\n /// <summary>\n /// Post the data as a multipart form\n /// </summary>\n public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, string> values)\n {\n string formDataBoundary = \"---------------------------\" + WebHelpers.RandomHexDigits(12);\n string contentType = \"multipart/form-data; boundary=\" + formDataBoundary;\n\n string formData = WebHelpers.MakeMultipartForm(values, formDataBoundary);\n return WebHelpers.PostForm(postUrl, userAgent, contentType, formData);\n }\n\n /// <summary>\n /// Post a form\n /// </summary>\n public static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, string formData)\n {\n HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;\n\n if (request == null)\n {\n throw new NullReferenceException(\"request is not a http request\");\n }\n\n // Add these, as we're doing a POST\n request.Method = \"POST\";\n request.ContentType = contentType;\n request.UserAgent = userAgent;\n request.CookieContainer = new CookieContainer();\n\n // We need to count how many bytes we're sending. \n byte[] postBytes = Encoding.UTF8.GetBytes(formData);\n request.ContentLength = postBytes.Length;\n\n using (Stream requestStream = request.GetRequestStream())\n {\n // Push it out there\n requestStream.Write(postBytes, 0, postBytes.Length);\n requestStream.Close();\n }\n\n return request.GetResponse() as HttpWebResponse;\n }\n\n /// <summary>\n /// Generate random hex digits \n /// </summary>\n public static string RandomHexDigits(int count)\n {\n Random random = new Random();\n StringBuilder result = new StringBuilder();\n for (int i = 0; i < count; i++)\n {\n int digit = random.Next(16);\n result.AppendFormat(\"{0:x}\", digit);\n }\n\n return result.ToString();\n }\n\n /// <summary>\n /// Turn the key and value pairs into a multipart form\n /// </summary>\n private static string MakeMultipartForm(Dictionary<string, string> values, string boundary)\n {\n StringBuilder sb = new StringBuilder();\n\n foreach (var pair in values)\n {\n sb.AppendFormat(\"--{0}\\r\\nContent-Disposition: form-data; name=\\\"{1}\\\"\\r\\n\\r\\n{2}\\r\\n\", boundary, pair.Key, pair.Value);\n }\n\n sb.AppendFormat(\"--{0}--\\r\\n\", boundary);\n\n return sb.ToString(); \n }\n }\n}\n try\n {\n using (HttpWebResponse response = WebHelpers.MultipartFormDataPost(postUrl, UserAgentString, this.loginForm)) \n {\n if (response != null)\n {\n Cookie loginCookie = response.Cookies[\"logincookie\"];\n .....\n" }, { "answer_id": 769093, "author": "Brian Grinstead", "author_id": 76137, "author_profile": "https://Stackoverflow.com/users/76137", "pm_score": 6, "selected": false, "text": "FormUpload FormUpload.FileParameter // Implements multipart/form-data POST in C# http://www.ietf.org/rfc/rfc2388.txt\n// http://www.briangrinstead.com/blog/multipart-form-post-in-c\npublic static class FormUpload\n{\n private static readonly Encoding encoding = Encoding.UTF8;\n public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, object> postParameters)\n {\n string formDataBoundary = String.Format(\"----------{0:N}\", Guid.NewGuid());\n string contentType = \"multipart/form-data; boundary=\" + formDataBoundary;\n\n byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);\n\n return PostForm(postUrl, userAgent, contentType, formData);\n }\n private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)\n {\n HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;\n\n if (request == null)\n {\n throw new NullReferenceException(\"request is not a http request\");\n }\n\n // Set up the request properties.\n request.Method = \"POST\";\n request.ContentType = contentType;\n request.UserAgent = userAgent;\n request.CookieContainer = new CookieContainer();\n request.ContentLength = formData.Length;\n\n // You could add authentication here as well if needed:\n // request.PreAuthenticate = true;\n // request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.MutualAuthRequested;\n // request.Headers.Add(\"Authorization\", \"Basic \" + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(\"username\" + \":\" + \"password\")));\n\n // Send the form data to the request.\n using (Stream requestStream = request.GetRequestStream())\n {\n requestStream.Write(formData, 0, formData.Length);\n requestStream.Close();\n }\n\n return request.GetResponse() as HttpWebResponse;\n }\n\n private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)\n {\n Stream formDataStream = new System.IO.MemoryStream();\n bool needsCLRF = false;\n\n foreach (var param in postParameters)\n {\n // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added.\n // Skip it on the first parameter, add it to subsequent parameters.\n if (needsCLRF)\n formDataStream.Write(encoding.GetBytes(\"\\r\\n\"), 0, encoding.GetByteCount(\"\\r\\n\"));\n\n needsCLRF = true;\n\n if (param.Value is FileParameter)\n {\n FileParameter fileToUpload = (FileParameter)param.Value;\n\n // Add just the first part of this param, since we will write the file data directly to the Stream\n string header = string.Format(\"--{0}\\r\\nContent-Disposition: form-data; name=\\\"{1}\\\"; filename=\\\"{2}\\\";\\r\\nContent-Type: {3}\\r\\n\\r\\n\",\n boundary,\n param.Key,\n fileToUpload.FileName ?? param.Key,\n fileToUpload.ContentType ?? \"application/octet-stream\");\n\n formDataStream.Write(encoding.GetBytes(header), 0, encoding.GetByteCount(header));\n\n // Write the file data directly to the Stream, rather than serializing it to a string.\n formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);\n }\n else\n {\n string postData = string.Format(\"--{0}\\r\\nContent-Disposition: form-data; name=\\\"{1}\\\"\\r\\n\\r\\n{2}\",\n boundary,\n param.Key,\n param.Value);\n formDataStream.Write(encoding.GetBytes(postData), 0, encoding.GetByteCount(postData));\n }\n }\n\n // Add the end of the request. Start with a newline\n string footer = \"\\r\\n--\" + boundary + \"--\\r\\n\";\n formDataStream.Write(encoding.GetBytes(footer), 0, encoding.GetByteCount(footer));\n\n // Dump the Stream into a byte[]\n formDataStream.Position = 0;\n byte[] formData = new byte[formDataStream.Length];\n formDataStream.Read(formData, 0, formData.Length);\n formDataStream.Close();\n\n return formData;\n }\n\n public class FileParameter\n {\n public byte[] File { get; set; }\n public string FileName { get; set; }\n public string ContentType { get; set; }\n public FileParameter(byte[] file) : this(file, null) { }\n public FileParameter(byte[] file, string filename) : this(file, filename, null) { }\n public FileParameter(byte[] file, string filename, string contenttype)\n {\n File = file;\n FileName = filename;\n ContentType = contenttype;\n }\n }\n}\n // Read file data\nFileStream fs = new FileStream(\"c:\\\\people.doc\", FileMode.Open, FileAccess.Read);\nbyte[] data = new byte[fs.Length];\nfs.Read(data, 0, data.Length);\nfs.Close();\n\n// Generate post objects\nDictionary<string, object> postParameters = new Dictionary<string, object>();\npostParameters.Add(\"filename\", \"People.doc\");\npostParameters.Add(\"fileformat\", \"doc\");\npostParameters.Add(\"file\", new FormUpload.FileParameter(data, \"People.doc\", \"application/msword\"));\n\n// Create request and receive response\nstring postURL = \"http://localhost\";\nstring userAgent = \"Someone\";\nHttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, postParameters);\n\n// Process response\nStreamReader responseReader = new StreamReader(webResponse.GetResponseStream());\nstring fullResponse = responseReader.ReadToEnd();\nwebResponse.Close();\nResponse.Write(fullResponse);\n" }, { "answer_id": 950609, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " //This URL not exist, it's only an example.\n string url = \"http://myBox.s3.amazonaws.com/\";\n //Instantiate new CustomWebRequest class\n CustomWebRequest wr = new CustomWebRequest(url);\n //Set values for parameters\n wr.ParamsCollection.Add(new ParamsStruct(\"key\", \"${filename}\"));\n wr.ParamsCollection.Add(new ParamsStruct(\"acl\", \"public-read\"));\n wr.ParamsCollection.Add(new ParamsStruct(\"success_action_redirect\", \"http://www.yahoo.com\"));\n wr.ParamsCollection.Add(new ParamsStruct(\"x-amz-meta-uuid\", \"14365123651274\"));\n wr.ParamsCollection.Add(new ParamsStruct(\"x-amz-meta-tag\", \"\"));\n wr.ParamsCollection.Add(new ParamsStruct(\"AWSAccessKeyId\", \"zzzz\")); \n wr.ParamsCollection.Add(new ParamsStruct(\"Policy\", \"adsfadsf\"));\n wr.ParamsCollection.Add(new ParamsStruct(\"Signature\", \"hH6lK6cA=\"));\n //For file type, send the inputstream of selected file\n StreamReader sr = new StreamReader(@\"file.txt\");\n wr.ParamsCollection.Add(new ParamsStruct(\"file\", sr, ParamsStruct.ParamType.File, \"file.txt\"));\n\n wr.PostData();\n" }, { "answer_id": 1040461, "author": "eeeeaaii", "author_id": 128431, "author_profile": "https://Stackoverflow.com/users/128431", "pm_score": 3, "selected": false, "text": "System.Net.ServicePointManager.Expect100Continue = false;\n HttpWebRequest Expect:100-continue Content-Type --THEBOUNDARY\n --THEBOUNDARY--\n" }, { "answer_id": 1844241, "author": "TheQult", "author_id": 219491, "author_profile": "https://Stackoverflow.com/users/219491", "pm_score": 2, "selected": false, "text": "namespace WindowsFormsApplication1\n{\n public static class FormUpload\n {\n private static string NewDataBoundary()\n {\n Random rnd = new Random();\n string formDataBoundary = \"\";\n while (formDataBoundary.Length < 15)\n {\n formDataBoundary = formDataBoundary + rnd.Next();\n }\n formDataBoundary = formDataBoundary.Substring(0, 15);\n formDataBoundary = \"-----------------------------\" + formDataBoundary;\n return formDataBoundary;\n }\n\n public static HttpWebResponse MultipartFormDataPost(string postUrl, IEnumerable<Cookie> cookies, Dictionary<string, string> postParameters)\n {\n string boundary = NewDataBoundary();\n\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postUrl);\n\n // Set up the request properties\n request.Method = \"POST\";\n request.ContentType = \"multipart/form-data; boundary=\" + boundary;\n request.UserAgent = \"PhasDocAgent 1.0\";\n request.CookieContainer = new CookieContainer();\n\n foreach (var cookie in cookies)\n {\n request.CookieContainer.Add(cookie);\n }\n\n #region WRITING STREAM\n using (Stream formDataStream = request.GetRequestStream())\n {\n foreach (var param in postParameters)\n {\n if (param.Value.StartsWith(\"file://\"))\n {\n string filepath = param.Value.Substring(7);\n\n // Add just the first part of this param, since we will write the file data directly to the Stream\n string header = string.Format(\"--{0}\\r\\nContent-Disposition: form-data; name=\\\"{1}\\\"; filename=\\\"{2}\\\";\\r\\nContent-Type: {3}\\r\\n\\r\\n\",\n boundary,\n param.Key,\n Path.GetFileName(filepath) ?? param.Key,\n MimeTypes.GetMime(filepath));\n\n formDataStream.Write(Encoding.UTF8.GetBytes(header), 0, header.Length);\n\n // Write the file data directly to the Stream, rather than serializing it to a string.\n\n byte[] buffer = new byte[2048];\n\n FileStream fs = new FileStream(filepath, FileMode.Open);\n\n for (int i = 0; i < fs.Length; )\n {\n int k = fs.Read(buffer, 0, buffer.Length);\n if (k > 0)\n {\n formDataStream.Write(buffer, 0, k);\n }\n i = i + k;\n }\n fs.Close();\n }\n else\n {\n string postData = string.Format(\"--{0}\\r\\nContent-Disposition: form-data; name=\\\"{1}\\\"\\r\\n\\r\\n{2}\\r\\n\",\n boundary,\n param.Key,\n param.Value);\n formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, postData.Length);\n }\n }\n // Add the end of the request\n byte[] footer = Encoding.UTF8.GetBytes(\"\\r\\n--\" + boundary + \"--\\r\\n\");\n formDataStream.Write(footer, 0, footer.Length);\n request.ContentLength = formDataStream.Length;\n formDataStream.Close();\n }\n #endregion\n\n return request.GetResponse() as HttpWebResponse;\n }\n }\n}\n" }, { "answer_id": 3211654, "author": "Luis Domingues", "author_id": 387607, "author_profile": "https://Stackoverflow.com/users/387607", "pm_score": 2, "selected": false, "text": "formDataStream.Write(encoding.GetBytes(postData), 0, postData.Length);\n byte[] aPostData=encoding.GetBytes(postData);\nformDataStream.Write(aPostData, 0, aPostData.Length);\n" }, { "answer_id": 12458948, "author": "Yavanosta", "author_id": 1103991, "author_profile": "https://Stackoverflow.com/users/1103991", "pm_score": 0, "selected": false, "text": "/// <summary>\n/// Sending file via multipart\\form-data\n/// </summary>\n/// <param name=\"url\">URL for send</param>\n/// <param name=\"file\">Local file path</param>\n/// <param name=\"paramName\">Request file param</param>\n/// <param name=\"contentType\">Content-Type file headr</param>\n/// <param name=\"nvc\">Additional post params</param>\nprivate static string httpUploadFile(string url, string file, string paramName, string contentType, NameValueCollection nvc)\n{\n //delimeter\n var boundary = \"---------------------------\" + DateTime.Now.Ticks.ToString(\"x\");\n\n //creating request\n var wr = (HttpWebRequest)WebRequest.Create(url);\n wr.ContentType = \"multipart/form-data; boundary=\" + boundary;\n wr.Method = \"POST\";\n wr.KeepAlive = true;\n\n //sending request\n using(var requestStream = wr.GetRequestStream())\n {\n using (var requestWriter = new StreamWriter(requestStream, Encoding.UTF8))\n {\n //params\n const string formdataTemplate = \"Content-Disposition: form-data; name=\\\"{0}\\\"\\r\\n\\r\\n{1}\";\n foreach (string key in nvc.Keys)\n {\n requestWriter.Write(boundary);\n requestWriter.Write(String.Format(formdataTemplate, key, nvc[key]));\n }\n requestWriter.Write(boundary);\n\n //file header\n const string headerTemplate = \"Content-Disposition: form-data; name=\\\"{0}\\\"; filename=\\\"{1}\\\"\\r\\nContent-Type: {2}\\r\\n\\r\\n\";\n requestWriter.Write(String.Format(headerTemplate, paramName, file, contentType));\n\n //file content\n using (var fileStream = new FileStream(file, FileMode.Open, FileAccess.Read))\n {\n fileStream.CopyTo(requestStream);\n }\n\n requestWriter.Write(\"\\r\\n--\" + boundary + \"--\\r\\n\");\n }\n }\n\n //reading response\n try\n {\n using (var wresp = (HttpWebResponse)wr.GetResponse())\n {\n if (wresp.StatusCode == HttpStatusCode.OK)\n {\n using (var responseStream = wresp.GetResponseStream())\n {\n if (responseStream == null)\n return null;\n using (var responseReader = new StreamReader(responseStream))\n {\n return responseReader.ReadToEnd();\n }\n }\n }\n\n throw new ApplicationException(\"Error while upload files. Server status code: \" + wresp.StatusCode.ToString());\n }\n }\n catch (Exception ex)\n {\n throw new ApplicationException(\"Error while uploading file\", ex);\n }\n}\n" }, { "answer_id": 18233515, "author": "codevision", "author_id": 354473, "author_profile": "https://Stackoverflow.com/users/354473", "pm_score": 5, "selected": false, "text": "using System;\nusing System.IO;\nusing System.Net.Http;\n\nnamespace HttpClientTest\n{\n class Program\n {\n static void Main(string[] args)\n {\n var client = new HttpClient();\n var content = new MultipartFormDataContent();\n content.Add(new StreamContent(File.Open(\"../../Image1.png\", FileMode.Open)), \"Image\", \"Image.png\");\n content.Add(new StringContent(\"Place string content here\"), \"Content-Id in the HTTP\"); \n var result = client.PostAsync(\"https://hostname/api/Account/UploadAvatar\", content);\n Console.WriteLine(result.Result.ToString());\n }\n }\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29876/" ]
219,833
<p>I'm collecting metadata using the sys.* views, and according to the documentation, the sys.identity_columns view will return the seed and increment values like so.</p> <pre><code>CREATE TABLE ident_test ( test_id int IDENTITY(1000,10), other int ) SELECT name, seed_value, increment_value FROM sys.identity_columns WHERE object_id = OBJECT_ID( 'ident_test' ) </code></pre> <p>However, the above query just returns one column. Is it just me?</p> <p>(Note: I've had to change this question somewhat from its earlier version.)</p>
[ { "answer_id": 219850, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "IDENTITY SELECT c.name, i.seed_value, i.increment_value\nFROM sys.columns c\nINNER JOIN sys.identity_columns i\n ON i.object_id = c.object_id\n AND i.column_id = c.column_id\n LEFT JOIN IDENTITY NULL INNER JOIN VIEW INNER JOIN sys.tables t\nON t.object_id = c.object_id\n IDENTITY" }, { "answer_id": 219854, "author": "BoltBait", "author_id": 20848, "author_profile": "https://Stackoverflow.com/users/20848", "pm_score": 2, "selected": true, "text": "SELECT c.name, i.seed_value, i.increment_value\nfrom sys.identity_columns i\njoin sys.columns c\n ON i.object_id = c.object_id\n AND i.column_id = c.column_id\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4525/" ]
219,851
<p>I want a method of the class: "<code>One</code>" ("<code>AccessibleWithinSameNamespace</code>") to be accessible by the class: "<code>Two</code>", without having "<code>Two</code>" extending "<code>One</code>".</p> <p>Both classes are in the same namespace, so I'm thinking that maybe there's an access-modifier that emulates the "<em>protected</em>" modifyer, but for namespaces.</p> <p>Some code:</p> <pre><code>namespace Test { class One { public void AccessibleToAll() { } protected void AccessibleWithinSameNamespace() { // I am not public // I can be accessed from other classes // within the same namespace of my class } } } namespace Test { class Two { public Two() { One one = new One(); // I am able to access this method because my class // is in the same namespace as the class: "One" one.AccessibleWithinSameNamespace(); } } } </code></pre>
[ { "answer_id": 219858, "author": "Jorge Villuendas Zapatero", "author_id": 27097, "author_profile": "https://Stackoverflow.com/users/27097", "pm_score": 3, "selected": true, "text": "namespace Test\n{\n class One\n {\n public void AccessibleToAll()\n {\n }\n\n\n internal void AccessibleWithinSameNamespace()\n {\n // I am not public\n\n // I can be accessed from other classes\n // within the same namespace of my class\n }\n }\n}\n\nnamespace Test\n{\n class Two\n {\n public Two()\n {\n One one = new One();\n\n // I am able to access this method because my class\n // is in the same namespace as the class: \"One\"\n one.AccessibleWithinSameNamespace();\n }\n }\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20946/" ]
219,868
<p>I am working on a simple notification service that will be used to deliver messages to the users surfing a website. The notifications do not have to be sent in real time but it might be a better user experience if they happened more frequently than say every 5 minutes. The data being sent to and from the client is not very large and it is a straight forward database query to retrieve the data.</p> <p>In reading other conversations on the topic it would appear that an AJAX push can result in higher server loads. Since I can tolerate longer server delays is it worth while to have the server push notifications or to simply poll.</p> <p>It is not much harder to implement the push scenario and so I thought I would see what the opinion was here.</p> <p>Thanks for your help.</p> <p>EDIT: I have looked into a simple AJAX Push and implemented a simple demo based on this <a href="http://uwmike.com/articles/2008/01/22/browser-data-push/#more-384" rel="nofollow noreferrer">article</a> by Mike Purvis. The client load is fairly low at around 5k for the initial version and expected to stay that way for quite some time.</p> <hr> <p>Thank you everyone for your responses. I have decided to go with the polling solution but to wrap it all within a utility library so that if they want to change it later it is easier.</p>
[ { "answer_id": 220066, "author": "savetheclocktower", "author_id": 25720, "author_profile": "https://Stackoverflow.com/users/25720", "pm_score": 1, "selected": false, "text": "cometd" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22914/" ]
219,870
<p>I have a WordPress site (2.6.2) in which I have set the Home page to a static page instead of the normal posts page. The ID of this page is 2, so in the WordPress template I have changed the <code>wp_list_pages</code> to look like this:</p> <pre><code>&lt;?php wp_list_pages('exclude=2&amp;title_li=&amp;depth=1' ); ?&gt; </code></pre> <p>this works fine, but now the Home page doesn't get "lit up" when it's selected (because in fact it's page_id 2 that is selected, and it doesn't show in the menu). Is there any easy way around this?</p> <p>If not, in broad outlines, what's the hard way around this? Make my own version of the <code>wp_list_pages</code> function?</p> <p>Thanks!</p>
[ { "answer_id": 220157, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 3, "selected": true, "text": "wp_enqueue_script('jquery');\n wp_enqueue_script( 'jquery', '/path/to/your/jquery.js', false, '1.2.1');\n if(window.location.href == 'http://www.example.com/'){ //checks for root path - \"home\" ('http://www.example.com/?p=7' or 'http://www.example.com/2008-10/7' will not match)\n jQuery('#nav > ul > li > a:first').addClass('current_page_item');\n}\n jQuery(jQuery('#nav > ul > li > a')[3]).addClass('current_page_item'); //add 'current_page_item' css class so menu item highlighting occurs\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8047/" ]
219,881
<p>Is there a preference or behavior difference between using:</p> <pre><code>if(obj.getClass().isArray()) {} </code></pre> <p>and</p> <pre><code>if(obj instanceof Object[]) {} </code></pre> <p>?</p>
[ { "answer_id": 219898, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 0, "selected": false, "text": "String[] instanceof Object[]" }, { "answer_id": 219998, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 9, "selected": true, "text": "instanceof Integer[] int[] instanceof if (obj instanceof Integer[]) {\n Integer[] array = (Integer[]) obj;\n /* Use the boxed array */\n} else if (obj instanceof int[]) {\n int[] array = (int[]) obj;\n /* Use the primitive array */\n} else ...\n instanceof isArray() instanceof false isArray NullPointerException instanceof false isArray() true" }, { "answer_id": 221631, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 3, "selected": false, "text": "obj int[] Class Object[] obj instanceof .getClass().isArray()" }, { "answer_id": 1681141, "author": "Sebastien Tardif", "author_id": 203525, "author_profile": "https://Stackoverflow.com/users/203525", "pm_score": 2, "selected": false, "text": "getClass().isArray() clazz.getName().charAt(0) == '['" }, { "answer_id": 12873642, "author": "dturanski", "author_id": 1743446, "author_profile": "https://Stackoverflow.com/users/1743446", "pm_score": 2, "selected": false, "text": "isArray() MissingMethodException:\nNo signature of sun.reflect.generics.reflectiveObjects.GenericArrayTypeImpl.isArray() ...\n instanceof Object[]" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5309/" ]
219,904
<p>If I have a property that I want to let inheritors write to, but keep readonly externally, what is the preferred way to implement this? I usually go with something like this:</p> <pre><code>private object m_myProp; public object MyProp { get { return m_myProp; } } protected void SetMyProp(object value) { m_myProp = value; } </code></pre> <p>Is there a better way?</p>
[ { "answer_id": 219913, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "private object m_myProp;\npublic object MyProp\n{\n get { return m_myProp; }\n protected set { m_myProp = value; }\n}\n public object MyProp {get; protected set;}\n" }, { "answer_id": 219931, "author": "Brendan Enrick", "author_id": 22381, "author_profile": "https://Stackoverflow.com/users/22381", "pm_score": 3, "selected": false, "text": "public object MyProp {get; protected set;}\n private object _myProp;\npublic object MyProp\n{\n get { return _myProp; }\n protected set { _myProp = value; }\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27414/" ]
219,914
<p>I've often used pointers to const objects, like so...</p> <pre><code>const int *p; </code></pre> <p>That simply means that you can't change the integer that <code>p</code> is pointing at through <code>p</code>. But I've also seen reference to const pointers, declared like this...</p> <pre><code>int* const p; </code></pre> <p>As I understand it, that means that the pointer variable <em>itself</em> is constant -- you can change the integer it points at all day long, but you can't make it point at something else.</p> <p>What possible use would that have?</p>
[ { "answer_id": 219932, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "struct MyClass\n{\n char* const ptr;\n MyClass(char* str) :ptr(str) {}\n\n void SomeFunc(MyOtherClass moc)\n {\n for(int i=0; i < 100; ++i)\n { \n printf(\"%c\", ptr[i]);\n moc.SomeOtherFunc(this);\n }\n }\n}\n" }, { "answer_id": 219962, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "this C * const C C const this const C * const volatile const volatile this volatile" }, { "answer_id": 219973, "author": "Andrew Johnson", "author_id": 5109, "author_profile": "https://Stackoverflow.com/users/5109", "pm_score": 5, "selected": false, "text": "int* const p = &i;\n\n...\n\np++; /* Compiler error, oops you meant */\n(*p)++; /* Increment the number */\n" }, { "answer_id": 220025, "author": "DavidG", "author_id": 25893, "author_profile": "https://Stackoverflow.com/users/25893", "pm_score": -1, "selected": false, "text": "object* var;\n int var;\n const object* var;\n const int var;\n" }, { "answer_id": 220062, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 3, "selected": false, "text": "use at volatile" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12193/" ]
219,928
<p>Everyone has this huge massively parallelized supercomputer on their desktop in the form of a graphics card GPU.</p> <ul> <li>What is the "hello world" equivalent of the GPU community?</li> <li>What do I do, where do I go, to get started programming the GPU for the major GPU vendors?</li> </ul> <p>-Adam</p>
[ { "answer_id": 12980973, "author": "Kyle Niemeyer", "author_id": 1569494, "author_profile": "https://Stackoverflow.com/users/1569494", "pm_score": 3, "selected": false, "text": "#pragma acc kernels int i;\nfloat a = 2.0;\nfloat b[10000];\n#pragma acc kernels\nfor (i = 0; i < 10000; ++i) b[i] = 1.0f;\n#pragma acc kernels\nfor (i = 0; i < 10000; ++i) {\n b[i] = b[i] * a;\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
219,982
<p>e.g,</p> <pre><code>foo1 foo2 foo10 foo100 </code></pre> <p>rather than</p> <pre><code>foo1 foo10 foo100 foo2 </code></pre> <p>Update: not interested in coding the sort myself (although that's interesting in its own right), but having the database to do the sort for me.</p>
[ { "answer_id": 219985, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 4, "selected": true, "text": "select * from t\n order by to_number(regexp_substr(a,'^[0-9]+')),\n to_number(regexp_substr(a,'[0-9]+$')),\n a;\n create index t_ix1\n on t (to_number(regexp_substr(a, '^[0-9]+')),\n to_number(regexp_substr(a, '[0-9]+$')), \n a);\n" }, { "answer_id": 4246927, "author": "Coder", "author_id": 516287, "author_profile": "https://Stackoverflow.com/users/516287", "pm_score": 2, "selected": false, "text": "CREATE OR replace function NATURAL_ORDER(\n P_STR varchar2\n) return varchar2\nIS\n/** --------------------------------------------------------------------\n Replaces all sequences of numbers shorter than 10 digits by 0-padded\n numbers that exactly 10 digits in length. Usefull for ordering-by\n using NATURAL ORDER algorithm.\n */\n l_result varchar2( 32700 );\n l_len integer;\n l_ix integer;\n l_end integer;\nbegin\n l_result := P_STR;\n l_len := LENGTH( l_result );\n l_ix := 1;\n while l_len > 0 loop\n l_ix := REGEXP_INSTR( l_result, '[0-9]{1,9}', l_ix, 1, 0 );\n EXIT when l_ix = 0;\n l_end := REGEXP_INSTR( l_result, '[^0-9]|$', l_ix, 1, 0 );\n if ( l_end - l_ix >= 10 ) then\n l_ix := l_end;\n else\n l_result := substr( l_result, 1, l_ix - 1 )\n || LPAD( SUBSTR( l_result, l_ix, l_end-l_ix ), 10, '0' )\n || substr( l_result, l_end )\n ;\n l_ix := l_ix + 10;\n end if;\n end loop;\n return l_result;\nend;\n/\n select 'ABC' || LVL || 'DEF' as STR\n from (\n select LEVEL as LVL\n from DUAL\n start with 1=1\n connect by LEVEL <= 35\n )\n order by NATURAL_ORDER( STR )\n" }, { "answer_id": 32215335, "author": "Vladimir Sitnikov", "author_id": 1261287, "author_profile": "https://Stackoverflow.com/users/1261287", "pm_score": 2, "selected": false, "text": "lpad('1 ', 3000, '1 ') varchar2(4000) *? select * from (\n select dbms_random.string('X', 30) val from xmltable('1 to 1000')\n)\norder by regexp_replace(regexp_replace(val, '(\\d+)', lpad('0', 20, '0')||'\\1')\n , '0*?(\\d{21}(\\D|$))', '\\1');\n natural_sort 02 1 3 regexp_replace(val, '(^|\\D)0+(\\d+)', '\\1\\2') 10.02 10.1 02 2 10.02.03 \" \"\" '\"'||regexp_replace(..., '([^0-9]+)', '\",\"\\1\",\"')||'\"' xmltable length(length(num))||length(num)||num lpad(num, 10, '0') xmltable xmltable select *\n from (\n select (select listagg(case when regexp_like(w, '^[0-9]')\n then length(length(w))||length(w)||w else w\n end\n ) within group (order by ord)\n from xmltable(t.csv columns w varchar2(4000) path '.'\n , ord for ordinality) q\n ) order_by\n , t.*\n from (\n select '\"'||regexp_replace(replace(\n regexp_replace(val, '(^|\\D)0+(\\d+)', '\\1\\2')\n , '\"', '\"\"')\n , '([^0-9]+)', '\",\"\\1\",\"')||'\"' csv\n , t.*\n from (\n select dbms_random.string('X', 30) val from xmltable('1 to 100')\n ) t\n ) t\n ) t\norder by order_by;\n order by select *\n from (select dbms_random.string('X', 30) val from xmltable('1 to 100')) t\n order by (\n select listagg(case when regexp_like(w, '^[0-9]')\n then length(length(w))||length(w)||w else w\n end\n ) within group (order by ord)\n from xmltable('$X'\n passing xmlquery(('\"'||regexp_replace(replace(\n regexp_replace(t.val, '(^|\\D)0+(\\d+)', '\\1\\2')\n , '\"', '\"\"')\n , '([^0-9]+)', '\",\"\\1\",\"')||'\"')\n returning sequence\n ) as X\n columns w varchar2(4000) path '.', ord for ordinality) q\n);\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
219,999
<p>I am connecting to a MySQL database with PHP and the CodeIgniter Framework. I want to store my passwords encrypted in the database and would like to know the best way to do this.</p>
[ { "answer_id": 220134, "author": "vt.", "author_id": 3905, "author_profile": "https://Stackoverflow.com/users/3905", "pm_score": 2, "selected": false, "text": "$hasher = new PasswordHash(8, false);\n\n// Before storing a password\n$hash = $hasher->HashPassword($password);\n\n// To check a password against a hash\nif ($hasher->CheckPassword($password, $hash))\n // $password and $hash match\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/219999", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
220,010
<p>Ok, so I know that global variables are considered bad, and the singleton pattern is overused. And I have read in many places that a class should do only one task and contain only those variables that allow it to accomplish that one task. However, while working on my latest project, I actually thought about these rules before writing any code and have noticed that I tend to break them at the very beginning of the program. </p> <p>I'm currently working on an MFC dialog based application, but this question could be applied to any UI driven application. I have separate classes that handle state machines, file reading/writing, and hardware interfacing. All of these objects will need some type of UI control or property display/editing. In the MFC dialog applications, the dialog is the program, so it must exist until the program is closed. I've usually just put the objects in the main dialog class for the application and had the dialog class serve double duty; as both the main UI and the home for all other objects in the application. In other applications, I've created these objects globally and referenced them from wherever they were needed. Neither of these ways seem correct. The first option breaks the one class, one task rule, and the second relies on globals and also creates hidden dependencies. I could institute some type of dependency injection, but where would all these variables that I would inject reside?</p> <p>I'm just wondering what others do to organize their programs without breaking the rules?</p>
[ { "answer_id": 230888, "author": "ravenspoint", "author_id": 16582, "author_profile": "https://Stackoverflow.com/users/16582", "pm_score": 2, "selected": false, "text": "class CsolverApp : public CWinApp\n{\npublic:\n\ncData theData;\n\n…\n #include “solver.h”\n\ntheApp.theData.somepublicmethod();\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23504/" ]
220,020
<h2>Caution: This question is over nine years old!</h2> <p>Your best option is to search for newer questions, or to search the answers below looking for your specific version of MVC, as many answers here are obsolete now. </p> <p>If you do find an answer that works for your version, please make sure the answer contains the version of MVC you are using.<br> <sub><sub>(The original question starts below)</sub></sub></p> <hr> <p>This seems a bit bizarre to me, but as far as I can tell, this is how you do it.</p> <p>I have a collection of objects, and I want users to select one or more of them. This says to me "form with checkboxes." My objects don't have any concept of "selected" (they're rudimentary POCO's formed by deserializing a wcf call). So, I do the following:</p> <pre><code>public class SampleObject{ public Guid Id {get;set;} public string Name {get;set;} } </code></pre> <p>In the view:</p> <pre><code>&lt;% using (Html.BeginForm()) { %&gt; &lt;%foreach (var o in ViewData.Model) {%&gt; &lt;%=Html.CheckBox(o.Id)%&gt;&amp;nbsp;&lt;%= o.Name %&gt; &lt;%}%&gt; &lt;input type="submit" value="Submit" /&gt; &lt;%}%&gt; </code></pre> <p>And, in the controller, this is the only way I can see to figure out what objects the user checked:</p> <pre><code>public ActionResult ThisLooksWeird(FormCollection result) { var winnars = from x in result.AllKeys where result[x] != "false" select x; // yadda } </code></pre> <p>Its freaky in the first place, and secondly, for those items the user checked, the FormCollection lists its value as "true false" rather than just true. </p> <p>Obviously, I'm missing something. I think this is built with the idea in mind that the objects in the collection that are acted upon within the html form are updated using <code>UpdateModel()</code> or through a ModelBinder. </p> <p>But my objects aren't set up for this; does that mean that this is the only way? Is there another way to do it?</p>
[ { "answer_id": 220041, "author": "mmacaulay", "author_id": 22152, "author_profile": "https://Stackoverflow.com/users/22152", "pm_score": 5, "selected": false, "text": "\n<input type=\"checkbox\" name=\"applyChanges\" />\n \nvar checkBox = Request.Form[\"applyChanges\"];\n\nif (checkBox == \"on\")\n{\n...\n}\n" }, { "answer_id": 220073, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 9, "selected": true, "text": "<input type=\"hidden\" /> <% using (Html.BeginForm(\"ShowData\", \"Home\")) { %>\n <% foreach (var o in ViewData.Model) { %>\n <input type=\"checkbox\" name=\"selectedObjects\" value=\"<%=o.Id%>\">\n <%= o.Name %>\n <%}%>\n <input type=\"submit\" value=\"Submit\" />\n<%}%>\n selectedObjects value public ActionResult ShowData(Guid[] selectedObjects) {\n foreach (Guid guid in selectedObjects) {\n Response.Write(guid.ToString());\n }\n Response.End();\n return (new EmptyResult());\n}\n Guid[] selectedObjects" }, { "answer_id": 435851, "author": "Andrea Balducci", "author_id": 54215, "author_profile": "https://Stackoverflow.com/users/54215", "pm_score": 7, "selected": false, "text": "bool bChecked = form[key].Contains(\"true\");\n" }, { "answer_id": 479205, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 6, "selected": false, "text": "<label for=\"checkbox1\">Checkbox 1</label> <%= Html.CheckBox(\"cbNewColors\", true) %><label for=\"cbNewColors\">New colors</label>\n" }, { "answer_id": 479220, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 6, "selected": false, "text": "<input\n type=\"hidden\".../>" }, { "answer_id": 2484678, "author": "Fluffy", "author_id": 298157, "author_profile": "https://Stackoverflow.com/users/298157", "pm_score": 3, "selected": false, "text": "model.Property = collection[\"ElementId\"].ToLower().StartsWith(\"true\");\n" }, { "answer_id": 2493106, "author": "Darcy", "author_id": 277140, "author_profile": "https://Stackoverflow.com/users/277140", "pm_score": 3, "selected": false, "text": " <%= Html.CheckBox(\"Rs232CheckBox\", false, new { @id = \"rs232\" })%>RS-232\n\n <%= Html.CheckBox(\"Rs422CheckBox\", false, new { @id = \"rs422\" })%>RS-422\n public ActionResults MyAction(bool Rs232CheckBox, bool Rs422CheckBox) {\n ...\n}\n" }, { "answer_id": 2975516, "author": "nautic20", "author_id": 358604, "author_profile": "https://Stackoverflow.com/users/358604", "pm_score": 3, "selected": false, "text": "public class SampleViewModel\n{\n public IList<SampleObject> SampleObjectList { get; set; }\n public Guid[] SelectedObjectIds { get; set; }\n\n public class SampleObject\n {\n public Guid Id { get; set; }\n public string Name { get; set; }\n }\n}\n <asp:Content ID=\"Content2\" ContentPlaceHolderID=\"MainContent\" runat=\"server\">\n<h2>Sample View</h2>\n<table>\n <thead> \n <tr>\n <th>Checked</th>\n <th>Object Name</th>\n </tr>\n </thead> \n<% using (Html.BeginForm()) %>\n<%{%> \n <tbody>\n <% foreach (var item in Model.SampleObjectList)\n { %>\n <tr>\n <td><input type=\"checkbox\" name=\"SelectedObjectIds\" value=\"<%= item.Id%>\" /></td>\n <td><%= Html.Encode(item.Name)%></td>\n </tr>\n <% } %>\n </tbody>\n</table>\n<input type=\"submit\" value=\"Submit\" />\n<%}%> \n [AcceptVerbs(HttpVerbs.Get)]\n public ActionResult SampleView(Guid id)\n {\n //Object to pass any input objects to the View Model Builder \n BuilderIO viewModelBuilderInput = new BuilderIO();\n\n //The View Model Builder is a conglomerate of repositories and methods used to Construct a View Model out of Business Objects\n SampleViewModel viewModel = sampleViewModelBuilder.Build(viewModelBuilderInput);\n\n return View(\"SampleView\", viewModel);\n }\n\n [AcceptVerbs(HttpVerbs.Post)]\n public ActionResult SampleView(SampleViewModel viewModel)\n {\n // The array of Guids successfully bound to the SelectedObjectIds property of the View Model!\n return View();\n }\n" }, { "answer_id": 3087936, "author": "bluwater2001", "author_id": 175111, "author_profile": "https://Stackoverflow.com/users/175111", "pm_score": 3, "selected": false, "text": "<input type = \"checkbox\" name = \"checkbox1\" /> <label> Check to say hi.</label>\n [AcceptVerbs(HttpVerbs.Post)]\n public ActionResult Index(FormCollection fc)\n {\n\n var s = fc[\"checkbox1\"];\n\n if (s == \"on\")\n {\n string x = \"Hi\";\n }\n }\n" }, { "answer_id": 3998715, "author": "Jeroen", "author_id": 484412, "author_profile": "https://Stackoverflow.com/users/484412", "pm_score": 2, "selected": false, "text": "Replace(\"true,false\",\"true\").Split(',')\n" }, { "answer_id": 4159141, "author": "Skadoosh", "author_id": 268730, "author_profile": "https://Stackoverflow.com/users/268730", "pm_score": 0, "selected": false, "text": "bool isChecked = false;\nif (Boolean.TryParse(Request.Form.GetValues(”chkHuman”)[0], out isChecked) == false)\n ModelState.AddModelError(”chkHuman”, “Nice try.”);\n" }, { "answer_id": 4553251, "author": "pawlom84", "author_id": 557001, "author_profile": "https://Stackoverflow.com/users/557001", "pm_score": 0, "selected": false, "text": "<input type=\"checkbox\" id=\"IsNew-checkbox\" checked=\"checked\" /> \n<input type=\"hidden\" id=\"IsNew\" name=\"IsNew\" value=\"true\" /> \n<script language=\"javascript\" type=\"text/javascript\" > \n $('#IsNew-checkbox').click(function () { \n if ($('#IsNew-checkbox').is(':checked')) { \n $('#IsNew').val('true'); \n } else { \n $('#IsNew').val('false'); \n } \n }); \n</script> \n" }, { "answer_id": 5737367, "author": "eyesnz", "author_id": 142413, "author_profile": "https://Stackoverflow.com/users/142413", "pm_score": 0, "selected": false, "text": "//looking for [true],[false]\nbool isChecked = form.GetValues(key).Contains(\"true\"); \n //looking for [false],[false] or [false]\nbool isNotChecked = !form.GetValues(key).Contains(\"true\"); \n GetValues" }, { "answer_id": 7013596, "author": "doronAv", "author_id": 888237, "author_profile": "https://Stackoverflow.com/users/888237", "pm_score": 0, "selected": false, "text": "$(document).ready $('input:hidden').each(function(el) {\n var that = $(this)[0];\n if(that.id.length < 1 ) {\n\n console.log(that.id);\n that.parentElement.removeChild(that);\n\n }\n});\n" }, { "answer_id": 7782174, "author": "Shawn Mclean", "author_id": 400861, "author_profile": "https://Stackoverflow.com/users/400861", "pm_score": 5, "selected": false, "text": "@model SampleObject\n\n@Html.CheckBoxFor(m => m.IsChecked)\n@Html.HiddenFor(m => m.Id)\n@Html.LabelFor(m => m.IsChecked, Model.Id)\n @Html.EditorFor(x => ViewData.Model)\n" }, { "answer_id": 8745716, "author": "kk-dev11", "author_id": 1076915, "author_profile": "https://Stackoverflow.com/users/1076915", "pm_score": 2, "selected": false, "text": "<input type=\"checkbox\" name=\"selectedProducts\" value=\"@item.ProductId\" />@item.Name [HttpPost]\n public ActionResult Checkbox(int[] selectedObjects)\n {\n var selected = from x in selectedObjects\n from y in db\n where y.ObjectId == x\n select y; \n\n return View(selected);\n }\n" }, { "answer_id": 10710496, "author": "BraveNewMath", "author_id": 551811, "author_profile": "https://Stackoverflow.com/users/551811", "pm_score": 2, "selected": false, "text": " $('input[type=\"checkbox\"]').each(function () {\n $(this).attr('value', $(this).is(':checked'));\n }); \n" }, { "answer_id": 11042576, "author": "Dan VanWinkle", "author_id": 412339, "author_profile": "https://Stackoverflow.com/users/412339", "pm_score": 2, "selected": false, "text": "Contains(\"true\");\n var value = (bool)ValueProvider.GetValue(\"key\").ConvertTo(typeof(bool));\n var allPermissionsBase = Request.Params.AllKeys.Where(x => x.Contains(\"permission_\")).ToList();\nvar allPermissions = new List<KeyValuePair<int, bool>>();\n\nforeach (var key in allPermissionsBase)\n{\n // Try to parse the key as int\n int keyAsInt;\n int.TryParse(key.Replace(\"permission_\", \"\"), out keyAsInt);\n\n // Try to get the value as bool\n var value = (bool)ValueProvider.GetValue(key).ConvertTo(typeof(bool));\n}\n public ActionResult UpdatePermissions(bool permission_1, bool permission_2)\n" }, { "answer_id": 16054941, "author": "treborian", "author_id": 2289733, "author_profile": "https://Stackoverflow.com/users/2289733", "pm_score": 0, "selected": false, "text": "Viewbag. Viewbag.Checkbool @Viewbag.Checkbool public ActionResult Anzeigen(int productid = 90, bool islive = true)\n <input id=\"isLive\" type=\"checkbox\" checked=\"@ViewBag.Value\" ONCLICK=\"window.location.href = '/MixCategory/Anzeigen?isLive=' + isLive.checked.toString()\" />\n" }, { "answer_id": 22028124, "author": "Ravi Ram", "author_id": 665387, "author_profile": "https://Stackoverflow.com/users/665387", "pm_score": 0, "selected": false, "text": "// MVC Work around for checkboxes.\nbool active = (Request.Form[\"active\"] == \"on\");\n" }, { "answer_id": 22331632, "author": "ChinaHelloWorld", "author_id": 3001024, "author_profile": "https://Stackoverflow.com/users/3001024", "pm_score": 2, "selected": false, "text": " <% foreach (var item in Model.SampleObjectList)\n { %>\n <tr>\n <td><input type=\"checkbox\" name=\"SelectedObjectIds\" value=\"<%= item.Id%>\" /></td>\n <td><%= Html.Encode(item.Name)%></td>\n </tr>\n <% } %>\n <% foreach (var item in Model.SampleObjectList)\n { %>\n <tr>\n <td><input type=\"checkbox\" name=\"SelectedObjectIds\" id=\"[some unique key]\" value=\"<%= item.Id%>\" /></td>\n <td><%= Html.Encode(item.Name)%></td>\n </tr>\n<% } %>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
220,021
<p>I am trying to use log4net in an ASP.NET application with Visual Studio 2005. I have declared an instance of the logger like so:</p> <pre><code>Private Shared ReadOnly log As ILog = LogManager.GetLogger("") </code></pre> <p>I am trying to use it in the following manner:</p> <pre><code>If log.IsDebugEnabled Then log.Debug("Integration Services Constructed") End If </code></pre> <p>Here is my configuration:</p> <pre class="lang-xml prettyprint-override"><code>&lt;log4net&gt; &lt;root&gt; &lt;level value="DEBUG" /&gt; &lt;appender-ref ref="RollingFileAppender" /&gt; &lt;/root&gt; &lt;appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender"&gt; &lt;file value="..\\logs\\logfile.log"/&gt; &lt;appendToFile value="true"/&gt; &lt;rollingStyle value="Size"/&gt; &lt;maxSizeRollBackups value="10"/&gt; &lt;maximumFileSize value="1MB"/&gt; &lt;staticLogFileName value="true"/&gt; &lt;layout type="log4net.Layout.PatternLayout"&gt; &lt;conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline"/&gt; &lt;/layout&gt; &lt;filter type="log4net.Filter.LevelRangeFilter"&gt; &lt;param name="LevelMin" value="DEBUG" /&gt; &lt;param name="LevelMax" value="FATAL" /&gt; &lt;/filter&gt; &lt;/appender&gt; &lt;/log4net&gt; </code></pre> <p>Unfortunately, <code>log.IsDebugEnabled</code> is always false. <br /> How do I configure log4net so that I can log only debug messages?</p>
[ { "answer_id": 220037, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 5, "selected": false, "text": "[assembly: XmlConfigurator(Watch = true)]\n log4net.config [assembly: log4net.Config.XmlConfigurator(ConfigFile = \"log4net.config\", Watch = true)]\n" }, { "answer_id": 21675765, "author": "Revan", "author_id": 2879268, "author_profile": "https://Stackoverflow.com/users/2879268", "pm_score": 0, "selected": false, "text": "<root>\n <level value=\"ALL\" />\n <appender-ref ref=\"AppenderName\" />\n </root>\n" }, { "answer_id": 22522189, "author": "developer9", "author_id": 1079542, "author_profile": "https://Stackoverflow.com/users/1079542", "pm_score": 1, "selected": false, "text": "<Assembly: log4net.Config.XmlConfigurator(Watch:=True)> \n" }, { "answer_id": 26756171, "author": "Protector one", "author_id": 125938, "author_profile": "https://Stackoverflow.com/users/125938", "pm_score": 2, "selected": false, "text": "log4net.Config.BasicConfigurator.Configure GetLogger" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19977/" ]
220,026
<p>I am attempting to import mxml files that I developed with Emacs into a new project in FlexBuilder...I have created a project and manually added all my MXML and actionscript files into FlexBuilder. </p> <p>I now can't figure out how to run the application. I believe the problem lies in the fact that FlexBuilder believes that all my mxml files are components, when in fact, they are applications...Is there a way to change this?</p> <p>When I right click on the file the "set as default application" and "run application" is disabled...</p> <p>Thanks.</p>
[ { "answer_id": 370835, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<applications> \n<application path=\"com/example/games/game1/Main.as\"/> \n<application path=\"com/example/games/game2/Main.as\"/> \n</applications>\n" }, { "answer_id": 18085736, "author": "Mauricio Gracia Gutierrez", "author_id": 1461862, "author_profile": "https://Stackoverflow.com/users/1461862", "pm_score": 0, "selected": false, "text": " <applications>\n <application path=\"EnvioManualExtractos.mxml\"/>\n <application path=\"REPLACE_WITH_REAL_NAME.mxml\"/>\n </applications>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
220,031
<p>Previously, settings for deployments of an ASP.NET application were stored in multiple configuration files under the Web.config config sections using a KEY/VALUE format. We are moving these 'site module options' to the database for a variety of reasons. </p> <p>Here are the two options we are mulling over at the moment: <br> 1. A single table with the applicationId, moduleId, and key as a Primary Key with a Value field. <br><strong>Pros:</strong> <br> - This mimics the file access. <br> - It is easy to select entire sections to cache in hashtables/value objects. <br><strong>Cons:</strong> <br> - More difficult to update since each key needs to be updated individually. <br> - Must cast each value if it's not a string. </p> <p><br> 2. Individual tables for each section which separate stored procedures, classes, etc. <br><strong>Pros:</strong> <br> - Data is guaranteed to be consistent since the column and object types are typed. <br> - Updating is done in one trip to the database through an explicit interface. <br><strong>Cons:</strong> <br> - Must change the application interface to access the <br> - Must update the objects, database tables, and stored procedures each time something changes. </p> <p>Do either of these sound like good ideas or is there another way I may have overlooked? </p>
[ { "answer_id": 223450, "author": "Brad Patton", "author_id": 27989, "author_profile": "https://Stackoverflow.com/users/27989", "pm_score": 1, "selected": false, "text": "/// <summary>\n/// The time passwords expire, in days, if ExpirePasswords is on\n/// </summary>\npublic int PasswordExpirationDays {\n get { return ParseUtils.ParseInt(this[\"PasswordExpirationDays\"], PW_MAX_AGE);}\n set { this[\"PasswordExpirationDays\"] = value.ToString(); }\n}\n" }, { "answer_id": 1150704, "author": "JBrooks", "author_id": 136059, "author_profile": "https://Stackoverflow.com/users/136059", "pm_score": 0, "selected": false, "text": " cApp.AppSettings[\"MySetting\"];\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
220,044
<p>Which sorting algorithm works best on mostly sorted data?</p>
[ { "answer_id": 220069, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 4, "selected": false, "text": "k 1..n el[k] >= el[k-1] 1..k-1 k>T T k" }, { "answer_id": 220750, "author": "zaphod", "author_id": 13871, "author_profile": "https://Stackoverflow.com/users/13871", "pm_score": 5, "selected": false, "text": "sort()" }, { "answer_id": 942024, "author": "Jonas Kölker", "author_id": 58668, "author_profile": "https://Stackoverflow.com/users/58668", "pm_score": 2, "selected": false, "text": "(i, j) i < j && a[i] > a[j]" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29783/" ]
220,051
<p>I'm not the best at PHP and would be extremely grateful if somebody could help. Basically I need to parse each line of a datafeed and just get each bit of information between each "|" - then I can add it to a database. I think I can handle getting the information from between the "|"'s by using explode but I need a bit of help with parsing each line from a text file as a singular. Infact to make it even more simple, I just need it to use each line of a variable, I will submit content to the variable using a textarea and a form. Any help would be greatly appreciated!</p>
[ { "answer_id": 220072, "author": "Randy", "author_id": 9361, "author_profile": "https://Stackoverflow.com/users/9361", "pm_score": 3, "selected": true, "text": "$lines = file(\"filename\");\nforeach($lines as $line) {\n $parts = explode(\"|\", $line);\n // do the database inserts here\n}\n" }, { "answer_id": 220078, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 0, "selected": false, "text": "$handle = fopen(\"/tmp/inputfile.txt\", \"r\");\nwhile (!feof($handle)) {\n $buffer = fgets($handle, 4096);\n echo $buffer;\n}\nfclose($handle);\n" }, { "answer_id": 220081, "author": "Zak", "author_id": 2112692, "author_profile": "https://Stackoverflow.com/users/2112692", "pm_score": 2, "selected": false, "text": "$sometext = \"balh | balh blah| more blah \\n extra balh |some blah |this blah\";\n\n$lines = explode(\"\\n\", $sometext);\nforeach($lines as $oneLine)\n{\n $lineElements[] = explode(\"|\", $oneLine);\n}\n" }, { "answer_id": 220086, "author": "Ryan Abbott", "author_id": 27908, "author_profile": "https://Stackoverflow.com/users/27908", "pm_score": 0, "selected": false, "text": "$myFile = \"File.txt\";\n$fh = fopen($myFile, 'r');\n$data = fread($fh);\nfclose($fh);\n$newLines = explode(\"\\n\",$data);\n\nforeach($newLines as $s)\n{\n $parsed = explode(\"|\",$s);\n foreach($parsed as $item)\n {\n // do your db load here\n }\n}\n" }, { "answer_id": 10914453, "author": "HenryHayes", "author_id": 1439760, "author_profile": "https://Stackoverflow.com/users/1439760", "pm_score": 1, "selected": false, "text": "$reader = new Dfp_Datafeed_File_Reader();\n$reader->setLocation('test.csv');\n\nforeach ($reader AS $record) {\n print_r($record);\n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26823/" ]
220,075
<p>OK, so I readily concede that I'm a newbie when it comes to continuous integration.</p> <p>That being said, I'm trying to set up a CC.NET environment to educate myself, but I'm having trouble finding the information I need to get the automated build portion set up.</p> <p>As I understand it, in C# the .csproj file produced by VS 2005 and forward <em>is</em> a valid MSBuild file. To wit, I've been able to integrate the MSBuild task into CC.NET using the .csproj file, but I have a few issues with this:</p> <ol> <li>There's a lot going on in here that I'm not sure I really need in an automated build environment.</li> <li>I didn't create this file. I do not understand it, and that scares me. (<a href="http://www.pragprog.com/the-pragmatic-programmer/extracts/coincidence" rel="noreferrer">Programming By Coincidence</a>)</li> <li>Most of what is going on seems to be abstracted through <code>$(MSBuildToolsPath)\Microsoft.CSharp.targets</code></li> <li>As a result of 1, 2, and 3, modifying the file to include something like MbUnit seems convoluted and more difficult than it needs to be. My only real option is to include it in the <code>AfterBuild</code> section, which seems kind of like a hack to me.</li> </ol> <p>So, a few questions for the CC.NET folks, the MSBuild folks, and the MbUnit folks.</p> <ol> <li>When using MSBuild, is it advisable to use the VS-generated .csproj file as the build file? Or should I create my own?</li> <li>Should MbUnit tests be part of the MSBuild file or the CC.NET file? My research seems to suggest that they belong in the MSBuild file. If that is the case, do I create a new MSBuild .proj file and check that in to CVS in addition to the .csproj file? Or does the MbUnit task become part of my .csproj file?</li> <li>Similar to question 2. If I add the MbUnit tests to the MSBuild file and end up using the .csproj file, is the <code>Target Name="AfterBuild"</code> really the section to add that information? Shouldn't there be a <code>Target Name="Test"</code> section? Using the VS generated .csproj file seems to prevent the second option.</li> </ol> <p>I know there's a lot there, but most of what I've been able to find online assumes a certain level of familiarity with these topics that I just don't have -- unless I'm mistaken, the learning curve for this stuff isn't a curve at all, it's a step function. :)</p> <p>Edit 1: I updated the text to be a bit more concise and to address some lingering questions I've had with the answers.</p>
[ { "answer_id": 221129, "author": "bh213", "author_id": 28912, "author_profile": "https://Stackoverflow.com/users/28912", "pm_score": 2, "selected": false, "text": "<MSBuild Projects=\"MySolution.sln\" Targets=\"Clean; Rebuild\" Properties=\"Configuration=$(BuildMode);\">\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1108/" ]
220,084
<p>Inspired by <a href="https://stackoverflow.com/questions/220044/which-sort-algorithm-works-best-on-mostly-sorted-data">this question</a></p> <p>The choice of which algorithm to use to sort a collection can be made better if we know ahead of time how well sorted a collection is. Is there a way we can measure (or maintain a measurement) of how well sorted the collection is? Can we do this in such a way that the cost of maintaining or measuring how well sorted something doesn't outweigh the benefit of choosing the best sort algorithm?</p>
[ { "answer_id": 220091, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 2, "selected": false, "text": "10" }, { "answer_id": 2099258, "author": "Aaron Couture", "author_id": 254612, "author_profile": "https://Stackoverflow.com/users/254612", "pm_score": 0, "selected": false, "text": "int sorted = 0;\nfor (int i = 0; i < list_length; i++) {\n if (list[i+1] >= list[i]) {\n sorted++;\n }\n}\nsortedness = sorted/(list_length-1);\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8123/" ]
220,097
<p>I'm trying to find out how to read/write to the extended file properties in C# e.g. Comment, Bit Rate, Date Accessed, Category etc that you can see in Windows explorer. Any ideas how to do this? EDIT: I'll mainly be reading/writing to video files (AVI/DIVX/...)</p>
[ { "answer_id": 220141, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 5, "selected": false, "text": "GetDetailsOf() shell32.dll" }, { "answer_id": 325659, "author": "Dirk Vollmar", "author_id": 40347, "author_profile": "https://Stackoverflow.com/users/40347", "pm_score": 5, "selected": false, "text": "Sub Main()\n Dim arrHeaders(35)\n\n Dim shell As New Shell32.Shell\n Dim objFolder As Shell32.Folder\n\n objFolder = shell.NameSpace(\"C:\\tmp\")\n\n For i = 0 To 34\n arrHeaders(i) = objFolder.GetDetailsOf(objFolder.Items, i)\n Next\n For Each strFileName In objfolder.Items\n For i = 0 To 34\n Console.WriteLine(i & vbTab & arrHeaders(i) & \": \" & objfolder.GetDetailsOf(strFileName, i))\n Next\n Next\n\n End Sub\n" }, { "answer_id": 2096315, "author": "csharptest.net", "author_id": 164392, "author_profile": "https://Stackoverflow.com/users/164392", "pm_score": 8, "selected": true, "text": "public static void Main(string[] args)\n{\n List<string> arrHeaders = new List<string>();\n\n Shell32.Shell shell = new Shell32.Shell();\n Shell32.Folder objFolder;\n\n objFolder = shell.NameSpace(@\"C:\\temp\\testprop\");\n\n for( int i = 0; i < short.MaxValue; i++ )\n {\n string header = objFolder.GetDetailsOf(null, i);\n if (String.IsNullOrEmpty(header))\n break;\n arrHeaders.Add(header);\n }\n\n foreach(Shell32.FolderItem2 item in objFolder.Items())\n {\n for (int i = 0; i < arrHeaders.Count; i++)\n {\n Console.WriteLine(\n $\"{i}\\t{arrHeaders[i]}: {objFolder.GetDetailsOf(item, i)}\");\n }\n }\n}\n" }, { "answer_id": 15111611, "author": "RajeshKdev", "author_id": 900307, "author_profile": "https://Stackoverflow.com/users/900307", "pm_score": 3, "selected": false, "text": "GetDetailsOf() Windows-OS List<string> arrHeaders = new List<string>();\n\n Shell shell = new ShellClass();\n Folder rFolder = shell.NameSpace(_rootPath);\n FolderItem rFiles = rFolder.ParseName(filename);\n\n for (int i = 0; i < short.MaxValue; i++)\n {\n string value = rFolder.GetDetailsOf(rFiles, i).Trim();\n arrHeaders.Add(value);\n }\n" }, { "answer_id": 37986932, "author": "Martin Schneider", "author_id": 1951524, "author_profile": "https://Stackoverflow.com/users/1951524", "pm_score": 5, "selected": false, "text": "Microsoft.WindowsAPICodePack-Shell Microsoft.WindowsAPICodePack-Core using Microsoft.WindowsAPICodePack.Shell;\nusing Microsoft.WindowsAPICodePack.Shell.PropertySystem;\n\nstring filePath = @\"C:\\temp\\example.docx\";\nvar file = ShellFile.FromFilePath(filePath);\n\n// Read and Write:\n\nstring[] oldAuthors = file.Properties.System.Author.Value;\nstring oldTitle = file.Properties.System.Title.Value;\n\nfile.Properties.System.Author.Value = new string[] { \"Author #1\", \"Author #2\" };\nfile.Properties.System.Title.Value = \"Example Title\";\n\n// Alternate way to Write:\n\nShellPropertyWriter propertyWriter = file.Properties.GetPropertyWriter();\npropertyWriter.WriteProperty(SystemProperties.System.Author, new string[] { \"Author\" });\npropertyWriter.Close();\n Author Title try catch" }, { "answer_id": 46648086, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 3, "selected": false, "text": "var folder = new Shell().NameSpace(folderPath);\nforeach (FolderItem2 item in folder.Items())\n{\n var company = item.ExtendedProperty(\"Company\");\n var author = item.ExtendedProperty(\"Author\");\n // Etc.\n}\n var shellAppType = Type.GetTypeFromProgID(\"Shell.Application\");\ndynamic shellApp = Activator.CreateInstance(shellAppType);\nvar folder = shellApp.NameSpace(folderPath);\nforeach (var item in folder.Items())\n{\n var company = item.ExtendedProperty(\"Company\");\n var author = item.ExtendedProperty(\"Author\");\n // Etc.\n}\n" }, { "answer_id": 49972293, "author": "Rohan", "author_id": 2191900, "author_profile": "https://Stackoverflow.com/users/2191900", "pm_score": 3, "selected": false, "text": "string propertyValue = GetExtendedFileProperty(\"c:\\\\temp\\\\FileNameYouWant.ext\",\"PropertyYouWant\");\n public static string GetExtendedFileProperty(string filePath, string propertyName)\n{\n string value = string.Empty;\n string baseFolder = Path.GetDirectoryName(filePath);\n string fileName = Path.GetFileName(filePath);\n\n //Method to load and execute the Shell object for Windows server 8 environment otherwise you get \"Unable to cast COM object of type 'System.__ComObject' to interface type 'Shell32.Shell'\"\n Type shellAppType = Type.GetTypeFromProgID(\"Shell.Application\");\n Object shell = Activator.CreateInstance(shellAppType);\n Shell32.Folder shellFolder = (Shell32.Folder)shellAppType.InvokeMember(\"NameSpace\", System.Reflection.BindingFlags.InvokeMethod, null, shell, new object[] { baseFolder });\n\n //Parsename will find the specific file I'm looking for in the Shell32.Folder object\n Shell32.FolderItem folderitem = shellFolder.ParseName(fileName);\n if (folderitem != null)\n {\n for (int i = 0; i < short.MaxValue; i++)\n {\n //Get the property name for property index i\n string property = shellFolder.GetDetailsOf(null, i);\n\n //Will be empty when all possible properties has been looped through, break out of loop\n if (String.IsNullOrEmpty(property)) break;\n\n //Skip to next property if this is not the specified property\n if (property != propertyName) continue; \n\n //Read value of property\n value = shellFolder.GetDetailsOf(folderitem, i);\n }\n }\n //returns string.Empty if no value was found for the specified property\n return value;\n}\n" }, { "answer_id": 57445289, "author": "pasx", "author_id": 683319, "author_profile": "https://Stackoverflow.com/users/683319", "pm_score": 1, "selected": false, "text": " var i = 0;\n while (true)\n {\n ...\n if (String.IsNullOrEmpty(header)) break;\n ...\n i++;\n private Dictionary<string, string> GetExtendedProperties(string filePath)\n {\n var directory = Path.GetDirectoryName(filePath);\n var shell = new Shell32.Shell();\n var shellFolder = shell.NameSpace(directory);\n var fileName = Path.GetFileName(filePath);\n var folderitem = shellFolder.ParseName(fileName);\n var dictionary = new Dictionary<string, string>();\n var i = -1;\n while (++i < 320)\n {\n var header = shellFolder.GetDetailsOf(null, i);\n if (String.IsNullOrEmpty(header)) continue;\n var value = shellFolder.GetDetailsOf(folderitem, i);\n if (!dictionary.ContainsKey(header)) dictionary.Add(header, value);\n Console.WriteLine(header +\": \" + value);\n }\n Marshal.ReleaseComObject(shell);\n Marshal.ReleaseComObject(shellFolder);\n return dictionary;\n }\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1769/" ]
220,100
<p>How do I enable double-buffering of a control using C# (Windows forms)?</p> <p>I have a panel control which I am drawing stuff into and also an owner-drawn tab control. Both suffer from flicker, so how can I enable double-buffering?</p>
[ { "answer_id": 220166, "author": "David Wengier", "author_id": 489, "author_profile": "https://Stackoverflow.com/users/489", "pm_score": 5, "selected": true, "text": "this.DoubleBuffered = true;\nthis.SetStyle(ControlStyles.UserPaint | \n ControlStyles.AllPaintingInWmPaint |\n ControlStyles.ResizeRedraw |\n ControlStyles.ContainerControl |\n ControlStyles.OptimizedDoubleBuffer |\n ControlStyles.SupportsTransparentBackColor\n , true);\n" }, { "answer_id": 221272, "author": "Mats Fredriksson", "author_id": 2973, "author_profile": "https://Stackoverflow.com/users/2973", "pm_score": -1, "selected": false, "text": "System.Windows.Forms.Form myForm = new System.Windows.forms.Form();\nmyForm.DoubleBuffered = true;\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220100", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13227/" ]
220,110
<p>I'm looking for a Java library that is geared towards network math and already tested. Nothing particularly fancy, just something to hold ips and subnets, and do things like print a subnet mask or calculate whether an IP is within a given subnet. </p> <p>Should I roll my own, or is there already a robust library for this?</p>
[ { "answer_id": 48216779, "author": "Sean F", "author_id": 6801443, "author_profile": "https://Stackoverflow.com/users/6801443", "pm_score": 2, "selected": false, "text": " String ipv6 = \"2001:db8:57AB:0000:0000:0000:0000:0001\";\n String ipv6subnet = \"2001:db8::/32\";\n String ipv4 = \"1.2.3.4\";\n try {\n IPAddressString ipv6addrstr = new IPAddressString(ipv6);\n IPAddressString ipv6addrsubnetstr = new IPAddressString(ipv6subnet);\n IPAddressString ipv4addrstr = new IPAddressString(ipv4);\n\n IPAddress ipv6addr = ipv6addrstr.toAddress();\n IPAddress ipv6addrsubnet = ipv6addrsubnetstr.toAddress();\n IPAddress ipv4mappedaddr = ipv4addrstr.toAddress().toIPv6();\n\n System.out.println(ipv6addrsubnet + \" contains \" + ipv6addr + \": \" + ipv6addrsubnet.contains(ipv6addr)); //\n System.out.println(ipv6addrsubnet + \" contains \" + ipv4mappedaddr + \": \" + ipv6addrsubnet.contains(ipv4mappedaddr)); //\n\n } catch(AddressStringException e) {\n //e.getMessage has validation error\n }\n 2001:db8::/32 contains 2001:db8:57ab::1 is true\n2001:db8::/32 contains ::ffff:102:304 is false\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13703/" ]
220,112
<p>I like to keep my websites extremely light and fast, but of course I need some kind of user tracking and analytics. </p> <p>It seems like Google Analytics always takes significant enough processing time that I'd like to replace it with something faster (and/or hosted locally), perhaps having less features. </p> <p>I really only care about these metrics: browser, OS, referrer, and # hits per page on a given day or week. </p> <p>Does anyone have any good suggestions, or is Google Analytics really the best option?</p>
[ { "answer_id": 6131702, "author": "roberkules", "author_id": 45948, "author_profile": "https://Stackoverflow.com/users/45948", "pm_score": 0, "selected": false, "text": "// first thing to do, make sure _gaq is defined:\nvar _gaq = _gaq || [];\n\n// set your account settings:\n_gaq.push(['_setAccount', 'UA-XXXXX-X']);\n\n// queue trackpageview whenever you want :)\n_gaq.push(['_trackPageview']);\n\n//////////////////////////////////////////////////////////////////\n\n(function($){\n // load the GA script only after the dom is ready\n // for simplicity using jQuery, of course you can just listen\n // to the DOMContentLoaded / window.load event\n $(function(){\n\n // standard code provided by google to load the GA script\n var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\n ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\n var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\n\n });\n})(jQuery);\n\n//////////////////////////////////////////////////////////////////\n\n// if the script is already loaded, it will execute the tracking request, otherwise it's in the queue\n_gaq.push(['_trackEvent', 'Videos', 'Play', 'Gone With the Wind']);\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220112", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25066/" ]
220,123
<p>I am trying to write a little backup program for friends and family and want it to be as simple to use a possible. I don't want to have to ask the user where to backup their data to, I just want to search for and use the first USB hard drive connected to the computer. Obtaining the unique ID of the hard drive would probably be a good idea too, just as a double check for next time the backup runs.</p>
[ { "answer_id": 220836, "author": "gregmac", "author_id": 7913, "author_profile": "https://Stackoverflow.com/users/7913", "pm_score": 1, "selected": false, "text": "foreach (IO.DriveInfo drive in IO.DriveInfo.GetDrives()) {\n if ((drive.DriveType == IO.DriveType.Removable)) {\n // this is a removable drive\n }\n}\n" }, { "answer_id": 223808, "author": "Stacey Richards", "author_id": 1142, "author_profile": "https://Stackoverflow.com/users/1142", "pm_score": 2, "selected": true, "text": "#include \"stdafx.h\"\n#include <setupapi.h>\n#include <devguid.h>\n#include <cfgmgr32.h>\nextern \"C\" __declspec(dllexport) int usb_hard_drives() {\n HDEVINFO hdevinfo = SetupDiGetClassDevs(&GUID_DEVCLASS_DISKDRIVE, NULL, NULL, DIGCF_PRESENT);\n if (hdevinfo == INVALID_HANDLE_VALUE) return -1;\n DWORD MemberIndex = 0;\n SP_DEVINFO_DATA sp_devinfo_data;\n ZeroMemory(&sp_devinfo_data, sizeof(sp_devinfo_data));\n sp_devinfo_data.cbSize = sizeof(sp_devinfo_data);\n int c = 0;\n while (SetupDiEnumDeviceInfo(hdevinfo, MemberIndex, &sp_devinfo_data)) {\n DWORD PropertyRegDataType;\n DWORD RequiredSize;\n DWORD PropertyBuffer;\n if (SetupDiGetDeviceRegistryProperty(hdevinfo, &sp_devinfo_data, SPDRP_CAPABILITIES, &PropertyRegDataType, (PBYTE)&PropertyBuffer, sizeof(PropertyBuffer), &RequiredSize)) {\n if (PropertyBuffer && CM_DEVCAP_REMOVABLE == CM_DEVCAP_REMOVABLE) {\n // do something here to identify the drive letter.\n c++;\n }\n } \n MemberIndex++;\n }\n SetupDiDestroyDeviceInfoList(hdevinfo);\n return c;\n}\n" }, { "answer_id": 12184547, "author": "Joel", "author_id": 124220, "author_profile": "https://Stackoverflow.com/users/124220", "pm_score": 1, "selected": false, "text": "if( 2 == ::getDriveType( <driveletter> )){\n // its removable \n}\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1142/" ]
220,126
<p>Let's say I have the following code:</p> <pre><code>@sites = Site.find(session[:sites]) # will be an array of Site ids @languages = Language.for_sites(@sites) </code></pre> <p>for_sites is a named_scope in the Language model that returns the languages associated with those sites, and languages are associated with sites using has_many through. The goal is for @languages to have a distinct array of the languages associated with the sites.</p> <p>Instead of calling the Language object on the second line, I'd ideally like to say </p> <pre><code>@sites.languages </code></pre> <p>and have the same list returned to me. Is there any way to do that cleanly in Rails 2.1 (or edge)? I know associations and named scopes can extend the array object to have attributes, but unless I'm missing something that doesn't apply here. Any plugins that do this would be welcome, it doesn't have to be in core.</p>
[ { "answer_id": 220504, "author": "JasonOng", "author_id": 6048, "author_profile": "https://Stackoverflow.com/users/6048", "pm_score": 0, "selected": false, "text": "class Array\n\n def languages\n ...\n end\n\nend\n" }, { "answer_id": 220593, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 0, "selected": false, "text": "has_many has_and_belongs_to_many Site.find( :all, :conditions =>{:id => session[:sites]}, :include => :languages )\n class Site\n named_scope :for_ids, lambda{ |x| {:conditions => {:id => x }\nend\n Site.for_ids(session[:sites]).find(:all, :include => :languages)\n" }, { "answer_id": 221487, "author": "Andrew", "author_id": 17408, "author_profile": "https://Stackoverflow.com/users/17408", "pm_score": 2, "selected": false, "text": "class Site\n named_scope :sites, lambda{|ids| :conditions => \"id in (#{ids.join(',')})\"}\n named_scope :languages, :include => :languages ... (whatever your named scope does)\nend\n Site.sites(session[:sites]).languages\n Site.sites(session[:sites]).languages.collect{|site| site.languages}.flatten\n class Language\n named_scope :for_sites, lambda{|site_ids| :joins => 'inner join sites on languages.site_id = sites.id' :conditions => \"sites.id in (#{site_ids.join(',')})\"}\nend\n Language.for_sites(session[:sites])\n" }, { "answer_id": 229990, "author": "Matt Burke", "author_id": 29691, "author_profile": "https://Stackoverflow.com/users/29691", "pm_score": 3, "selected": true, "text": "class Site\n def find(*args)\n result = super\n result.extend LanguageAggregator if Array === result\n result\n end\nend\n\nmodule LanguageAggregator\n def languages\n Language.find(:all, :conditions => [ 'id in (?)', self.collect { |site| site.id } ])\n end\nend\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220126", "https://Stackoverflow.com", "https://Stackoverflow.com/users/140/" ]
220,142
<p>I need to output the contents of a text field using MS Query Analyzer. I have tried this:</p> <pre><code>select top 1 text from myTable </code></pre> <p>(where text is a <code>text</code> field)</p> <p>and</p> <pre><code>DECLARE @data VarChar(8000) select top 1 @data = text from myTable PRINT @data </code></pre> <p>The first one prints only the first 2000 or so characters and the second only prints the first 8000 characters. Is there any way to get all of the text?</p> <p>Notes:</p> <ul> <li>must work with SQL Server 7</li> </ul>
[ { "answer_id": 220232, "author": "Ryan Abbott", "author_id": 27908, "author_profile": "https://Stackoverflow.com/users/27908", "pm_score": 4, "selected": true, "text": "DECLARE @limit as int,\n @charLen as int,\n @current as int,\n @chars as varchar(8000)\n\nSET @limit = 8000\n\nSELECT TOP 1 @charLen = LEN(text)\nFROM myTable\n\nSET @current = 1\n\nWHILE @current < @charLen\nBEGIN\n SELECT TOP 1 @chars = SUBSTRING(text,@current,@limit)\n FROM myTable\n PRINT @chars\n\n SET @current = @current + @limit\nEND\n" }, { "answer_id": 7834425, "author": "Daniel", "author_id": 172885, "author_profile": "https://Stackoverflow.com/users/172885", "pm_score": 0, "selected": false, "text": "CREATE PROCEDURE [dbo].[LongPrint]\n @String NVARCHAR(MAX)\n\nAS\n\n/*\nExample:\n\nexec LongPrint @string =\n'This String\nExists to test\nthe system.'\n\n*/\n\n/* This procedure is designed to overcome the limitation\nin the SQL print command that causes it to truncate strings\nlonger than 8000 characters (4000 for nvarchar).\n\nIt will print the text passed to it in substrings smaller than 4000\ncharacters. If there are carriage returns (CRs) or new lines (NLs in the text),\nit will break up the substrings at the carriage returns and the\nprinted version will exactly reflect the string passed.\n\nIf there are insufficient line breaks in the text, it will\nprint it out in blocks of 4000 characters with an extra carriage\nreturn at that point.\n\nIf it is passed a null value, it will do virtually nothing.\n\nNOTE: This is substantially slower than a simple print, so should only be used\nwhen actually needed.\n */\n\nDECLARE\n @CurrentEnd BIGINT, /* track the length of the next substring */\n @offset tinyint /*tracks the amount of offset needed */\n\nset @string = replace( replace(@string, char(13) + char(10), char(10)) , char(13), char(10))\n\nWHILE LEN(@String) > 1\nBEGIN\n\nIF CHARINDEX(CHAR(10), @String) between 1 AND 4000\n BEGIN\n\nSET @CurrentEnd = CHARINDEX(char(10), @String) -1\n set @offset = 2\n END\n ELSE\n BEGIN\n SET @CurrentEnd = 4000\n set @offset = 1\n END\n\nPRINT SUBSTRING(@String, 1, @CurrentEnd)\n\nset @string = SUBSTRING(@String, @CurrentEnd+@offset, 1073741822)\n\nEND /*End While loop*/\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/80/" ]
220,146
<p>My applications installer offers the user the ability to run the application as a service through use of the <code>srvany.exe</code> application. To remove the application on uninstall, I've been using the application <code>instsrv.exe</code> with the following command:</p> <blockquote> <p>instsrv "myservice" REMOVE</p> </blockquote> <p>On Windows Server 2003, I encounter error 1783.</p> <p>Any ideas on what is causing this problem? Am I using the wrong approach for <code>Win2k3</code>?</p>
[ { "answer_id": 8461061, "author": "DmitryK", "author_id": 155584, "author_profile": "https://Stackoverflow.com/users/155584", "pm_score": 0, "selected": false, "text": "SC STOP servicename\nSC DELETE servicename\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18836/" ]
220,147
<p>Can someone please let me know how to get the different segments of the three rows that are intersecting in different ways using SQL? The three rows in #t2 represent sets A,B, C - I am looking for A I B, A I C, B I C, A I B I C, A' , B', C' etc., (7 possible segments with 3 rows as in a Venn diagram) where I is the Intersection.</p> <p>I am looking for a generic solution which can handle n number of rows in #t2.</p> <pre><code>-- SQL Code Begin create table #t1 (key1 int, key2 int) -- for each Key1 there can be 1 or more Key2 go create table #t2 (row_id int identity(101, 1), key1 int) --row_id is the primary key go insert into #t1 select 1, 11 union select 1, 12 union select 1, 13 union select 1, 14 union select 2, 13 union select 2, 15 union select 2, 16 union select 2, 17 union select 3, 13 union select 3, 12 union select 3, 16 union select 3, 17 -- 1 --&gt; 11, 12, 13, 14 -- 2 --&gt; 13, 15, 16, 17 -- 3 --&gt; 13, 12, 16, 17 insert into #t2 (key1) select 1 union select 2 union select 3 -- SQL Code End </code></pre> <p>The output I am looking for is,</p> <pre><code>1001 11 (A') 1001 14 (A') 1002 12 (A I C - A I B I C) 1003 13 (A I B I C) 1004 15 (B') 1005 16 (B I C - A I B I C) 1005 17 (B I C - A I B I C) </code></pre> <p>The output has 5 segments, instead of the possible 7 as two of them are NULL.</p>
[ { "answer_id": 220284, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "SELECT key2,\n CASE\n WHEN InA = 1 and InB = 1 and InC = 1 THEN 'ABC'\n WHEN InA = 0 and InB = 1 and InC = 1 THEN 'BC'\n WHEN InA = 1 and InB = 0 and InC = 1 THEN 'AC'\n WHEN InA = 1 and InB = 1 and InC = 0 THEN 'AB'\n WHEN InA = 1 and InB = 0 and InC = 0 THEN 'A'\n WHEN InA = 0 and InB = 1 and InC = 0 THEN 'B'\n WHEN InA = 0 and InB = 0 and InC = 1 THEN 'C'\n ELSE 'I''m broke'\n END as [SubSet]\nFROM\n\n(\nSELECT key2,\n MAX(CASE WHEN key1 = 1 THEN 1 ELSE 0 END) as InA,\n MAX(CASE WHEN key1 = 2 THEN 1 ELSE 0 END) as InB,\n MAX(CASE WHEN key1 = 3 THEN 1 ELSE 0 END) as InC\nFROM #t1\nWHERE key1 in (1, 2, 3)\nGROUP BY key2\n) sub\n\nORDER BY key2\n" }, { "answer_id": 220990, "author": "Dheer", "author_id": 17266, "author_profile": "https://Stackoverflow.com/users/17266", "pm_score": 0, "selected": false, "text": "1, Key1-Value 1\n2, Key1-Value 2\n4, Key1-Value 3\n 1 , 1\n2 , 2\n4 , 3\n select sum(identity), key2\nfrom t1, t2\nwhere t1.key1 = t2.key1\ngroupby key2\n 1 11\n5 12\n7 13\n1 14\n2 15\n6 16\n6 17\n" }, { "answer_id": 221130, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 3, "selected": true, "text": "DECLARE @Key2 INT\nDECLARE @Subset VARCHAR(1000)\nDECLARE @tblResults TABLE\n(\n Key2 INT,\n Subset VARCHAR(1000)\n)\n\nSET @Subset = ''\nSELECT @Key2 = MIN(Key2) FROM #t1\n\nWHILE @Key2 IS NOT NULL\nBEGIN\n SELECT @Subset = @Subset + CAST(Key1 AS VARCHAR(10))\n FROM #t1\n WHERE Key2 = @Key2\n\n INSERT INTO @tblResults (Key2, Subset)\n VALUES (@Key2, @Subset)\n\n SET @Subset = ''\n SELECT @Key2 = MIN(Key2) FROM #t1 WHERE Key2 > @Key2\nEND\n\nSELECT * FROM @tblResults\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26309/" ]
220,149
<p>I want to capture the HTTP request header fields, primarily the Referer and User-Agent, within my client-side JavaScript. How may I access them?</p> <hr> <p>Google Analytics manages to get the data via JavaScript that they have you embed in you pages, so it is definitely possible.</p> <blockquote> <p><strong>Related:</strong><br> <a href="https://stackoverflow.com/questions/220231/accessing-http-headers-in-javascript">Accessing the web page&#39;s HTTP Headers in JavaScript</a></p> </blockquote>
[ { "answer_id": 220169, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 7, "selected": true, "text": "document.referrer navigator.userAgent" }, { "answer_id": 4315364, "author": "Tommy Lacroix", "author_id": 513832, "author_profile": "https://Stackoverflow.com/users/513832", "pm_score": 3, "selected": false, "text": "<script type=\"text/javascript\">\ndocument.write(document.referrer);\n</script>\n <?php echo $_SERVER[\"HTTP_REFERER\"]; ?>\n" }, { "answer_id": 24618498, "author": "silvertback42", "author_id": 3813784, "author_profile": "https://Stackoverflow.com/users/3813784", "pm_score": -1, "selected": false, "text": "var ref = Request.ServerVariables(\"HTTP_REFERER\");\n" }, { "answer_id": 64625138, "author": "Erick RaApa", "author_id": 14138687, "author_profile": "https://Stackoverflow.com/users/14138687", "pm_score": 1, "selected": false, "text": " browser.webRequest.onHeadersReceived.addListener(\n (headersDetails)=> {\n console.log(\"Request: \" + headersDetails);\n },\n {urls: [\"*://hostName/*\"]}\n );`\n browser.webRequest.onHeadersReceived.addListener(\n browser.tabs.executeScript({\n code: 'console.log(\"Headers success\")',\n });\n});\n browser.webRequest.onHeadersReceived.addListener(\n browser.tabs.executeScript({\n file: './headersReveiced.js',\n });\n});\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13930/" ]
220,159
<p>I'd like to log the <em>call trace</em> during certain points, like failed assertions, or uncaught exceptions.</p>
[ { "answer_id": 220168, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 3, "selected": false, "text": "#import <ExceptionHandling/NSExceptionHandler.h>\n\n[[NSExceptionHandler defaultExceptionHandler] \n setExceptionHandlingMask: NSLogUncaughtExceptionMask | \n NSLogUncaughtSystemExceptionMask | \n NSLogUncaughtRuntimeErrorMask]\n" }, { "answer_id": 2322894, "author": "smokris", "author_id": 64860, "author_profile": "https://Stackoverflow.com/users/64860", "pm_score": 10, "selected": true, "text": "NSLog(@\"%@\", NSThread.callStackSymbols);\n NSString backtrace_symbols()" }, { "answer_id": 14228652, "author": "Zayin Krige", "author_id": 541634, "author_profile": "https://Stackoverflow.com/users/541634", "pm_score": 5, "selected": false, "text": "#import <UIKit/UIKit.h>\n\n#import \"AppDelegate.h\"\n\nint main(int argc, char *argv[])\n{\n @autoreleasepool {\n int retval;\n @try{\n retval = UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));\n }\n @catch (NSException *exception)\n {\n NSLog(@\"Gosh!!! %@\", [exception callStackSymbols]);\n @throw;\n }\n return retval;\n }\n}\n" }, { "answer_id": 53263697, "author": "Dipak", "author_id": 1482311, "author_profile": "https://Stackoverflow.com/users/1482311", "pm_score": 1, "selected": false, "text": "print(\"stack trace:\\(Thread.callStackSymbols)\")\n" }, { "answer_id": 69894408, "author": "miragessee", "author_id": 5592365, "author_profile": "https://Stackoverflow.com/users/5592365", "pm_score": -1, "selected": false, "text": "[NSThread callStackSymbols].description\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10184/" ]
220,165
<p>I'm trying to learn GNUMake for a small project I'm working on. So far, even the "basic" tutorials seem pretty rough and I've yet to make sense of the makefile syntax.</p> <p>Does anyone have some good resources for an absolute beginner to get familiar with GNUMake?</p>
[ { "answer_id": 11355908, "author": "FooF", "author_id": 709646, "author_profile": "https://Stackoverflow.com/users/709646", "pm_score": 0, "selected": false, "text": "info pinfo" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1473493/" ]
220,176
<p>If I download a .gem file to a folder in my computer, can I install it later using <code>gem install</code>?</p>
[ { "answer_id": 220181, "author": "Chris Bunch", "author_id": 422, "author_profile": "https://Stackoverflow.com/users/422", "pm_score": 9, "selected": true, "text": "gem install" }, { "answer_id": 286347, "author": "JasonTrue", "author_id": 13433, "author_profile": "https://Stackoverflow.com/users/13433", "pm_score": 8, "selected": false, "text": "gem install --local path_to_gem/filename.gem --local gem install --help" }, { "answer_id": 7956096, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "gem install /full/path/to/your.gem\n" }, { "answer_id": 17057296, "author": "Boris Stitnicky", "author_id": 1153747, "author_profile": "https://Stackoverflow.com/users/1153747", "pm_score": 5, "selected": false, "text": "# do this in the proper directory\nbundle gem foobar\n # cd into your gem directory\nrake install\n rake install" }, { "answer_id": 35004163, "author": "leobelizquierdo", "author_id": 4346603, "author_profile": "https://Stackoverflow.com/users/4346603", "pm_score": 3, "selected": false, "text": "gem install -l gemname.gem" }, { "answer_id": 42891981, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 4, "selected": false, "text": "gem 'pry', path: './pry' ./pry bundle install gem install pry/pry.gem GEM_PATH bundle gem pry gem update" }, { "answer_id": 58331390, "author": "Daniel Antonio Nuñez Carhuayo", "author_id": 1698859, "author_profile": "https://Stackoverflow.com/users/1698859", "pm_score": 1, "selected": false, "text": "[Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache *.gems [Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache [Ruby Installation version]/lib/ruby/gems/[Ruby version]/cache gem install anygemwithdependencieshere cucumber-2.99.0 gem server" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/220176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14755/" ]