qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
316,295
<p>I have a function that exports a table to CSV and in the query I set which fields will export.</p> <p>Here is the query:</p> <pre><code>SELECT lname, fname, email, address1, address2, city, state, zip, venue_id, dtelephone, etelephone, tshirt FROM volunteers_2009 </code></pre> <p>The field venue_id is the the id of the venue which is referred to in another table (venues)</p> <p>So volunteers_2009.venue_id = venues.id</p> <p>When I open the CSV file it displays the venue_id which I understand, but I need help modifying the query to put in the name of the venue (venues.venue_name) within the CSV file.</p> <p>Any help is appreciated.</p>
[ { "answer_id": 316303, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 0, "selected": false, "text": "SELECT a.lname as lname, a.fname as fname, a.email as email,\n a.address1 as address1, a.address2 as address2, a.city as city, \n a.state as state, a.zip as zip, a.venue_id as venue_id,\n b.venue_name as venue_name, a.dtelephone as dtelephone,\n a.etelephone as etelephone, a.tshirt as tshirt\nFROM volunteers_2009 a, venues b\nWHERE a.venue_id = b.id\nAND a.venue_id IS NOT NULL\nUNION ALL\nSELECT a.lname as lname, a.fname as fname, a.email as email,\n a.address1 as address1, a.address2 as address2, a.city as city, \n a.state as state, a.zip as zip, a.venue_id as venue_id,\n '' as venue_name, a.dtelephone as dtelephone,\n a.etelephone as etelephone, a.tshirt as tshirt\nFROM volunteers_2009 a\nWHERE a.venue_id IS NULL\n" }, { "answer_id": 316311, "author": "Nrj", "author_id": 11614, "author_profile": "https://Stackoverflow.com/users/11614", "pm_score": 0, "selected": false, "text": "SELECT lname, fname, email, address1, address2, city, \nstate, zip, b.venue_name, dtelephone, etelephone, tshirt FROM \nvolunteers_2009 a, venues b \nwhere a.venue_id = b. venue_id\n SELECT lname, fname, email, address1, address2, city, \nstate, zip, b.venue_name, dtelephone, etelephone, tshirt FROM \nvolunteers_2009 a(+), venues b \nwhere a.venue_id = b. venue_id\n" }, { "answer_id": 316324, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": true, "text": "SELECT a.lname, a.fname,a. email, a.address1,a. address2, a.city, \n a.state, a.zip, a.venue_id, a.dtelephone, a.etelephone, a.tshirt,\n COALESCE(b.venue_name,'') AS VenueName\nFROM volunteers_2009 a\nLEFT JOIN venues b ON b.id=a.venue_id\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
316,312
<p>From the help for the Overflow Error in VBA, there's the following examples:</p> <pre><code>Dim x As Long x = 2000 * 365 ' gives an error Dim x As Long x = CLng(2000) * 365 ' fine </code></pre> <p>I would have thought that, since the Long data type is supposed to be able to hold 32-bit numbers, that the first example would work fine.</p> <p>I ask this because I have some code like this:</p> <pre><code>Dim Price as Long Price = CLng(AnnualCost * Months / 12) </code></pre> <p>and this throws an Overflow Error when AnnualCost is 5000 and Months is 12.</p> <p>What am I missing?</p>
[ { "answer_id": 316331, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 5, "selected": true, "text": "Dim Price as Long\nPrice = CLng(AnnualCost) * Months / 12\n" }, { "answer_id": 396310, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "Price = CLng(AnnualCost * Months / 12&)\n Const lngMonths12_c as Long = 12\nPrice = CLng(AnnualCost * Months / lngMonths12_c)\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10439/" ]
316,315
<p>Is it possible to determine whether a particular youtube video is encoded with H.264 or FLV through the YouTube data API? If so, how? </p> <p>I can start a file download and check how the video stream was encoded (programmatically, of course), but I'd like to use the YouTube data API to avoid all that overhead.</p>
[ { "answer_id": 316331, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 5, "selected": true, "text": "Dim Price as Long\nPrice = CLng(AnnualCost) * Months / 12\n" }, { "answer_id": 396310, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "Price = CLng(AnnualCost * Months / 12&)\n Const lngMonths12_c as Long = 12\nPrice = CLng(AnnualCost * Months / lngMonths12_c)\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25164/" ]
316,320
<p>I ran into this bug where an element of an array, if its index is the string "0", is inaccessible. </p> <p>It's not a bug with unserialize, either, as this occurred in my code without invoking it.</p> <pre><code>$arr = unserialize('a:1:{s:1:"0";i:5;}'); var_dump($arr["0"]); //should be 5, but is NULL var_dump($arr[0]); //maybe this would work? no. NULL </code></pre> <p>Am I doing something wrong here? How do I access this element of the array?</p>
[ { "answer_id": 316336, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 0, "selected": false, "text": "int(5)\n" }, { "answer_id": 316343, "author": "kranzky", "author_id": 5442, "author_profile": "https://Stackoverflow.com/users/5442", "pm_score": 3, "selected": false, "text": "var_dump( $arr ); // => array(1) { [\"0\"]=> int(5) } \n$arr2[\"0\"]=5;\nvar_dump($arr2); // => array(1) { [0]=> int(5) } \nprint serialize($arr2); // a:1:{i:0;i:5;}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
316,325
<p>I downloaded and installed this version of <a href="http://en.wikipedia.org/wiki/WxPython" rel="nofollow noreferrer">wxPython</a> for use with my Python 2.6 installation:</p> <p><a href="http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe" rel="nofollow noreferrer">http://downloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.9.1-py26.exe</a></p> <p>When I run Python and try to import wx, I get the following error:</p> <pre><code>C:\Program Files\Console2&gt;python Python 2.6 (r26:66721, Oct 2 2008, 11:35:03) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import wx Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\__init__.py", line 45, in &lt;module&gt; from wx._core import * File "c:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_core.py", line 4, in &lt;module&gt; import _core_ ImportError: DLL load failed: This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. &gt;&gt;&gt; </code></pre> <p>I have already tried removing wxPython and installing again and I got the same error. How can I fix this problem?</p>
[ { "answer_id": 853581, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "msvcr90.dll microsoft.vc90.crt.manifest python" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40495/" ]
316,341
<p>Hopefully this is a really quick one ;) I have written a lexer / parser specification in ANTLR3, and am targeting the CSharp2 target. The generated code works correctly, but I can't get ANTLR to put the C# output into a namespace.</p> <p>The relevant section of the Grammar file is as follows:</p> <pre><code>grammar MyGrammar; options { language = CSharp2; output = AST; ASTLabelType = CommonTree; } </code></pre> <p>To generate the correct namespace, I have tried:</p> <pre><code>@namespace { MyNamespace } </code></pre> <p>and</p> <pre><code>@lexer::namespace { MyNamespace } @parser::namespace { MyNamespace } </code></pre> <p>but both of these generate errors, claiming that the file has no rules.</p> <p>Any help is appreciated.</p>
[ { "answer_id": 316858, "author": "Fionn", "author_id": 21566, "author_profile": "https://Stackoverflow.com/users/21566", "pm_score": 4, "selected": true, "text": "grammar Test;\n\noptions\n{\n language=CSharp2;\n}\n\n@lexer::namespace {\n My.Name.Space\n}\n\n@parser::namespace {\n My.Name.Space\n}\n\n\nDIGIT : '0'..'9';\n\nsimple : DIGIT EOF;\n" }, { "answer_id": 12477999, "author": "Rainer", "author_id": 1680403, "author_profile": "https://Stackoverflow.com/users/1680403", "pm_score": 2, "selected": false, "text": "language = 'CSharp3'; @lexer::namespace {\n My.Name.Space\n}\n\n@parser::namespace {\n My.Name.Space\n}\n } // namespace \n My.Name.Space <-- compile error here\n @lexer::namespace {My.Name.Space}\n\n@parser::namespace {My.Name.Space}\n } // namespace My.Name.Space <-- within the line comment, no error of course\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/691/" ]
316,352
<p>In Java, you can qualify local variables and method parameters with the final keyword.</p> <pre><code>public static void foo(final int x) { final String qwerty = "bar"; } </code></pre> <p>Doing so results in not being able to reassign x and qwerty in the body of the method.</p> <p>This practice nudges your code in the direction of immutability which is generally considered a plus. But, it also tends to clutter up code with "final" showing up everywhere. What is your opinion of the final keyword for local variables and method parameters in Java?</p>
[ { "answer_id": 3852070, "author": "fastcodejava", "author_id": 184730, "author_profile": "https://Stackoverflow.com/users/184730", "pm_score": 2, "selected": false, "text": "final final" }, { "answer_id": 3852100, "author": "kartheek", "author_id": 5760280, "author_profile": "https://Stackoverflow.com/users/5760280", "pm_score": 2, "selected": false, "text": "final final" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32174/" ]
316,367
<p>In a comment on a previous question, someone said that the following sql statement opens me up to sql injection:</p> <pre><code>select ss.*, se.name as engine, ss.last_run_at + interval ss.refresh_frequency day as next_run_at, se.logo_name from searches ss join search_engines se on ss.engine_id = se.id where ss.user_id='.$user_id.' group by ss.id order by ss.project_id, ss.domain, ss.keywords </code></pre> <p>Assuming that the <code>$userid</code> variable is properly escaped, how does this make me vulnerable, and what can I do to fix it?</p>
[ { "answer_id": 316372, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": true, "text": "$db_connection = new mysqli(\"localhost\", \"user\", \"pass\", \"db\");\n$statement = $db_connection->prepare(\"SELECT thing FROM stuff WHERE id = ?\");\n$statement->bind_param(\"i\", $user_id); //$user_id is an integer which goes \n //in place of ?\n$statement->execute();\n" }, { "answer_id": 316405, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 1, "selected": false, "text": "prepare execute prepare" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39539/" ]
316,383
<p>i need a C# library about strict HTML validation and filtering </p>
[ { "answer_id": 316372, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": true, "text": "$db_connection = new mysqli(\"localhost\", \"user\", \"pass\", \"db\");\n$statement = $db_connection->prepare(\"SELECT thing FROM stuff WHERE id = ?\");\n$statement->bind_param(\"i\", $user_id); //$user_id is an integer which goes \n //in place of ?\n$statement->execute();\n" }, { "answer_id": 316405, "author": "staticsan", "author_id": 28832, "author_profile": "https://Stackoverflow.com/users/28832", "pm_score": 1, "selected": false, "text": "prepare execute prepare" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/441493/" ]
316,384
<p>How do you go about checking that an IIS website is successfully using Kerberos and not falling back on NTLM?</p>
[ { "answer_id": 319245, "author": "James Newton-King", "author_id": 11829, "author_profile": "https://Stackoverflow.com/users/11829", "pm_score": 3, "selected": true, "text": "Negotiate TlRMTVNTUA\n" }, { "answer_id": 605057, "author": "Christopher G. Lewis", "author_id": 13532, "author_profile": "https://Stackoverflow.com/users/13532", "pm_score": 2, "selected": false, "text": " Authorization Header (Negotiate) appears to contain a Kerberos ticket:\n60 82 13 7B 06 06 2B 06 01 05 05 02 A0 82 13 6F `.{..+..... .o\n WWW-Authenticate Header (Negotiate) appears to be a Kerberos reply:\nA1 81 A0 30 81 9D A0 03 0A 01 00 A1 0B 06 09 2A ¡ 0 ....¡...*\n" }, { "answer_id": 605075, "author": "jsw", "author_id": 55952, "author_profile": "https://Stackoverflow.com/users/55952", "pm_score": 1, "selected": false, "text": "Successful Network Logon:\nUser Name: {Username here}\nDomain: {Domain name here}\nLogon ID: (0x0,0x########)\nLogon Type: 3\nLogon Process: Kerberos\nAuthentication Package: Kerberos\nWorkstation Name: \nLogon GUID: {########-####-####-####-############}\nCaller User Name: -\nCaller Domain: -\nCaller Logon ID: -\nCaller Process ID: -\nTransited Services: -\nSource Network Address: -\nSource Port: -\n\n\nFor more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11829/" ]
316,409
<p>I'm trying out PHPTAL and I want to render a table with zebra stripes. I'm looping through a simple php assoc array ($_SERVER).</p> <p>Note that I don't want to use jQuery or anything like that, I'm trying to learn PHPTAL usage!</p> <p>Currently I have it working like this (too verbose for my liking):</p> <pre><code>&lt;tr tal:repeat="item server"&gt; &lt;td tal:condition="repeat/item/odd" tal:content="repeat/item/key" class="odd"&gt;item key&lt;/td&gt; &lt;td tal:condition="repeat/item/even" tal:content="repeat/item/key" class="even"&gt;item key&lt;/td&gt; &lt;td tal:condition="repeat/item/odd" tal:content="item" class="odd"&gt;item value&lt;/td&gt; &lt;td tal:condition="repeat/item/even" tal:content="item" class="even"&gt;item value&lt;/td&gt; &lt;/tr&gt; </code></pre> <p>Basically I want some kind of conditional assignment on the fly, but I'm unsure of the syntax.</p>
[ { "answer_id": 316420, "author": "starmonkey", "author_id": 29854, "author_profile": "https://Stackoverflow.com/users/29854", "pm_score": 2, "selected": false, "text": "<tr tal:repeat=\"item server\">\n <td tal:content=\"repeat/item/key\" tal:attributes=\"class php: repeat.item.odd ? 'odd' : 'even'\">item key</td>\n <td tal:content=\"item\" tal:attributes=\"class php: repeat.item.odd ? 'odd' : 'even'\">item value</td>\n</tr>\n" }, { "answer_id": 320112, "author": "Kornel", "author_id": 27009, "author_profile": "https://Stackoverflow.com/users/27009", "pm_score": 3, "selected": true, "text": "phptal_tales_evenodd() phptal_tales() <td tal:attributes=\"class evenodd:repeat/item/odd\">\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29854/" ]
316,422
<p>I've built a entity framework model against a 2008 database. All works ok against the 2008 database. When I try to update the entity on a 2005 database I get this error. </p> <pre>The version of SQL Server in use does not support datatype 'datetime2</pre> <p>I specifically did not use any 2008 features when I built the database. I can't find any reference to datetime2 in the code. And, yes the column is defined as "datetime" in the database. </p>
[ { "answer_id": 2211263, "author": "Jason", "author_id": 26860, "author_profile": "https://Stackoverflow.com/users/26860", "pm_score": 4, "selected": false, "text": "<Schema Namespace=\"Foobar.Store\" Alias=\"Self\" Provider=\"System.Data.SqlClient\" ProviderManifestToken=\"2005\" >\n" }, { "answer_id": 8764394, "author": "Vance Kessler", "author_id": 1135166, "author_profile": "https://Stackoverflow.com/users/1135166", "pm_score": 3, "selected": false, "text": "$(SolutionDir)Artifacts\\SetEdmxVer\\SetEdmxSqlVersion $(ProjectDir)MyModel.edmx 2005\n using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Xml;\n\nnamespace SetEdmxSqlVersion\n{\n class Program\n {\n static void Main(string[] args)\n {\n if (2 != args.Length)\n {\n Console.WriteLine(\"usage: SetEdmxSqlVersion <edmxFile> <sqlVer>\");\n return;\n }\n string edmxFilename = args[0];\n string ver = args[1];\n XmlDocument xmlDoc = new XmlDocument();\n xmlDoc.Load(edmxFilename);\n\n XmlNamespaceManager mgr = new XmlNamespaceManager(xmlDoc.NameTable);\n mgr.AddNamespace(\"edmx\", \"http://schemas.microsoft.com/ado/2008/10/edmx\");\n mgr.AddNamespace(\"ssdl\", \"http://schemas.microsoft.com/ado/2009/02/edm/ssdl\");\n XmlNode node = xmlDoc.DocumentElement.SelectSingleNode(\"/edmx:Edmx/edmx:Runtime/edmx:StorageModels/ssdl:Schema\", mgr);\n if (node == null)\n {\n Console.WriteLine(\"Could not find Schema node\");\n }\n else\n {\n Console.WriteLine(\"Setting EDMX version to {0} in file {1}\", ver, edmxFilename);\n node.Attributes[\"ProviderManifestToken\"].Value = ver;\n xmlDoc.Save(edmxFilename);\n }\n }\n }\n}\n" }, { "answer_id": 9914867, "author": "MemeDeveloper", "author_id": 661584, "author_profile": "https://Stackoverflow.com/users/661584", "pm_score": 2, "selected": false, "text": "<Target Name=\"BeforeBuild\">\n <!--Check out BD.edmx, Another.edmx, all configs-->\n <Exec Command=\"$(SolutionDir)\\Library\\tf checkout /lock:none $(ProjectDir)Generation\\DB.edmx\" />\n <Exec Command=\"$(SolutionDir)\\Library\\tf checkout /lock:none $(ProjectDir)Generation\\Another.edmx\" />\n <!--Set to 2008 for Dev-->\n <Exec Condition=\" '$(Configuration)' == 'DEV1' \" Command=\"$(SolutionDir)Library\\SetEdmxSqlVersion $(ProjectDir)Generation\\DB.edmx 2008\" />\n <Exec Condition=\" '$(Configuration)' == 'DEV1' \" Command=\"$(SolutionDir)Library\\SetEdmxSqlVersion $(ProjectDir)Generation\\Another.edmx 2008\" />\n <Exec Condition=\" '$(Configuration)' == 'DEV2' \" Command=\"$(SolutionDir)Library\\SetEdmxSqlVersion $(ProjectDir)Generation\\DB.edmx 2008\" />\n <Exec Condition=\" '$(Configuration)' == 'DEV2' \" Command=\"$(SolutionDir)Library\\SetEdmxSqlVersion $(ProjectDir)Generation\\Another.edmx 2008\" />\n <!--Set to 2005 for Deployments-->\n <Exec Condition=\" '$(Configuration)' == 'TEST' \" Command=\"$(SolutionDir)Library\\SetEdmxSqlVersion $(ProjectDir)Generation\\DB.edmx 2005\" />\n <Exec Condition=\" '$(Configuration)' == 'TEST' \" Command=\"$(SolutionDir)Library\\SetEdmxSqlVersion $(ProjectDir)Generation\\Another.edmx 2005\" />\n <Exec Condition=\" '$(Configuration)' == 'PRODUCTION' \" Command=\"$(SolutionDir)Library\\SetEdmxSqlVersion $(ProjectDir)Generation\\DB.edmx 2005\" />\n <Exec Condition=\" '$(Configuration)' == 'PRODUCTION' \" Command=\"$(SolutionDir)Library\\SetEdmxSqlVersion $(ProjectDir)Generation\\Another.edmx 2005\" />\n </Target>\n" }, { "answer_id": 12060806, "author": "sinelaw", "author_id": 562906, "author_profile": "https://Stackoverflow.com/users/562906", "pm_score": 1, "selected": false, "text": "ProviderManifestToken DbModelBuilder DbProviderInfo Build" }, { "answer_id": 35867046, "author": "Edgar", "author_id": 552448, "author_profile": "https://Stackoverflow.com/users/552448", "pm_score": 2, "selected": false, "text": " <Target Name=\"BeforeBuild\">\n <XmlPeek XmlInputPath=\"$(ProjectDir)MyModel.edmx\"\n Namespaces=\"&lt;Namespace Prefix='edmx' Uri='http://schemas.microsoft.com/ado/2009/11/edmx'/&gt;&lt;Namespace Prefix='ssdl' Uri='http://schemas.microsoft.com/ado/2009/11/edm/ssdl'/&gt;\"\n Query=\"/edmx:Edmx/edmx:Runtime/edmx:StorageModels/ssdl:Schema/@ProviderManifestToken\">\n <Output TaskParameter=\"Result\" ItemName=\"TargetedSQLVersion\" />\n </XmlPeek>\n\n <XmlPoke Condition=\"@(TargetedSQLVersion) != 2008\"\n XmlInputPath=\"$(ProjectDir)MyModel.edmx\"\n Namespaces=\"&lt;Namespace Prefix='edmx' Uri='http://schemas.microsoft.com/ado/2009/11/edmx'/&gt;&lt;Namespace Prefix='ssdl' Uri='http://schemas.microsoft.com/ado/2009/11/edm/ssdl'/&gt;\"\n Query=\"/edmx:Edmx/edmx:Runtime/edmx:StorageModels/ssdl:Schema/@ProviderManifestToken\"\n Value=\"2008\">\n </XmlPoke>\n </Target>\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1351/" ]
316,454
<p>My current problem is that I have a JFrame with a 2x2 GridLayout. And inside one of the squares, I have a JPanel that is to display a grid. I am having a field day with the java swing library... take a look</p> <p><a href="http://img114.imageshack.us/img114/9683/frameow2.jpg" rel="nofollow noreferrer">Image</a></p> <p>Java is automatically expanding each JLabel to fit the screen. I want it to just be those blue squares (water) and the black border and not that gray space. Is there a way I can just set the size of that JPanel permanently so that I don't have to go through changing the size of the JFrame a million times before I get the exact dimension so that the gray space disappears?</p> <p>I also would like to set the size of those buttons so they are not so huge (<code>BorderLayout</code> is being used for the buttons and TextField)</p>
[ { "answer_id": 316460, "author": "javamonkey79", "author_id": 27657, "author_profile": "https://Stackoverflow.com/users/27657", "pm_score": 1, "selected": false, "text": "setResizeable( false )" }, { "answer_id": 316496, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "JPanel GridBagLayout JPanel BorderLayout JLabel BorderLayout.CENTER JPanel theButtonPanel = new JPanel(new BorderLayout());\nJButton button1 = new JButton(\"Fire\");\nJButton button2 = new JButton(\"Pass\");\nJButton button3 = new JButton(\"Forfiet\");\n\nJPanel innerButtonContainer = new JPanel(new Grid(1, 3, 8, 8));\ninnerButtonContainer.add(button1);\ninnerButtonContainer.add(button2);\ninnerButtonContainer.add(button3);\n\ntheButtonPanel.add(innterButtonContainer);\n" }, { "answer_id": 321839, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "TableLayout" }, { "answer_id": 358002, "author": "Jay Sheridan", "author_id": 30619, "author_profile": "https://Stackoverflow.com/users/30619", "pm_score": 2, "selected": false, "text": "GridBagLayout water.setPreferredSize(new Dimension(20, 20));\nwater.setMinimumSize(new Dimension(20, 20));\nwater.setMaximumSize(new Dimension(20, 20));\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29326/" ]
316,463
<p>How would I go upon detecting input for a console application in C#?</p> <p>Let's say for example I want the console application to start up by writing: Welcome To Food Hut (cursor to type stuff here after the first line)</p> <p>I would want the console application to detect two commands:</p> <p>1: /help - which will display some help gibberish.</p> <p>2: /food pizza -t pepperoni -d pepsi - which will display "So you would like a Pizza with Pepperoni and Pepsi to drink?"</p> <p>How would I go upon detecting first what /command was typed and also reading the arguments like -t pepperoni (topping) and -d pepsi (to drink) if /food pizza was typed?</p> <p>My main problem is figuring out how to detect the first word ever typed, figuring out that if it was /help then call some method that would post some help text into the console or if the command is /food then to read what is after the /food command, -t, and -p.</p> <pre><code> static void Main(string[] args) { Console.WriteLine("Welcome To Food Hut"); Console.ReadLine(); // if readline equals to /help then display some help text. // if /food command is typed, read first argument after /food Pizza, -t TheTopping // and -p ForWhatToDrink // and then display, 'So you would like a Pizza with Pepperoni and Pepsi to drink?' } </code></pre>
[ { "answer_id": 316482, "author": "Juliet", "author_id": 40516, "author_profile": "https://Stackoverflow.com/users/40516", "pm_score": 2, "selected": false, "text": "string input = Console.ReadLine();\nif (input == \"/help\") { }\nelse if (input.StartsWith(\"/food\")) { }\nelse { //... }\n Food:\n1) Tofu\n2) Tempeh\n3) Seitan\n4) Soup\n\nChoice (1-4)? [users input]\n\nDrink:\n1) Pepsi\n2) Coffee\n3) Water\n4) Tea\n5) Juice\n\nChoice (1-5)? [users input]\n" }, { "answer_id": 316572, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "input = Console.ReadLine();\nstring[] commands = input.Split(' ');\nif(commands[0] == \"/food\")\n{\n if(commands[1] == \"Pizza\");\n .....\n}\n" }, { "answer_id": 316594, "author": "Stefan Schultze", "author_id": 6358, "author_profile": "https://Stackoverflow.com/users/6358", "pm_score": 5, "selected": false, "text": "static void Main(string[] args)\n{\n Arguments cmdline = new Arguments(args);\n\n Console.WriteLine(cmdline[\"name\"]);\n}\n" }, { "answer_id": 2086762, "author": "Adrian", "author_id": 253264, "author_profile": "https://Stackoverflow.com/users/253264", "pm_score": -1, "selected": false, "text": "mssinp.exe -cf \"C:\\Temp\\config.txt\"\n [0] 'C'\n[1] '\\Temp\\config.txt'\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
316,485
<p>How can I rename a schema using SQL Server? </p>
[ { "answer_id": 316769, "author": "Ray Lu", "author_id": 11413, "author_profile": "https://Stackoverflow.com/users/11413", "pm_score": 5, "selected": false, "text": "ALTER SCHEMA NewSchema TRANSFER OldSchema.Object;\n" }, { "answer_id": 317711, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 6, "selected": false, "text": "USE SandBox\n\nDECLARE @OldSchema AS varchar(255)\nDECLARE @NewSchema AS varchar(255)\nDECLARE @newLine AS varchar(2) = CHAR(13) + CHAR(10)\n\nSET @OldSchema = 'dbo'\nSET @NewSchema = 'StackOverflow'\n\nDECLARE @sql AS varchar(MAX)\n\nSET @sql = 'CREATE SCHEMA [' + @NewSchema + ']' + @newLine\nSELECT @sql = @sql + 'GO' + @newLine\nSELECT @sql = @sql + 'ALTER SCHEMA [' + @NewSchema + '] TRANSFER [' + TABLE_SCHEMA + '].[' + TABLE_NAME + ']'\n + @newLine\nFROM INFORMATION_SCHEMA.TABLES\nWHERE TABLE_SCHEMA = @OldSchema\n\nSET @sql = @sql + 'DROP SCHEMA [' + @OldSchema + ']'\n\nPRINT @sql -- NOTE PRINT HAS AN 8000 byte limit - 8000 varchar/4000 nvarchar - see comments\nIF (0=1) EXEC (@sql)\n" }, { "answer_id": 4582820, "author": "MSAG", "author_id": 560974, "author_profile": "https://Stackoverflow.com/users/560974", "pm_score": 2, "selected": false, "text": "USE DatabaseName\n\nDECLARE @OldSchema AS varchar(255)\nDECLARE @NewSchema AS varchar(255)\n\nSET @OldSchema = 'ComputerLearn'\nSET @NewSchema = 'Basic'\n\nDECLARE @sql AS varchar(MAX)\n\nSET @sql = 'CREATE SCHEMA [' + @NewSchema + ']' + CHAR(13) + CHAR(10)\n\nSELECT @sql = @sql + 'ALTER SCHEMA [' + @NewSchema + '] TRANSFER [' + sys.schemas.name + '].[' + sys.procedures.name + ']'\n + CHAR(13) + CHAR(10)\nFROM sys.procedures,sys.schemas\nWHERE sys.procedures.schema_id=sys.schemas.schema_id and sys.schemas.name = @OldSchema\n\nSET @sql = @sql + 'DROP SCHEMA [' + @OldSchema + ']'\n\nPRINT @sql\nIF (0=1) EXEC (@sql)\n" }, { "answer_id": 12815780, "author": "Adail Retamal", "author_id": 1716719, "author_profile": "https://Stackoverflow.com/users/1716719", "pm_score": 4, "selected": false, "text": "DECLARE @OldSchema AS varchar(255)\nDECLARE @NewSchema AS varchar(255)\n\nSET @OldSchema = 'dbo'\nSET @NewSchema = 'StackOverflow'\n\nDECLARE @sql AS varchar(MAX)\n\nDECLARE @Schema AS varchar(MAX)\nDECLARE @Obj AS varchar(MAX)\n\n-- First transfer Tables and Views\n\nDECLARE CU_OBJS CURSOR FOR\n SELECT TABLE_SCHEMA, TABLE_NAME\n FROM INFORMATION_SCHEMA.TABLES\n WHERE TABLE_SCHEMA = @OldSchema\n\nOPEN CU_OBJS\n\nFETCH NEXT FROM CU_OBJS\nINTO @Schema, @Obj\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n SELECT @sql = 'ALTER SCHEMA [' + @NewSchema + '] TRANSFER [' + @OldSchema + '].[' + @Obj + ']'\n PRINT @sql\n-- EXEC (@sql)\n\n FETCH NEXT FROM CU_OBJS\n INTO @Schema, @Obj\nEND\n\nCLOSE CU_OBJS\nDEALLOCATE CU_OBJS\n\n\n-- Now transfer Stored Procedures\n\nDECLARE CU_OBJS CURSOR FOR\n SELECT sys.schemas.name, sys.procedures.name\n FROM sys.procedures,sys.schemas\n WHERE sys.procedures.schema_id=sys.schemas.schema_id and sys.schemas.name = @OldSchema\n\nOPEN CU_OBJS\n\nFETCH NEXT FROM CU_OBJS\nINTO @Schema, @Obj\n\nWHILE @@FETCH_STATUS = 0\nBEGIN\n SELECT @sql = 'ALTER SCHEMA [' + @NewSchema + '] TRANSFER [' + @Schema + '].[' + @Obj + ']'\n PRINT @sql\n-- EXEC (@sql)\n\n FETCH NEXT FROM CU_OBJS\n INTO @Schema, @Obj\nEND\n\nCLOSE CU_OBJS\nDEALLOCATE CU_OBJS\n" }, { "answer_id": 14208731, "author": "KESAVAN PURUSOTHAMAN", "author_id": 1956974, "author_profile": "https://Stackoverflow.com/users/1956974", "pm_score": 3, "selected": false, "text": " IF OBJECT_ID ( 'dbo.RenameSchema', 'P' ) IS NOT NULL \n DROP PROCEDURE dbo.RenameSchema;\n GO \n\nCREATE PROCEDURE dbo.RenameSchema \n\n @OLDNAME varchar(500),\n@NEWNAME varchar(500)\n\nAS \n /*check for oldschema exist or not */\n IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE name = @OLDNAME)\n\n BEGIN\n\n RETURN\n\n END\n\n /* Create the schema with new name */\n IF NOT EXISTS (SELECT 1 FROM sys.schemas WHERE name = @NEWNAME)\n\n BEGIN\n\n EXECUTE( 'CREATE SCHEMA ' + @NEWNAME );\n\n END \n\n /* get the object under the old schema and transfer those objects to new schema */\n DECLARE Schema_Cursor CURSOR FOR\n\n SELECT ' ALTER SCHEMA ' + @NEWNAME + ' TRANSFER '+ SCHEMA_NAME(SCHEMA_ID)+'.'+ name \n as ALTSQL from sys.objects WHERE type IN ('U','V','P','Fn') AND \n SCHEMA_NAME(SCHEMA_ID) = @OLDNAME;\n\n OPEN Schema_Cursor; \n\n DECLARE @SQL varchar(500) \n\n FETCH NEXT FROM Schema_Cursor INTO @SQL;\n\n WHILE @@FETCH_STATUS = 0\n BEGIN\n exec (@SQL) \n FETCH NEXT FROM Schema_Cursor INTO @SQL;\n END;\n\n CLOSE Schema_Cursor;\n\n DEALLOCATE Schema_Cursor;\n\n /* drop the old schema which should be the user schema */\n IF @OLDNAME <> 'dbo' and @OLDNAME <> 'guest'\n BEGIN\n EXECUTE ('DROP SCHEMA ' + @OLDNAME) \n END\n GO\n EXECUTE RenameSchema 'oldname','newname'\n EXECUTE RenameSchema 'dbo','guest' \n" }, { "answer_id": 36710833, "author": "Kazmi", "author_id": 6201949, "author_profile": "https://Stackoverflow.com/users/6201949", "pm_score": 1, "selected": false, "text": "PopulationByCountrySTG CountryRegionSTG create schema stg\n ALTER SCHEMA stg TRANSFER dbo.PopulationByCountrySTG;\nALTER SCHEMA stg TRANSFER dbo.CountryRegionSTG;\n" }, { "answer_id": 37738609, "author": "Tetrapike", "author_id": 3758810, "author_profile": "https://Stackoverflow.com/users/3758810", "pm_score": 2, "selected": false, "text": "declare @sql varchar(8000), @table varchar(1000), @oldschema varchar(1000), @newschema varchar(1000)\n\n set @oldschema = 'old'\n set @newschema = 'dbo'\n\n while exists(select * from sys.tables where schema_name(schema_id) = @oldschema)\n\n begin\n select @table = name from sys.tables \n where object_id in(select min(object_id) from sys.tables where schema_name(schema_id) = @oldschema)\n\n set @sql = 'alter schema [' + @newschema + '] transfer [' + @oldschema + '].[' + @table + ']'\n\n exec(@sql)\n end\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
316,486
<p>I have been looking at using TDD and implementing proper testing (only just started to learn how much better it makes your life) in any of my projects that I create in the future. So for the last couple of days I have been floating around on SO trying to learn about how to design your application for testability, but I still seem to be struggling with some of the ideas. </p> <p>I have read a lot that you should program <strong>against interfaces</strong> rather than <strong>classes</strong>. The main problem I'm having is, how many interfaces should you create? Should you have one for everything you want to test? or am I reading this wrong?</p> <p>Another thing is use lots of dependency injection, so you can mock the parts that you are injecting rather than use the real things. Is this correct? or am I way off here too?</p>
[ { "answer_id": 316536, "author": "tsimon", "author_id": 1685, "author_profile": "https://Stackoverflow.com/users/1685", "pm_score": 4, "selected": true, "text": "Assert.AreEqual(5, calc.Add(2, 3), \"Adding positives not as expected\");\nAssert.AreEqual(-5, calc.Add(-2, -3), \"Adding negatives not as expected\");\nAssert.AreEqual(-2, calc.Add(-3, 2), \"Adding one positive and one negative not as expected\");\n\n// your framework might provide a cleaner way of doing this:\ntry {\n int result = calc.Add(Int32.Max, 5);\n Assert.Fail(\"Expected overflow error. Received: \" + result);\n} catch(Exception e) {\n // This should be a more specific error that I'm not looking up\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6335/" ]
316,488
<p>What is the best way to construct a bit mask in C with <code>m</code> set bits preceded by <code>k</code> unset bits, and followed by <code>n</code> unset bits:</p> <pre><code>00..0 11..1 00..0 k m n </code></pre> <p>For example, k=1, m=4, n=3 would result in the bit mask:</p> <pre><code>01111000 </code></pre>
[ { "answer_id": 316493, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 6, "selected": true, "text": "~(~0 << m) << n\n" }, { "answer_id": 316494, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 5, "selected": false, "text": "mask = ((1 << m) - 1) << n;\n" }, { "answer_id": 316796, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 3, "selected": false, "text": "\n((~((unsigned int)0) << k) >> (k + n)) << n\n ~0 >> n #include <stdio.h>\n#include <limits.h>\n\nenum { ULONG_BITS = (sizeof(unsigned long) * CHAR_BIT) };\n\nstatic unsigned long set_mask_1(int k, int m, int n)\n{\n return ~(~0 << m) << n;\n}\n\nstatic unsigned long set_mask_2(int k, int m, int n)\n{\n return ((1 << m) - 1) << n;\n}\n\nstatic unsigned long set_mask_3(int k, int m, int n)\n{\n return ((~((unsigned long)0) << k) >> (k + n)) << n;\n}\n\nstatic int test_cases[][2] =\n{\n { 1, 0 },\n { 1, 1 },\n { 1, 2 },\n { 1, 3 },\n { 2, 1 },\n { 2, 2 },\n { 2, 3 },\n { 3, 4 },\n { 3, 5 },\n};\n\nint main(void)\n{\n size_t i;\n for (i = 0; i < 9; i++)\n {\n int m = test_cases[i][0];\n int n = test_cases[i][1];\n int k = ULONG_BITS - (m + n);\n printf(\"%d/%d/%d = 0x%08lX = 0x%08lX = 0x%08lX\\n\", k, m, n,\n set_mask_1(k, m, n),\n set_mask_2(k, m, n),\n set_mask_3(k, m, n));\n }\n return 0;\n}\n" }, { "answer_id": 45574016, "author": "Nubcake", "author_id": 4575668, "author_profile": "https://Stackoverflow.com/users/4575668", "pm_score": 1, "selected": false, "text": "n=0 m=31 ~(~0 << 31) << 0 0111 1111 1111 1111 1111 1111 1111 1111‬ ((1 << 31)-1) << 0 0111 1111 1111 1111 1111 1111 1111 1111‬ unsigned int create_mask(unsigned int n,unsigned int m) {\n // 0 <= start_bit, end_bit <= 31\n assert(n >=0 && m<=31);\n return (m - n == 31 ? ~0: ((1 << (m-n)+1)-1) << n);\n}\n [m,n] create_mask(0,0) create_mask(4,6) ... 00111 0000" }, { "answer_id": 45579825, "author": "wim", "author_id": 2439725, "author_profile": "https://Stackoverflow.com/users/2439725", "pm_score": 1, "selected": false, "text": "mask = _bzhi_u32(-1,m)<<n;\n bzhi _bzhi_u32 #include <stdio.h>\n#include <x86intrin.h>\n/* gcc -O3 -Wall -m64 -march=haswell bitmsk_mn.c */\n\nunsigned int bitmsk(unsigned int m, unsigned int n)\n{\n return _bzhi_u32(-1,m)<<n;\n}\n\nint main() {\n int k = bitmsk(7,13);\n printf(\"k= %08X\\n\",k);\n return 0;\n}\n $./a.out\nk= 000FE000\n _bzhi_u32(-1,m)<<n movl $-1, %edx\nbzhi %edi, %edx, %edi\nshlx %esi, %edi, %eax\n bzhi shlx" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1692070/" ]
316,508
<p>I am trying to write a JavaScript script to add to greasemonkey that adds a button after an element. The onClick for this button should copy the parents element text to the keyboard. I have seen plenty of examples that copy already selected text to the clipboard such as this:</p> <pre><code> &lt;SCRIPT LANGUAGE="JavaScript"&gt; &lt;!-- Begin function copyit(theField) { var selectedText = document.selection; if (selectedText.type == 'Text') { var newRange = selectedText.createRange(); theField.focus(); theField.value = newRange.text; } else { alert('Alert: Select The text in the textarea then click on this button'); } } // End --&gt; &lt;/script&gt; &lt;input onclick="copyit(this.form.text_select)" type="button" value="Click Here to Copy the Highlighted Text" name="copy_button"&gt; </code></pre> <p>Found <a href="http://www.wallpaperama.com/forums/javascript-copy-selected-text-box-select-all-highlight-text-form-copy-paste-t706.html" rel="noreferrer">here</a>. </p> <p>I have also found that you can select text in input elements. I have tried combining both techniques, as well as many others with no viable solution yet. I am not even sure why the code above copies to the clipboard. Does anyone have a solution to this? </p>
[ { "answer_id": 348379, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 4, "selected": true, "text": "var tc = textToCopy.replace(/\\n\\n/g, '\\n');\nif (window.clipboardData) // IE\n{\n window.clipboardData.setData(\"Text\", tc);\n}\nelse\n{\n unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege(\"UniversalXPConnect\");\n const clipboardHelper = Components.classes\n [\"@mozilla.org/widget/clipboardhelper;1\"].\n getService(Components.interfaces.nsIClipboardHelper);\n clipboardHelper.copyString(tc);\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27657/" ]
316,520
<p>I saw this signature on the ListView class:</p> <pre><code>public ListView..::.ListViewItemCollection Items { get; } </code></pre> <p>When I saw that, "What?!"</p> <p>I searched "dot dot colon colon dot" and "..::." on Google with no result.</p> <p><img src="https://i.stack.imgur.com/av0FO.png" alt="alt text"></p>
[ { "answer_id": 316568, "author": "tsimon", "author_id": 1685, "author_profile": "https://Stackoverflow.com/users/1685", "pm_score": -1, "selected": false, "text": "public class ListView {\n public ListViewItemCollection Items {get;}\n\n public class ListViewItemCollection : IList {\n // more code here\n }\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11238/" ]
316,524
<p>I wish to find all rows in a table where one column is a substring of another column.</p> <p>In other words, suppose I have a table (called people) with two columns: firstname and lastname, and I want to find all people like "rob robinowitz" and "jill bajillion".</p> <p>Is there a way to do something like "select * from people where lastname like %firstname%"? (But something which actually works).</p>
[ { "answer_id": 316539, "author": "Dmitry Khalatov", "author_id": 18174, "author_profile": "https://Stackoverflow.com/users/18174", "pm_score": 4, "selected": true, "text": "select * from people where lastname like '%' + firstname + '%'\n select * from people where charindex(firstname,lastname)>0\n" }, { "answer_id": 316542, "author": "kmkaplan", "author_id": 24774, "author_profile": "https://Stackoverflow.com/users/24774", "pm_score": 0, "selected": false, "text": "SELECT * FROM people WHERE INSTR(lastname, firstname) <> 0\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31060/" ]
316,528
<p>Sounds easy, but I can't find where this built in class and others exists in the documentation. I use functions but want to know what there is on the OO side.</p>
[ { "answer_id": 316541, "author": "majelbstoat", "author_id": 38812, "author_profile": "https://Stackoverflow.com/users/38812", "pm_score": 2, "selected": false, "text": "Reflection::export(new ReflectionClass('DateTime'));\n\nClass [ class DateTime ] {\n\n - Constants [11] {\n Constant [ string ATOM ] { Y-m-d\\TH:i:sP }\n Constant [ string COOKIE ] { l, d-M-y H:i:s T }\n Constant [ string ISO8601 ] { Y-m-d\\TH:i:sO }\n Constant [ string RFC822 ] { D, d M y H:i:s O }\n Constant [ string RFC850 ] { l, d-M-y H:i:s T }\n Constant [ string RFC1036 ] { D, d M y H:i:s O }\n Constant [ string RFC1123 ] { D, d M Y H:i:s O }\n Constant [ string RFC2822 ] { D, d M Y H:i:s O }\n Constant [ string RFC3339 ] { Y-m-d\\TH:i:sP }\n Constant [ string RSS ] { D, d M Y H:i:s O }\n Constant [ string W3C ] { Y-m-d\\TH:i:sP }\n }\n\n - Static properties [0] {\n }\n\n - Static methods [0] {\n }\n\n - Properties [0] {\n }\n\n - Methods [9] {\n Method [ public method __construct ] {\n }\n\n Method [ public method format ] {\n }\n\n Method [ public method modify ] {\n }\n\n Method [ public method getTimezone ] {\n }\n\n Method [ public method setTimezone ] {\n }\n\n Method [ public method getOffset ] {\n }\n\n Method [ public method setTime ] {\n }\n\n Method [ public method setDate ] {\n }\n\n Method [ public method setISODate ] {\n }\n }\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10117/" ]
316,532
<p>If I have code like this:</p> <pre><code> public XALServiceConfiguration CreateInstance() { var config = ConfigurationManager.GetSection(ConfigurationSectionName) as XALServiceConfiguration; if (config == null) throw new ConfigurationErrorsException("Configuration element 'xalService' was not found or is not of correct type."); return config; } </code></pre> <p>How can I test that the exception is thrown if the section is missing from the configuration file ? For other tests, the configuration section needs to be in the config file, so I cannot actually remove it from the file.</p> <p>I am using the Visual Studio 2008 Unit test framework.</p>
[ { "answer_id": 316538, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 0, "selected": false, "text": "try catch Assert" }, { "answer_id": 316553, "author": "tsimon", "author_id": 1685, "author_profile": "https://Stackoverflow.com/users/1685", "pm_score": 1, "selected": false, "text": "try {\n XALServiceConfiguration config = CreateInstance();\n} catch (ConfigurationErrorsException cee) {\n Assert.Fail(\"Could not create XALServiceConfiguration: \" + e.Message);\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13627/" ]
316,540
<p>I want add the new node as parent node of the old nodes in XML using C#. for example node have the following XMl file:</p> <pre><code>&lt;bookstore&gt; &lt;books&gt; &lt;author&gt; &lt;/author&gt; &lt;/books&gt; &lt;/bookstore&gt; </code></pre> <p>like that now I want add the new like below:</p> <pre><code>&lt;bookstore&gt; &lt;newnode&gt; &lt;books&gt; &lt;author&gt; &lt;/author&gt; &lt;/books&gt; &lt;/newnode&gt; &lt;/bookstore&gt; </code></pre>
[ { "answer_id": 316561, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "XmlDocument xd = new XmlDocument();\nxd.Load(\"oldxmlfile.xml\");\nXmlNode oldNode = xd[\"nameOfRootNode\"];\nxd.RemoveAll();\nXmlNode newParent = xd.CreateNode(\"nodename\");\nnewParent.AppendChild(oldNode);\nxd.AppendChild(newParent);\nxd.Save(\"newXmlFile.xml\");\n" }, { "answer_id": 316698, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "XmlDocument doc = new XmlDocument();\n// load the current xml\ndoc.LoadXml(xml);\n// create a new \"newnode\" node and add it into the tree\nXmlElement newnode = (XmlElement) doc.DocumentElement.AppendChild(doc.CreateElement(\"newnode\"));\n// locate the original \"books\" node and move it\nnewnode.AppendChild(doc.SelectSingleNode(\"/bookstore/books\"));\n// show the result\nConsole.WriteLine(doc.OuterXml);\n" }, { "answer_id": 316707, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 2, "selected": false, "text": "XmlDocument doc = new XmlDocument();\ndoc.Load(\"BookStore.xml\");\nXmlElement newNode = doc.CreateElement(\"newnode\");\ndoc.DocumentElement.AppendChild(newNode);\nnewNode.AppendChild(doc.SelectSingleNode(\"/bookstore/books\"));\ndoc.Save(\"BookStore.xml\");\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
316,574
<p>Are there any command line interfaces to the DHCP settings in Mac OS X? I have found that inside System Profiler, the Network tab provides a lot of useful information, but I have not found any documentation about any command line equivalents.</p>
[ { "answer_id": 316598, "author": "Jason Coco", "author_id": 34218, "author_profile": "https://Stackoverflow.com/users/34218", "pm_score": -1, "selected": false, "text": "ifconfig(8)\nnetstat(1)\nnetintro(4)\n" }, { "answer_id": 316601, "author": "Arne Burmeister", "author_id": 12890, "author_profile": "https://Stackoverflow.com/users/12890", "pm_score": 5, "selected": true, "text": "networksetup -listallnetworkservices\nnetworksetup -getinfo <networkservice>\nnetworksetup -setdhcp <networkservice> [clientid]\n" }, { "answer_id": 327302, "author": "tegbains", "author_id": 19419, "author_profile": "https://Stackoverflow.com/users/19419", "pm_score": 3, "selected": false, "text": "ipconfig getpacket `interface`\n en0, en1 ipconfig getpacket en1\nop = BOOTREPLY\nhtype = 1\nflags = 0\nhlen = 6\nhops = 0\nxid = 215448168\nsecs = 3\nciaddr = 0.0.0.0\nyiaddr = 192.168.15.121\nsiaddr = 0.0.0.0\ngiaddr = 0.0.0.0\nchaddr = 0:19:e3:6:70:95\nsname = \nfile = \noptions:\nOptions count is 8\ndhcp_message_type (uint8): ACK 0x5\nserver_identifier (ip): 192.168.15.1\nlease_time (uint32): 0xa8c0\nsubnet_mask (ip): 255.255.255.0\nrouter (ip_mult): {192.168.15.1}\ndomain_name_server (ip_mult): {192.168.15.249, 192.168.15.240}\ndomain_name (string): domain.com\nend (none): \n ipconfig getoption en0 optionname\n ipconfig getoption en1 router 192.168.15.1\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2910/" ]
316,581
<p>I have a batch file that does this.</p> <p>ECHO A41,35,0,a,1,1,N,"Mr ZACHARY KAPLAN">> test.txt </p> <p>There are about 30k similar lines. It takes the batch file about 5 hours to run. </p> <p>Is there a way to speed this up?</p> <p>/Jeanre</p>
[ { "answer_id": 316631, "author": "hasen", "author_id": 35364, "author_profile": "https://Stackoverflow.com/users/35364", "pm_score": 1, "selected": false, "text": ">>> import re\n>>> text = 'ECHO A41,35,0,a,1,1,N,\"Mr ZACHARY KAPLAN\">> test.txt'\n>>> re.sub( r\"ECHO\\s*(.*?)>>\\s*test.txt\", r\"\\1\", text )\n'A41,35,0,a,1,1,N,\"Mr ZACHARY KAPLAN\"'\n import re\nf = open(\"input.bat\")\nof = open(\"output.txt\", \"w\" )\nfor line in f:\n of.write( re.sub( r\"ECHO\\s*(.*?)>>\\s*test.txt\", r\"\\1\", line ) )\n" }, { "answer_id": 316691, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": 2, "selected": false, "text": "ECHO OFF ECHO A41,35,0,a,1,1,N,\"Mr ZACHARY KAPLAN\"\n" }, { "answer_id": 8137344, "author": "jimmy", "author_id": 1047614, "author_profile": "https://Stackoverflow.com/users/1047614", "pm_score": 2, "selected": false, "text": "JAM DO %%Fo CAt Pa (set /p %yodo%=jol)\n\nRUn\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
316,582
<p>I want to pose a question such as:</p> <blockquote> <p>What is your name? Joe</p> </blockquote> <p>How would I accomplish this using <code>Console.WriteLine</code> to also wait for the response on that same line instead of it being broken into:</p> <blockquote> <p>What is your name?</p> <p>Joe</p> </blockquote>
[ { "answer_id": 316583, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 7, "selected": true, "text": "Console.Write Console.Write(\"What is your name? \");\nvar name = Console.ReadLine();\n" }, { "answer_id": 316587, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "Console.Write WriteLine Console.Write Console.Write(\"What is your name? \");\nConsole.Out.Flush();\nvar name = Console.ReadLine();\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
316,590
<p>Suppose I want to count the lines of code in a project. If all of the files are in the same directory I can execute:</p> <pre><code>cat * | wc -l </code></pre> <p>However, if there are sub-directories, this doesn't work. For this to work cat would have to have a recursive mode. I suspect this might be a job for xargs, but I wonder if there is a more elegant solution?</p>
[ { "answer_id": 316602, "author": "chromakode", "author_id": 40508, "author_profile": "https://Stackoverflow.com/users/40508", "pm_score": 4, "selected": false, "text": "find find . -type f -execdir cat {} \\; | wc -l" }, { "answer_id": 316605, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 4, "selected": false, "text": "find -name '*php' | xargs cat | wc -l\n" }, { "answer_id": 316613, "author": "philant", "author_id": 18804, "author_profile": "https://Stackoverflow.com/users/18804", "pm_score": 8, "selected": true, "text": "cat wc wc -l * \n find find . -name \"*.c\" -exec wc -l {} \\;\n . -name \"*.c\" -exec {} wc-l \\; -print find . -name \"*.c\" -print | xargs wc -l \n -print0 -print xargs -null find . -name \"*.c\" -print0 | xargs -0 wc -l\n" }, { "answer_id": 316639, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 5, "selected": false, "text": "grep '' -R . | wc -l \n find . -exec wc -l {} \\;\n find . -exec wc -l {} + \n grep '' -IR . | wc -l\n grep '' -aR . | wc -l \n cd /usr/include;\nfind -type f -exec perl -e 'printf qq[%s => %s\\n], scalar @ARGV, length join q[ ], @ARGV' {} + \n# 4066 => 130974\n# 3399 => 130955\n# 3155 => 130978\n# 2762 => 130991\n# 3923 => 130959\n# 3642 => 130989\n# 4145 => 130993\n# 4382 => 130989\n# 4406 => 130973\n# 4190 => 131000\n# 4603 => 130988\n# 3060 => 95435\n" }, { "answer_id": 316640, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 3, "selected": false, "text": "find . -name \"*.c\" -print0 | xargs -0 cat | wc -l\n" }, { "answer_id": 5613184, "author": "abalmos", "author_id": 699598, "author_profile": "https://Stackoverflow.com/users/699598", "pm_score": 1, "selected": false, "text": "find . -type f -exec wc -l {} \\; | awk '{total += $1} END{print total}'\n" }, { "answer_id": 16262231, "author": "Dave Pitts", "author_id": 200438, "author_profile": "https://Stackoverflow.com/users/200438", "pm_score": 2, "selected": false, "text": "find . -name \"*rb\" -print0 | xargs -0 head -10000\n ==> ./recipes/default.rb <==\nDOWNLOAD_DIR = '/tmp/downloads'\nMYSQL_DOWNLOAD_URL = 'http://cdn.mysql.com/Downloads/MySQL-5.6/mysql-5.6.10-debian6.0-x86_64.deb'\nMYSQL_DOWNLOAD_FILE = \"#{DOWNLOAD_DIR}/mysql-5.6.10-debian6.0-x86_64.deb\"\n\npackage \"mysql-server-5.5\"\n...\n\n==> ./templates/default/my.cnf.erb <==\n#\n# The MySQL database server configuration file.\n#\n...\n\n==> ./templates/default/mysql56.sh.erb <==\nPATH=/opt/mysql/server-5.6/bin:$PATH \n" }, { "answer_id": 22774421, "author": "curran", "author_id": 2188100, "author_profile": "https://Stackoverflow.com/users/2188100", "pm_score": 0, "selected": false, "text": "# $excluded is a regex for paths to exclude from line counting\nexcluded=\"spec\\|node_modules\\|README\\|lib\\|docs\\|csv\\|XLS\\|json\\|png\"\n\ncountLines(){\n # $total is the total lines of code counted\n total=0\n # -mindepth exclues the current directory (\".\")\n for file in `find . -mindepth 1 -name \"*.*\" |grep -v \"$excluded\"`; do\n # First sed: only count lines of code that are not commented with //\n # Second sed: don't count blank lines\n # $numLines is the lines of code\n numLines=`cat $file | sed '/\\/\\//d' | sed '/^\\s*$/d' | wc -l`\n total=$(($total + $numLines))\n echo \" \" $numLines $file\n done\n echo \" \" $total in total\n}\n\necho Source code files:\ncountLines\necho Unit tests:\ncd spec\ncountLines\n Source code files:\n 2 ./buildDocs.sh\n 24 ./countLines.sh\n 15 ./css/dashboard.css\n 53 ./data/un_population/provenance/preprocess.js\n 19 ./index.html\n 5 ./server/server.js\n 2 ./server/startServer.sh\n 24 ./SpecRunner.html\n 34 ./src/computeLayout.js\n 60 ./src/configDiff.js\n 18 ./src/dashboardMirror.js\n 37 ./src/dashboardScaffold.js\n 14 ./src/data.js\n 68 ./src/dummyVis.js\n 27 ./src/layout.js\n 28 ./src/links.js\n 5 ./src/main.js\n 52 ./src/processActions.js\n 86 ./src/timeline.js\n 73 ./src/udc.js\n 18 ./src/wire.js\n 664 in total\nUnit tests:\n 230 ./ComputeLayoutSpec.js\n 134 ./ConfigDiffSpec.js\n 134 ./ProcessActionsSpec.js\n 84 ./UDCSpec.js\n 149 ./WireSpec.js\n 731 in total\n" }, { "answer_id": 23890207, "author": "SD.", "author_id": 2007944, "author_profile": "https://Stackoverflow.com/users/2007944", "pm_score": 0, "selected": false, "text": "find . -name \"*.h\" -print | xargs wc -l\n" }, { "answer_id": 25460713, "author": "PMD", "author_id": 3970453, "author_profile": "https://Stackoverflow.com/users/3970453", "pm_score": 2, "selected": false, "text": "wc -cl `find . -name \"*.php\" -type f`\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316590", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39584/" ]
316,626
<p>I have a version resource in my resources in a C++ project which contains version number, copyright and build details. Is there an easy way to access this at run-time to populate my <em>help/about</em> dialog as I am currently maintaining seperate const values of this information. Ideally, the solution should work for Windows/CE mobile and earlier versions of Visual C++ (6.0 upwards).</p>
[ { "answer_id": 316633, "author": "Rob", "author_id": 9236, "author_profile": "https://Stackoverflow.com/users/9236", "pm_score": 3, "selected": false, "text": "HRSRC res = ::FindResource(NULL, MAKEINTRESOURCE(MY_VERSION_ID), RT_VERSION);\nDWORD size = ::SizeofResource(NULL, res);\nHGLOBAL mem = ::LoadResource(NULL, res);\nLPVOID raw_data = ::LockResource(mem);\n...\n::FreeResource(mem);\n" }, { "answer_id": 316725, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 3, "selected": false, "text": "TCHAR moduleName[MAX_PATH+1];\n(void)GetModuleFileName(AfxGetInstanceHandle(), moduleName, MAX_PATH);\nDWORD dummyZero;\nDWORD versionSize = GetFileVersionInfoSize(moduleName, &dummyZero);\nif(versionSize == 0)\n{\n return NULL;\n}\nvoid* pVersion = malloc(versionSize);\nif(pVersion == NULL)\n{\n return NULL;\n}\nif(!GetFileVersionInfo(moduleName, NULL, versionSize, pVersion))\n{\n free(pVersion);\n return NULL;\n}\n\nUINT length;\nVS_FIXEDFILEINFO* pFixInfo;\nVERIFY(VerQueryValue(pVersionInfo, const_cast<LPTSTR>(\"\\\\\"), (LPVOID*)&pFixInfo, &length));\n" }, { "answer_id": 1174697, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 6, "selected": true, "text": "bool GetProductAndVersion(CStringA & strProductName, CStringA & strProductVersion)\n{\n // get the filename of the executable containing the version resource\n TCHAR szFilename[MAX_PATH + 1] = {0};\n if (GetModuleFileName(NULL, szFilename, MAX_PATH) == 0)\n {\n TRACE(\"GetModuleFileName failed with error %d\\n\", GetLastError());\n return false;\n }\n\n // allocate a block of memory for the version info\n DWORD dummy;\n DWORD dwSize = GetFileVersionInfoSize(szFilename, &dummy);\n if (dwSize == 0)\n {\n TRACE(\"GetFileVersionInfoSize failed with error %d\\n\", GetLastError());\n return false;\n }\n std::vector<BYTE> data(dwSize);\n\n // load the version info\n if (!GetFileVersionInfo(szFilename, NULL, dwSize, &data[0]))\n {\n TRACE(\"GetFileVersionInfo failed with error %d\\n\", GetLastError());\n return false;\n }\n\n // get the name and version strings\n LPVOID pvProductName = NULL;\n unsigned int iProductNameLen = 0;\n LPVOID pvProductVersion = NULL;\n unsigned int iProductVersionLen = 0;\n\n // replace \"040904e4\" with the language ID of your resources\n if (!VerQueryValue(&data[0], _T(\"\\\\StringFileInfo\\\\040904e4\\\\ProductName\"), &pvProductName, &iProductNameLen) ||\n !VerQueryValue(&data[0], _T(\"\\\\StringFileInfo\\\\040904e4\\\\ProductVersion\"), &pvProductVersion, &iProductVersionLen))\n {\n TRACE(\"Can't obtain ProductName and ProductVersion from resources\\n\");\n return false;\n }\n\n strProductName.SetString((LPCSTR)pvProductName, iProductNameLen);\n strProductVersion.SetString((LPCSTR)pvProductVersion, iProductVersionLen);\n\n return true;\n}\n" }, { "answer_id": 5222343, "author": "EdM", "author_id": 185082, "author_profile": "https://Stackoverflow.com/users/185082", "pm_score": 4, "selected": false, "text": " // replace \"040904e4\" with the language ID of your resources\n !VerQueryValue(&data[0], _T(\"\\\\StringFileInfo\\\\040904e4\\\\ProductVersion\"), &pvProductVersion, &iProductVersionLen))\n{\n TRACE(\"Can't obtain ProductName and ProductVersion from resources\\n\");\n return false;\n}\n UINT uiVerLen = 0;\nVS_FIXEDFILEINFO* pFixedInfo = 0; // pointer to fixed file info structure\n// get the fixed file info (language-independent) \nif(VerQueryValue(&data[0], TEXT(\"\\\\\"), (void**)&pFixedInfo, (UINT *)&uiVerLen) == 0)\n{\n return false;\n}\n\n strProductVersion.Format(\"%u.%u.%u.%u\", \n HIWORD (pFixedInfo->dwProductVersionMS),\n LOWORD (pFixedInfo->dwProductVersionMS),\n HIWORD (pFixedInfo->dwProductVersionLS),\n LOWORD (pFixedInfo->dwProductVersionLS));\n" }, { "answer_id": 12219041, "author": "Vitaly", "author_id": 1639181, "author_profile": "https://Stackoverflow.com/users/1639181", "pm_score": 0, "selected": false, "text": "VerQueryValueA VerQueryValueW VerQueryValueA VerQueryValueW VerQueryValueA ReadVersion" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22564/" ]
316,629
<p>I'm adding avatars to a forum engine I'm designing, and I'm debating whether to do something simple (forum image is named .png) and use PHP to check if the file exists before displaying it, or to do something a bit more complicated (but not much) and use a database field to contain the name of the image to show.</p> <p>I'd much rather go with the file_exists() method personally, as that gives me an easy way to fall back to a "default" avatar if the current one doesn't exist (yet), and its simple to implement code wise. However, I'm worried about performance, since this will be run once per user shown per pageload on the forum read pages. So I'd like to know, does the file_exists() function in PHP cause any major slowdowns that would cause significant performance hits in high traffic conditions?</p> <p>If not, great. If it does, what is your opinion on alternatives for keeping track of a user-uploaded image? Thanks!</p> <p>PS: The code differences I can see are that the file checking versions lets the files do the talking, while the database form trusts that the database is accurate and doesn't bother to check. (its just a url that gets passed to the browser of course.)</p>
[ { "answer_id": 316729, "author": "Zebra North", "author_id": 17440, "author_profile": "https://Stackoverflow.com/users/17440", "pm_score": 5, "selected": true, "text": "SELECT CONCAT(IF(has_avatar, id, 'default'), '.png') AS avatar FROM users" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19521/" ]
316,649
<p>I am trying to use C# to parse CSV. I used regular expressions to find <code>","</code> and read string if my header counts were equal to my match count.</p> <p>Now this will not work if I have a value like:</p> <pre><code>"a",""b","x","y"","c" </code></pre> <p>then my output is:</p> <pre><code>'a' '"b' 'x' 'y"' 'c' </code></pre> <p>but what I want is:</p> <pre><code>'a' '"b","x","y"' 'c' </code></pre> <p>Is there any regex or any other logic I can use for this ?</p>
[ { "answer_id": 316663, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 0, "selected": false, "text": "\"a\", \"\"b\", \"\"c\", \"d\"\", \"e\"\"" }, { "answer_id": 316669, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "(\"\".*?\"\"|\"[^\"]*\")\n \"(\".*?\"|[^\"]*)\"\n" }, { "answer_id": 316733, "author": "Bevan", "author_id": 30280, "author_profile": "https://Stackoverflow.com/users/30280", "pm_score": 2, "selected": false, "text": " public IEnumerable<string> SplitCSV(string line)\n {\n int index = 0;\n int start = 0;\n bool inString = false;\n\n foreach (char c in line)\n {\n switch (c)\n {\n case '\"':\n inString = !inString;\n break;\n\n case ',':\n if (!inString)\n {\n yield return line.Substring(start, index - start);\n start = index + 1;\n }\n break;\n }\n index++;\n }\n\n if (start < index)\n yield return line.Substring(start, index - start);\n }\n yield return inSingleQuotedString inDoubleQuotedString" }, { "answer_id": 317016, "author": "saku", "author_id": 30726, "author_profile": "https://Stackoverflow.com/users/30726", "pm_score": 2, "selected": false, "text": "public static List<string> SplitCSV(string line)\n{\n if (string.IsNullOrEmpty(line))\n throw new ArgumentException();\n\n List<string> result = new List<string>();\n\n bool inQuote = false;\n StringBuilder val = new StringBuilder();\n\n // parse line\n foreach (var t in line.Split(','))\n {\n int count = t.Count(c => c == '\"');\n\n if (count > 2 && !inQuote)\n {\n inQuote = true;\n val.Append(t);\n val.Append(',');\n continue;\n }\n\n if (count > 2 && inQuote)\n {\n inQuote = false;\n val.Append(t);\n result.Add(val.ToString());\n continue;\n }\n\n if (count == 2 && !inQuote)\n {\n result.Add(t);\n continue;\n }\n\n if (count == 2 && inQuote)\n {\n val.Append(t);\n val.Append(',');\n continue;\n }\n }\n\n // remove quotation\n for (int i = 0; i < result.Count; i++)\n {\n string t = result[i];\n result[i] = t.Substring(1, t.Length - 2);\n }\n\n return result;\n}\n" }, { "answer_id": 3567944, "author": "NahuelGQ", "author_id": 356604, "author_profile": "https://Stackoverflow.com/users/356604", "pm_score": 1, "selected": false, "text": "a,\"line 1\nline 2\nline 3\"\nb,\"line 1\nline 2\nline 3\"\n [DelimitedRecord(\",\")]\npublic class MyRecord\n{ \n public string field1;\n [FieldQuoted('\"', QuoteMode.OptionalForRead, MultilineMode.AllowForRead)]\n public string field2;\n}\n static void Main()\n{\n FileHelperEngine engine = new FileHelperEngine(typeof(MyRecord));\n MyRecord[] res = engine.ReadFile(\"file.csv\"); \n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
316,673
<p>I have an app that is written in Swing, awt. I want to prevent users from pasting values into the textfields. is there any way to do this without using action listeners?</p>
[ { "answer_id": 316703, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "paste() JTextComponent" }, { "answer_id": 2343559, "author": "Rob", "author_id": 282240, "author_profile": "https://Stackoverflow.com/users/282240", "pm_score": 2, "selected": false, "text": "textComponent.setEditable(false);" }, { "answer_id": 7491183, "author": "Christian", "author_id": 955589, "author_profile": "https://Stackoverflow.com/users/955589", "pm_score": 5, "selected": false, "text": "textComponent.setTransferHandler(null);\n" }, { "answer_id": 44419569, "author": "jprism", "author_id": 1196170, "author_profile": "https://Stackoverflow.com/users/1196170", "pm_score": 1, "selected": false, "text": "public class PastlessJTextField extends JTextField {\n\n public PastlessJTextField() {\n super();\n }\n public PastlessJTextField( int columns ){\n super( columns );\n }\n\n @Override\n public void paste() {\n // do nothing\n }\n\n\n }\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
316,674
<p>How would I accomplish displaying a line as the one below in a console window by writing it into a variable during design time then just calling Console.WriteLine(sDescription) to display it?</p> <pre><code> Options: -t Description of -t argument. -b Description of -b argument. </code></pre>
[ { "answer_id": 316680, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 2, "selected": false, "text": "Console.Write(\"Options:\\n\\tSomething\\t\\tElse\");\n Options:\n Something Else\n" }, { "answer_id": 316688, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "/? string.Format" }, { "answer_id": 316695, "author": "Boris Callens", "author_id": 11333, "author_profile": "https://Stackoverflow.com/users/11333", "pm_score": 3, "selected": true, "text": "String sDescription =\n@\"Options:\n -t Description of -t argument.\";\n string formatString = \"{0:10} {1}\";\nConsole.WriteLine(\"Options:\");\nConsole.WriteLine(formatString, \"-t\", \"Description of -t argument.\");\nConsole.WriteLine(formatString, \"-b\", \"Description of -b argument.\");\n" }, { "answer_id": 318794, "author": "Logicalmind", "author_id": 26977, "author_profile": "https://Stackoverflow.com/users/26977", "pm_score": 1, "selected": false, "text": "System.Environment.NewLine\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
316,682
<p>I have a byte stream I need parsed into a struct, and I also need to be able to parse the struct back to a byte stream.</p> <p>Below is an example of what I want where I've used BitConverter to parse the values. I hope there is a more efficient way of doing this, because my structs are HUGE!</p> <pre><code>ref struct TestStruct { int TestInt; float TestFloat; }; int main(array&lt;System::String ^&gt; ^args) { // populating array - just for demo, it's really coming from a file array&lt;unsigned char&gt;^ arrBytes = gcnew array&lt;unsigned char&gt;(8); Array::Copy(BitConverter::GetBytes((int)1234), arrBytes, 4); Array::Copy(BitConverter::GetBytes((float)12.34), 0, arrBytes, 4, 4); // parsing to struct - I want help TestStruct^ myStruct = gcnew TestStruct(); myStruct-&gt;TestInt = BitConverter::ToInt32(arrBytes, 0); myStruct-&gt;TestFloat = BitConverter::ToSingle(arrBytes, 4); String^ str = Console::ReadLine(); return 0; } </code></pre>
[ { "answer_id": 316705, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": -1, "selected": false, "text": "char buffer[sizeof(MYSTRUCT)];\nmemcopy((char*) &mystruct, buffer, sizeof(MYSTRUCT));\n" }, { "answer_id": 316718, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 2, "selected": true, "text": "struct a {\n int i;\n}\n\nstruct b {\n string name;\n struct a a;\n}\n cout << \"struct \" << name << \" * read_struct_\" << name << \" (stream in) {\" << NL\n << \" struct \" << name << \" * result = malloc (sizeof(struct \" << name << \"));\" NL\nparseFields (headerStream);\ncout << \" return result;\" << NL << \"}\" << NL ; } \n cout << \"read_\" << fieldType << \"(in, &result->\" << fieldName << \");\" << NL;\n struct a * read_struct_a (stream in) {\n struct a * result = malloc(sizeof(struct a));\n read_int(in, &result->i);\n return result;\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37583/" ]
316,727
<p>I always tell in c# a variable of type double is not suitable for money. All weird things could happen. But I can't seem to create an example to demonstrate some of these issues. Can anyone provide such an example?</p> <p>(edit; this post was originally tagged C#; some replies refer to specific details of <code>decimal</code>, which therefore means <a href="http://msdn.microsoft.com/en-us/library/system.decimal.aspx" rel="noreferrer"><code>System.Decimal</code></a>).</p> <p>(edit 2: I was specific asking for some c# code, so I don't think this is language agnostic only)</p>
[ { "answer_id": 316731, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 8, "selected": true, "text": "double x = 3.65, y = 0.05, z = 3.7;\nConsole.WriteLine((x + y) == z); // false\n" }, { "answer_id": 316737, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "using System;\n\nclass Test\n{\n static void Main()\n {\n double x = 0.1;\n double y = x + x + x;\n Console.WriteLine(y == 0.3); // Prints False\n }\n}\n" }, { "answer_id": 316788, "author": "Richard Poole", "author_id": 26003, "author_profile": "https://Stackoverflow.com/users/26003", "pm_score": 3, "selected": false, "text": "decimal double decimal double" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316727", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56/" ]
316,747
<p>I had this question earlier and it was concluded it was a bug in 5.2.5. Well, it's still broken in 5.2.6, at least for me:</p> <p>Please let me know if it is broken or works for you:</p> <pre><code>$obj = new stdClass(); $obj-&gt;{"foo"} = "bar"; $obj-&gt;{"0"} = "zero"; $arr = (array)$obj; //foo -- bar //0 -- {error: undefined index} foreach ($arr as $key=&gt;$value){ echo "$key -- " . $arr[$key] . "\n"; } </code></pre> <p>Any ways to "fix" the array after it has been cast from a stdClass?</p>
[ { "answer_id": 316772, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 3, "selected": true, "text": "$arr = array_combine(array_keys($arr), array_values($arr));\n" }, { "answer_id": 316776, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "unserialize(serialize($arr));\n" }, { "answer_id": 316789, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 1, "selected": false, "text": "function noopa( $a ){ return $a; }\n$arr = array_map('noopa', $arr ); \n$arr[0]; # no error! \n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
316,757
<p>The UK VAT system is changing from 17.5% to 15%. What strategies have you used in your code to store the VAT, and how will the change affect your applications. Do you store a history of vats so you can calculate old prices, or are old invoices stored in a separate table? Is it a simple config setting, or did you bodge it? What's the ideal way to store VAT?</p>
[ { "answer_id": 316768, "author": "digiguru", "author_id": 5055, "author_profile": "https://Stackoverflow.com/users/5055", "pm_score": -1, "selected": false, "text": "Table tbl_config\n config_id int\n config_name varchar(255)\n config_value varchar(255)\n" }, { "answer_id": 1927870, "author": "Stephen", "author_id": 179110, "author_profile": "https://Stackoverflow.com/users/179110", "pm_score": 0, "selected": false, "text": "SELECT * FROM vat WHERE NOW() > vat_date ORDER BY vat_date DESC LIMIT 1\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5055/" ]
316,761
<p>I'm working with a Java program that has multiple components (with Eclipse &amp; Ant at the moment). </p> <p>Is there some way to start multiple programs with one launch configuration? I have an Ant target that does the job (launches multiple programs) but there are things I would like to do:</p> <ul> <li>I would like to debug the programs with Eclipse, hence the need for Eclipse launch.</li> <li>I would like to see the outputs for the programs at separate consoles.</li> </ul> <p>Also other ways to launch multiple Java programs "with one click" with separate consoles and/or debugging would be ok.</p>
[ { "answer_id": 316783, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": true, "text": "Main Class: org.apache.tools.ant.Main\n\n-Dant.home=${resource_loc:/myPath/apache_ant} \n-f ${resource_loc:/myProject/config/myFile-ant.xml}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28482/" ]
316,773
<p>Ok I am a total beginner with the Solaris Operating system and I need to install and configure samba on 3 boxes each has a different version of Solaris (8,9,10).</p> <p>What I want to know location of samba configuration file i.e., <code>smb.conf</code> files in each version? So far all I have found is </p> <ol> <li><p>Solaris 8 </p> <blockquote> <p>/usr/local/samba/lib/smb.conf</p> </blockquote></li> <li><p>Solaris 9 and Solaris 10</p> <blockquote> <p>/etc/sfw/samba/smb.conf</p> </blockquote></li> </ol> <p>Is this right? I need to know where these files go by default when samba is installed.</p>
[ { "answer_id": 316816, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 3, "selected": true, "text": "/usr/local/samba/ smbd -D -s /myPath/smb.conf\n -D -s <configuration file>" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316773", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38210/" ]
316,780
<p>I'm developing a multilanguage software. As far as the application code goes, localizability is not an issue. We can use language specific resources and have all kinds of tools that work well with them.</p> <p>But what is the best approach in defining a multilanguage database schema? Let's say we have a lot of tables (100 or more), and each table can have multiple columns that can be localized (most of nvarchar columns should be localizable). For instance one of the tables might hold product information:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE T_PRODUCT ( NAME NVARCHAR(50), DESCRIPTION NTEXT, PRICE NUMBER(18, 2) ) </code></pre> <p>I can think of three approaches to support multilingual text in NAME and DESCRIPTION columns:</p> <ol> <li><p>Separate column for each language</p> <p>When we add a new language to the system, we must create additional columns to store the translated text, like this:</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE T_PRODUCT ( NAME_EN NVARCHAR(50), NAME_DE NVARCHAR(50), NAME_SP NVARCHAR(50), DESCRIPTION_EN NTEXT, DESCRIPTION_DE NTEXT, DESCRIPTION_SP NTEXT, PRICE NUMBER(18,2) ) </code></pre></li> <li><p>Translation table with columns for each language</p> <p>Instead of storing translated text, only a foreign key to the translations table is stored. The translations table contains a column for each language.</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE T_PRODUCT ( NAME_FK int, DESCRIPTION_FK int, PRICE NUMBER(18, 2) ) CREATE TABLE T_TRANSLATION ( TRANSLATION_ID, TEXT_EN NTEXT, TEXT_DE NTEXT, TEXT_SP NTEXT ) </code></pre></li> <li><p>Translation tables with rows for each language</p> <p>Instead of storing translated text, only a foreign key to the translations table is stored. The translations table contains only a key, and a separate table contains a row for each translation to a language.</p> <pre class="lang-sql prettyprint-override"><code>CREATE TABLE T_PRODUCT ( NAME_FK int, DESCRIPTION_FK int, PRICE NUMBER(18, 2) ) CREATE TABLE T_TRANSLATION ( TRANSLATION_ID ) CREATE TABLE T_TRANSLATION_ENTRY ( TRANSLATION_FK, LANGUAGE_FK, TRANSLATED_TEXT NTEXT ) CREATE TABLE T_TRANSLATION_LANGUAGE ( LANGUAGE_ID, LANGUAGE_CODE CHAR(2) ) </code></pre></li> </ol> <p>There are pros and cons to each solution, and I would like to know what are your experiences with these approaches, what do you recommend and how would you go about designing a multilanguage database schema.</p>
[ { "answer_id": 316829, "author": "user39603", "author_id": 39603, "author_profile": "https://Stackoverflow.com/users/39603", "pm_score": 3, "selected": false, "text": "table Product\nproductid INT PK, price DECIMAL, translationid INT FK\n\ntable Translation\ntranslationid INT PK\n\ntable TranslationItem\ntranslationitemid INT PK, translationid INT FK, text VARCHAR, languagecode CHAR(2)\n\nview ProductView\nselect * from Product\ninner join Translation\ninner join TranslationItem\nwhere languagecode='en'\n" }, { "answer_id": 11833464, "author": "randomizer", "author_id": 1057564, "author_profile": "https://Stackoverflow.com/users/1057564", "pm_score": 2, "selected": false, "text": "CREATE TABLE T_TRANSLATION (\n TRANSLATION_ID\n)\n table Product\nproductid INT PK, price DECIMAL, translationid INT FK\n\ntable Translation\ntranslationid INT PK\n\ntable TranslationItem\ntranslationitemid INT PK, translationid INT FK, text VARCHAR, languagecode CHAR(2)\n\nview ProductView\nselect * from Product\ninner join Translation\ninner join TranslationItem\nwhere languagecode='en'\n table Product\n productid INT PK, price DECIMAL\n\n table ProductItem\n productitemid INT PK, productid INT FK, text VARCHAR, languagecode CHAR(2)\n\n view ProductView\n select * from Product\n inner join ProductItem\n where languagecode='en'\n" }, { "answer_id": 12062632, "author": "Bart VW", "author_id": 1615274, "author_profile": "https://Stackoverflow.com/users/1615274", "pm_score": 1, "selected": false, "text": "TA_product: ProductID, ProductPrice\nTA_Language: LanguageID, Language\nTA_Productname: ProductnameID, ProductID, LanguageID, ProductName\n" }, { "answer_id": 13863718, "author": "davey", "author_id": 692151, "author_profile": "https://Stackoverflow.com/users/692151", "pm_score": 1, "selected": false, "text": "CREATE TABLE translation_entry (\n translation_id int,\n language_id int,\n table_name nvarchar(200),\n table_column_name nvarchar(200),\n table_row_id bigint,\n translated_text ntext\n )\n\n CREATE TABLE translation_language (\n id int,\n language_code CHAR(2)\n ) \n" }, { "answer_id": 18181495, "author": "bamburik", "author_id": 1939631, "author_profile": "https://Stackoverflow.com/users/1939631", "pm_score": 4, "selected": false, "text": "PRODUCTS (\n id \n price\n created_at\n)\n\nLANGUAGES (\n id \n title\n)\n\nTRANSLATIONS (\n id (// id of translation, UNIQUE)\n language_id (// id of desired language)\n table_name (// any table, in this case PRODUCTS)\n item_id (// id of item in PRODUCTS)\n field_name (// fields to be translated)\n translation (// translation text goes here)\n)\n" }, { "answer_id": 26056292, "author": "Stefan Steiger", "author_id": 155077, "author_profile": "https://Stackoverflow.com/users/155077", "pm_score": 6, "selected": false, "text": "SELECT ['DESCRIPTION_' + @in_language] FROM T_Products\n SELECT \n Product_UID \n ,\n CASE @in_language \n WHEN 'DE' THEN DESCRIPTION_DE \n WHEN 'SP' THEN DESCRIPTION_SP \n ELSE DESCRIPTION_EN \n END AS Text \nFROM T_Products \n CREATE PROCEDURE [dbo].[sp_RPT_DATA_BadExample]\n @in_mandant varchar(3) \n ,@in_language varchar(2) \n ,@in_building varchar(36) \n ,@in_wing varchar(36) \n ,@in_reportingdate varchar(50) \nAS\nBEGIN\n DECLARE @sql varchar(MAX), @reportingdate datetime\n \n -- Abrunden des Eingabedatums auf 00:00:00 Uhr\n SET @reportingdate = CONVERT( datetime, @in_reportingdate) \n SET @reportingdate = CAST(FLOOR(CAST(@reportingdate AS float)) AS datetime)\n SET @in_reportingdate = CONVERT(varchar(50), @reportingdate) \n \n SET NOCOUNT ON;\n\n\n SET @sql='SELECT \n Building_Nr AS RPT_Building_Number \n ,Building_Name AS RPT_Building_Name \n ,FloorType_Lang_' + @in_language + ' AS RPT_FloorType \n ,Wing_No AS RPT_Wing_Number \n ,Wing_Name AS RPT_Wing_Name \n ,Room_No AS RPT_Room_Number \n ,Room_Name AS RPT_Room_Name \n FROM V_Whatever \n WHERE SO_MDT_ID = ''' + @in_mandant + ''' \n \n AND \n ( \n ''' + @in_reportingdate + ''' BETWEEN CAST(FLOOR(CAST(Room_DateFrom AS float)) AS datetime) AND Room_DateTo \n OR Room_DateFrom IS NULL \n OR Room_DateTo IS NULL \n ) \n '\n \n IF @in_building <> '00000000-0000-0000-0000-000000000000' SET @sql=@sql + 'AND (Building_UID = ''' + @in_building + ''') '\n IF @in_wing <> '00000000-0000-0000-0000-000000000000' SET @sql=@sql + 'AND (Wing_UID = ''' + @in_wing + ''') '\n \n EXECUTE (@sql) \n \nEND\n\n\nGO\n <insert name of your \"favourite\" person here> <insert name of your \"favourite\" person here> -- CREATE TABLE MyTable(myfilename nvarchar(100) NULL, filemeta xml NULL )\n\n\n;WITH CTE AS \n(\n -- INSERT INTO MyTable(myfilename, filemeta) \n SELECT \n 'test.mp3' AS myfilename \n --,CONVERT(XML, N'<?xml version=\"1.0\" encoding=\"utf-16\" standalone=\"yes\"?><body>Hello</body>', 2) \n --,CONVERT(XML, N'<?xml version=\"1.0\" encoding=\"utf-16\" standalone=\"yes\"?><body><de>Hello</de></body>', 2) \n ,CONVERT(XML\n , N'<?xml version=\"1.0\" encoding=\"utf-16\" standalone=\"yes\"?>\n<lang>\n <de>Deutsch</de>\n <fr>Français</fr>\n <it>Ital&amp;iano</it>\n <en>English</en>\n</lang>\n ' \n , 2 \n ) AS filemeta \n) \n\nSELECT \n myfilename\n ,filemeta\n --,filemeta.value('body', 'nvarchar') \n --, filemeta.value('.', 'nvarchar(MAX)') \n\n ,filemeta.value('(/lang//de/node())[1]', 'nvarchar(MAX)') AS DE\n ,filemeta.value('(/lang//fr/node())[1]', 'nvarchar(MAX)') AS FR\n ,filemeta.value('(/lang//it/node())[1]', 'nvarchar(MAX)') AS IT\n ,filemeta.value('(/lang//en/node())[1]', 'nvarchar(MAX)') AS EN\nFROM CTE \n filemeta.value('(/lang//' + @in_language + '/node())[1]', 'nvarchar(MAX)') AS bla\n UPDATE YOUR_TABLE\nSET YOUR_XML_FIELD_NAME.modify('replace value of (/lang/de/text())[1] with \"&quot;I am a ''value &quot;\"')\nWHERE id = 1 \n /lang/de/... '.../' + @in_language + '/...' CREATE TABLE dbo.T_Languages\n(\n Lang_ID int NOT NULL\n ,Lang_NativeName national character varying(200) NULL\n ,Lang_EnglishName national character varying(200) NULL\n ,Lang_ISO_TwoLetterName character varying(10) NULL\n ,CONSTRAINT PK_T_Languages PRIMARY KEY ( Lang_ID )\n);\n\nGO\n\n\n\n\nCREATE TABLE dbo.T_Products\n(\n PROD_Id int NOT NULL\n ,PROD_InternalName national character varying(255) NULL\n ,CONSTRAINT PK_T_Products PRIMARY KEY ( PROD_Id )\n); \n\nGO\n\n\n\nCREATE TABLE dbo.T_Products_i18n\n(\n PROD_i18n_PROD_Id int NOT NULL\n ,PROD_i18n_Lang_Id int NOT NULL\n ,PROD_i18n_Text national character varying(200) NULL\n ,CONSTRAINT PK_T_Products_i18n PRIMARY KEY (PROD_i18n_PROD_Id, PROD_i18n_Lang_Id)\n);\n\nGO\n\n-- ALTER TABLE dbo.T_Products_i18n WITH NOCHECK ADD CONSTRAINT FK_T_Products_i18n_T_Products FOREIGN KEY(PROD_i18n_PROD_Id)\nALTER TABLE dbo.T_Products_i18n \n ADD CONSTRAINT FK_T_Products_i18n_T_Products \n FOREIGN KEY(PROD_i18n_PROD_Id)\n REFERENCES dbo.T_Products (PROD_Id)\nON DELETE CASCADE \nGO\n\nALTER TABLE dbo.T_Products_i18n CHECK CONSTRAINT FK_T_Products_i18n_T_Products\nGO\n\nALTER TABLE dbo.T_Products_i18n \n ADD CONSTRAINT FK_T_Products_i18n_T_Languages \n FOREIGN KEY( PROD_i18n_Lang_Id )\n REFERENCES dbo.T_Languages( Lang_ID )\nON DELETE CASCADE \nGO\n\nALTER TABLE dbo.T_Products_i18n CHECK CONSTRAINT FK_T_Products_i18n_T_Products\nGO\n\n\n \nCREATE TABLE dbo.T_Products_i18n_Cust\n(\n PROD_i18n_Cust_PROD_Id int NOT NULL\n ,PROD_i18n_Cust_Lang_Id int NOT NULL\n ,PROD_i18n_Cust_Text national character varying(200) NULL\n ,CONSTRAINT PK_T_Products_i18n_Cust PRIMARY KEY ( PROD_i18n_Cust_PROD_Id, PROD_i18n_Cust_Lang_Id )\n);\n\nGO\n\nALTER TABLE dbo.T_Products_i18n_Cust \n ADD CONSTRAINT FK_T_Products_i18n_Cust_T_Languages \n FOREIGN KEY(PROD_i18n_Cust_Lang_Id)\n REFERENCES dbo.T_Languages (Lang_ID)\n\nALTER TABLE dbo.T_Products_i18n_Cust CHECK CONSTRAINT FK_T_Products_i18n_Cust_T_Languages\n\nGO\n\n\n\nALTER TABLE dbo.T_Products_i18n_Cust \n ADD CONSTRAINT FK_T_Products_i18n_Cust_T_Products \n FOREIGN KEY(PROD_i18n_Cust_PROD_Id)\nREFERENCES dbo.T_Products (PROD_Id)\nGO\n\nALTER TABLE dbo.T_Products_i18n_Cust CHECK CONSTRAINT FK_T_Products_i18n_Cust_T_Products\nGO\n DELETE FROM T_Languages;\nINSERT INTO T_Languages (Lang_ID, Lang_NativeName, Lang_EnglishName, Lang_ISO_TwoLetterName) VALUES (1, N'English', N'English', N'EN');\nINSERT INTO T_Languages (Lang_ID, Lang_NativeName, Lang_EnglishName, Lang_ISO_TwoLetterName) VALUES (2, N'Deutsch', N'German', N'DE');\nINSERT INTO T_Languages (Lang_ID, Lang_NativeName, Lang_EnglishName, Lang_ISO_TwoLetterName) VALUES (3, N'Français', N'French', N'FR');\nINSERT INTO T_Languages (Lang_ID, Lang_NativeName, Lang_EnglishName, Lang_ISO_TwoLetterName) VALUES (4, N'Italiano', N'Italian', N'IT');\nINSERT INTO T_Languages (Lang_ID, Lang_NativeName, Lang_EnglishName, Lang_ISO_TwoLetterName) VALUES (5, N'Russki', N'Russian', N'RU');\nINSERT INTO T_Languages (Lang_ID, Lang_NativeName, Lang_EnglishName, Lang_ISO_TwoLetterName) VALUES (6, N'Zhungwen', N'Chinese', N'ZH');\n\nDELETE FROM T_Products;\nINSERT INTO T_Products (PROD_Id, PROD_InternalName) VALUES (1, N'Orange Juice');\nINSERT INTO T_Products (PROD_Id, PROD_InternalName) VALUES (2, N'Apple Juice');\nINSERT INTO T_Products (PROD_Id, PROD_InternalName) VALUES (3, N'Banana Juice');\nINSERT INTO T_Products (PROD_Id, PROD_InternalName) VALUES (4, N'Tomato Juice');\nINSERT INTO T_Products (PROD_Id, PROD_InternalName) VALUES (5, N'Generic Fruit Juice');\n\nDELETE FROM T_Products_i18n;\nINSERT INTO T_Products_i18n (PROD_i18n_PROD_Id, PROD_i18n_Lang_Id, PROD_i18n_Text) VALUES (1, 1, N'Orange Juice');\nINSERT INTO T_Products_i18n (PROD_i18n_PROD_Id, PROD_i18n_Lang_Id, PROD_i18n_Text) VALUES (1, 2, N'Orangensaft');\nINSERT INTO T_Products_i18n (PROD_i18n_PROD_Id, PROD_i18n_Lang_Id, PROD_i18n_Text) VALUES (1, 3, N'Jus d''Orange');\nINSERT INTO T_Products_i18n (PROD_i18n_PROD_Id, PROD_i18n_Lang_Id, PROD_i18n_Text) VALUES (1, 4, N'Succo d''arancia');\nINSERT INTO T_Products_i18n (PROD_i18n_PROD_Id, PROD_i18n_Lang_Id, PROD_i18n_Text) VALUES (2, 1, N'Apple Juice');\nINSERT INTO T_Products_i18n (PROD_i18n_PROD_Id, PROD_i18n_Lang_Id, PROD_i18n_Text) VALUES (2, 2, N'Apfelsaft');\n\nDELETE FROM T_Products_i18n_Cust;\nINSERT INTO T_Products_i18n_Cust (PROD_i18n_Cust_PROD_Id, PROD_i18n_Cust_Lang_Id, PROD_i18n_Cust_Text) VALUES (1, 2, N'Orangäsaft'); -- Swiss German, if you wonder\n DECLARE @__in_lang_id int\nSET @__in_lang_id = (\n SELECT Lang_ID\n FROM T_Languages\n WHERE Lang_ISO_TwoLetterName = 'DE'\n)\n\nSELECT \n PROD_Id \n ,PROD_InternalName -- Default Fallback field (internal name/one language only setup), just in ResultSet for demo-purposes\n ,PROD_i18n_Text -- Translation text, just in ResultSet for demo-purposes\n ,PROD_i18n_Cust_Text -- Custom Translations (e.g. per customer) Just in ResultSet for demo-purposes\n ,COALESCE(PROD_i18n_Cust_Text, PROD_i18n_Text, PROD_InternalName) AS DisplayText -- What we actually want to show \nFROM T_Products \n\nLEFT JOIN T_Products_i18n \n ON PROD_i18n_PROD_Id = T_Products.PROD_Id \n AND PROD_i18n_Lang_Id = @__in_lang_id \n \nLEFT JOIN T_Products_i18n_Cust \n ON PROD_i18n_Cust_PROD_Id = T_Products.PROD_Id\n AND PROD_i18n_Cust_Lang_Id = @__in_lang_id\n \n de-DE-1901\nde-DE-1996\n de-CH-1901\nde-CH-1996\n ON DELETE CASCADE REFERENCES dbo.T_Products( PROD_Id )\n DELETE FROM T_Products SELECT * FROM sys.fn_helpcollations() \nWHERE description LIKE '%insensitive%'\nAND name LIKE '%german%' \n SELECT \n COALESCE(GRP_Name_i18n_cust, GRP_Name_i18n, GRP_Name) AS GroupName \nFROM T_Groups \n\nORDER BY GroupName COLLATE {#COLLATION}\n cmd.CommandText = cmd.CommandText.Replace(\"{#COLLATION}\", auth.user.language.collation)\n SELECT \n COALESCE(GRP_Name_i18n_cust, GRP_Name_i18n, GRP_Name) AS GroupName \nFROM T_Groups \n\nORDER BY GroupName COLLATE German_PhoneBook_CI_AI\n" }, { "answer_id": 63784569, "author": "Bartłomiej Sobieszek", "author_id": 2010246, "author_profile": "https://Stackoverflow.com/users/2010246", "pm_score": 1, "selected": false, "text": "CREATE MATERIALIZED VIEW VCategories AS (\n SELECT cat.id, lng.iso_639_1_code, ct.descriptor, ct.value\n FROM Categories cat\n JOIN CategoryTranslations ct ON ct.category_id = cat.id\n JOIN Languages lng ON lng.id = ct.language_id\n);\n SELECT * FROM VCategories WHERE id = 120 AND iso_639_1_code = 'en'\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5348/" ]
316,781
<p>Just wondering if there is anything built-in to Javascript that can take a Form and return the query parameters, eg: <code>"var1=value&amp;var2=value2&amp;arr[]=foo&amp;arr[]=bar..."</code></p> <p>I've been wondering this for years.</p>
[ { "answer_id": 316817, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": " var foo = document.createElement(\"elementnamehere\"); \n foo.attribute = allUserSpecifiedDataConsideredDangerousHere; \n somenode.appendChild(foo); \n document.write(\"<elementnamehere attribute=\\\"\" \n + ilovebrokenwebsites \n + \"\\\">\" \n + stringdata \n + \"</elementnamehere>\");\n" }, { "answer_id": 316850, "author": "Shyam Kumar Sundarakumar", "author_id": 35392, "author_profile": "https://Stackoverflow.com/users/35392", "pm_score": 2, "selected": false, "text": "$('formName').serialize()" }, { "answer_id": 317000, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 3, "selected": false, "text": "function serialize(form) {\n if (!form || !form.elements) return;\n\n var serial = [], i, j, first;\n var add = function (name, value) {\n serial.push(encodeURIComponent(name) + '=' + encodeURIComponent(value));\n }\n\n var elems = form.elements;\n for (i = 0; i < elems.length; i += 1, first = false) {\n if (elems[i].name.length > 0) { /* don't include unnamed elements */\n switch (elems[i].type) {\n case 'select-one': first = true;\n case 'select-multiple':\n for (j = 0; j < elems[i].options.length; j += 1)\n if (elems[i].options[j].selected) {\n add(elems[i].name, elems[i].options[j].value);\n if (first) break; /* stop searching for select-one */\n }\n break;\n case 'checkbox':\n case 'radio': if (!elems[i].checked) break; /* else continue */\n default: add(elems[i].name, elems[i].value); break;\n }\n }\n }\n\n return serial.join('&');\n}\n" }, { "answer_id": 413320, "author": "Thibaut Barrère", "author_id": 20302, "author_profile": "https://Stackoverflow.com/users/20302", "pm_score": 2, "selected": false, "text": "Object.toQueryString({ action: 'ship', order_id: 123, fees: ['f1', 'f2'], 'label': 'a demo' })\n\n// -> 'action=ship&order_id=123&fees=f1&fees=f2&label=a%20demo'\n" }, { "answer_id": 5340658, "author": "Michael", "author_id": 13379, "author_profile": "https://Stackoverflow.com/users/13379", "pm_score": 6, "selected": false, "text": "function buildUrl(url, parameters){\n var qs = \"\";\n for(var key in parameters) {\n var value = parameters[key];\n qs += encodeURIComponent(key) + \"=\" + encodeURIComponent(value) + \"&\";\n }\n if (qs.length > 0){\n qs = qs.substring(0, qs.length-1); //chop off last \"&\"\n url = url + \"?\" + qs;\n }\n return url;\n}\n\n// example:\nvar url = \"http://example.com/\";\n\nvar parameters = {\n name: \"George Washington\",\n dob: \"17320222\"\n};\n\nconsole.log(buildUrl(url, parameters));\n// => http://www.example.com/?name=George%20Washington&dob=17320222\n" }, { "answer_id": 12216561, "author": "Klemen Tusar", "author_id": 1040452, "author_profile": "https://Stackoverflow.com/users/1040452", "pm_score": 7, "selected": false, "text": "jQuery.param() var params = {\n parameter1: 'value1',\n parameter2: 'value2',\n parameter3: 'value3' \n};\nvar query = $.param(params);\nconsole.log(query);\n parameter1=value1&parameter2=value2&parameter3=value3\n" }, { "answer_id": 12816698, "author": "Manish Singh", "author_id": 518493, "author_profile": "https://Stackoverflow.com/users/518493", "pm_score": 5, "selected": false, "text": "$.param $.param({ action: 'ship', order_id: 123, fees: ['f1', 'f2'], 'label': 'a demo' })\n\n// -> \"action=ship&order_id=123&fees%5B%5D=f1&fees%5B%5D=f2&label=a+demo\"\n" }, { "answer_id": 31977054, "author": "SaraNa", "author_id": 2607777, "author_profile": "https://Stackoverflow.com/users/2607777", "pm_score": 1, "selected": false, "text": "var uri = new URI(\"?hello=world\");\nuri.setSearch(\"hello\", \"mars\"); // returns the URI instance for chaining\n// uri == \"?hello=mars\"\n\nuri.setSearch({ foo: \"bar\", goodbye : [\"world\", \"mars\"] });\n// uri == \"?hello=mars&foo=bar&goodbye=world&goodbye=mars\"\n\nuri.setSearch(\"goodbye\", \"sun\");\n// uri == \"?hello=mars&foo=bar&goodbye=sun\"\n\n// CAUTION: beware of arrays, the following are not quite the same\n// If you're dealing with PHP, you probably want the latter…\nuri.setSearch(\"foo\", [\"bar\", \"baz\"]);\nuri.setSearch(\"foo[]\", [\"bar\", \"baz\"]);`\n" }, { "answer_id": 34209399, "author": "Klesun", "author_id": 2750743, "author_profile": "https://Stackoverflow.com/users/2750743", "pm_score": 8, "selected": false, "text": "var params = {\n parameter1: 'value_1',\n parameter2: 'value 2',\n parameter3: 'value&3' \n};\n\nvar esc = encodeURIComponent;\nvar query = Object.keys(params)\n .map(k => esc(k) + '=' + esc(params[k]))\n .join('&');\n .map... .map(function(k) {return esc(k) + '=' + esc(params[k]);})\n" }, { "answer_id": 42567395, "author": "ImLeo", "author_id": 1141936, "author_profile": "https://Stackoverflow.com/users/1141936", "pm_score": 4, "selected": false, "text": "const querystring = require('querystring')\n\nurl += '?' + querystring.stringify(parameters)\n" }, { "answer_id": 49701878, "author": "Josh", "author_id": 3851016, "author_profile": "https://Stackoverflow.com/users/3851016", "pm_score": 8, "selected": false, "text": "const params = new URLSearchParams({\n var1: \"value\",\n var2: \"value2\",\n arr: \"foo\",\n});\nconsole.log(params.toString());\n//Prints \"var1=value&var2=value2&arr=foo\"" }, { "answer_id": 50438911, "author": "Przemek", "author_id": 959552, "author_profile": "https://Stackoverflow.com/users/959552", "pm_score": 5, "selected": false, "text": "Object.entries() [key, value] {a: 1, b: 2} [['a', 1], ['b', 2]] const buildURLQuery = obj =>\n Object.entries(obj)\n .map(pair => pair.map(encodeURIComponent).join('='))\n .join('&');\n buildURLQuery({name: 'John', gender: 'male'});\n \"name=John&gender=male\"\n" }, { "answer_id": 52722743, "author": "Björn Tantau", "author_id": 2695799, "author_profile": "https://Stackoverflow.com/users/2695799", "pm_score": 3, "selected": false, "text": "FormData URLSearchParams const formData = new FormData(form);\nconst searchParams = new URLSearchParams(formData);\nconst queryString = searchParams.toString();\n" }, { "answer_id": 55684947, "author": "Hien Nguyen", "author_id": 4964569, "author_profile": "https://Stackoverflow.com/users/4964569", "pm_score": 1, "selected": false, "text": "url path hash parameters var url = buildUrl('http://mywebsite.com', {\n path: 'about',\n hash: 'contact',\n queryParams: {\n 'var1': 'value',\n 'var2': 'value2',\n 'arr[]' : 'foo'\n }\n });\n console.log(url);\n ;(function () {\n 'use strict';\n\n var root = this;\n var previousBuildUrl = root.buildUrl;\n\n var buildUrl = function (url, options) {\n var queryString = [];\n var key;\n var builtUrl;\n var caseChange; \n \n // 'lowerCase' parameter default = false, \n if (options && options.lowerCase) {\n caseChange = !!options.lowerCase;\n } else {\n caseChange = false;\n }\n\n if (url === null) {\n builtUrl = '';\n } else if (typeof(url) === 'object') {\n builtUrl = '';\n options = url;\n } else {\n builtUrl = url;\n }\n\n if(builtUrl && builtUrl[builtUrl.length - 1] === '/') {\n builtUrl = builtUrl.slice(0, -1);\n } \n\n if (options) {\n if (options.path) {\n var localVar = String(options.path).trim(); \n if (caseChange) {\n localVar = localVar.toLowerCase();\n }\n if (localVar.indexOf('/') === 0) {\n builtUrl += localVar;\n } else {\n builtUrl += '/' + localVar;\n }\n }\n\n if (options.queryParams) {\n for (key in options.queryParams) {\n if (options.queryParams.hasOwnProperty(key) && options.queryParams[key] !== void 0) {\n var encodedParam;\n if (options.disableCSV && Array.isArray(options.queryParams[key]) && options.queryParams[key].length) {\n for(var i = 0; i < options.queryParams[key].length; i++) {\n encodedParam = encodeURIComponent(String(options.queryParams[key][i]).trim());\n queryString.push(key + '=' + encodedParam);\n }\n } else { \n if (caseChange) {\n encodedParam = encodeURIComponent(String(options.queryParams[key]).trim().toLowerCase());\n }\n else {\n encodedParam = encodeURIComponent(String(options.queryParams[key]).trim());\n }\n queryString.push(key + '=' + encodedParam);\n }\n }\n }\n builtUrl += '?' + queryString.join('&');\n }\n\n if (options.hash) {\n if(caseChange)\n builtUrl += '#' + String(options.hash).trim().toLowerCase();\n else\n builtUrl += '#' + String(options.hash).trim();\n }\n } \n return builtUrl;\n };\n\n buildUrl.noConflict = function () {\n root.buildUrl = previousBuildUrl;\n return buildUrl;\n };\n\n if (typeof(exports) !== 'undefined') {\n if (typeof(module) !== 'undefined' && module.exports) {\n exports = module.exports = buildUrl;\n }\n exports.buildUrl = buildUrl;\n } else {\n root.buildUrl = buildUrl;\n }\n}).call(this);\n\n\nvar url = buildUrl('http://mywebsite.com', {\n path: 'about',\n hash: 'contact',\n queryParams: {\n 'var1': 'value',\n 'var2': 'value2',\n 'arr[]' : 'foo'\n }\n });\n console.log(url);" }, { "answer_id": 56964456, "author": "Mahdi Bashirpour", "author_id": 6569224, "author_profile": "https://Stackoverflow.com/users/6569224", "pm_score": 0, "selected": false, "text": "var params = { width:1680, height:1050 };\nvar str = jQuery.param( params );\n\nconsole.log(str) <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>" }, { "answer_id": 60279590, "author": "ajaykumar mp", "author_id": 8557136, "author_profile": "https://Stackoverflow.com/users/8557136", "pm_score": 2, "selected": false, "text": "var obj = {\na:\"a\",\nb:\"b\"\n}\n\nObject.entries(obj).map(([key, val])=>`${key}=${val}`).join(\"&\");\n" }, { "answer_id": 60992038, "author": "David Pascoal", "author_id": 2375648, "author_profile": "https://Stackoverflow.com/users/2375648", "pm_score": 3, "selected": false, "text": "const params: {\n key1: 'value1',\n key2: 'value2',\n key3: 'value3',\n}\n\nconst esc = encodeURIComponent;\nconst query = Object.keys(params)\n .map(k => esc(k) + '=' + esc(params[k]))\n .join('&');\n\nreturn fetch('my-url', {\n method: 'POST',\n headers: {'Content-Type': 'application/x-www-form-urlencoded'},\n body: query,\n})\n" }, { "answer_id": 64190199, "author": "Tinsae", "author_id": 7455604, "author_profile": "https://Stackoverflow.com/users/7455604", "pm_score": 5, "selected": false, "text": "URL seachParameters let stringUrl = \"http://www.google.com/search\";\nlet url = new URL(stringUrl);\nlet params = url.searchParams;\nparams.append(\"q\", \"This is seach query\");\n\nconsole.log(url.toString());\n http://www.google.com/search?q=This+is+seach+query\n" }, { "answer_id": 69472057, "author": "Simone", "author_id": 801544, "author_profile": "https://Stackoverflow.com/users/801544", "pm_score": 2, "selected": false, "text": "UrlSearchParams .get .set .set let url = new URL('https://example.com?foo=1&bar=2');\nlet params = new URLSearchParams(url.search);\n\n// Add a third parameter\nparams.set('baz', 3);\n\nparams.toString(); // \"foo=1&bar=2&baz=3\"\n let url = new URL('https://example.com?foo=1&bar=2');\n\n// Add a third parameter\nurl.searchParams.set('baz', 3);\n\nurl.searchParams.toString(); // \"foo=1&bar=2&baz=3\"\n" }, { "answer_id": 73890306, "author": "Liam", "author_id": 8959570, "author_profile": "https://Stackoverflow.com/users/8959570", "pm_score": 0, "selected": false, "text": " urlParams = obj =>{\n const removeUndefined = JSON.parse(JSON.stringify(obj))\n const result = new URLSearchParams(removeUndefined).toString();\n return result ? `?${result}`: '';\n }\n console.log(urlParams({qwe: undefined, txt: 'asd'})) // '?txt=asd'\n console.log(urlParams({qwe: undefined})) // ''" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
316,790
<p>Got a little problem with a Seam application I'm working on and I was wondering if anyone knows a way round it. I've got a form in my application that uses AJAX to show certain input boxes depending on an item in a dropdown box. The code works fine except for setting the ID's in my input boxes. It looks like JSF doesn't let me set an ID via a variable. Other attributes like "for" in labels are fine. Here's some code explaining what I mean:</p> <pre><code>&lt;ui:repeat value="#{serviceHome.instance.serviceSettings}" var="currSetting" &gt; &lt;li&gt; &lt;!-- Imagine the below works out as "settingABC" --&gt; &lt;c:set var="labelKey" value="setting#{jsfUtils.removeWhitespace(currSetting.key.name)}" /&gt; &lt;!-- Labelkey is correctly added into this input so for = "settingABC" --&gt; &lt;h:outputLabel for="#{labelKey}" styleClass="required generated" value="#{currSetting.key.name}:"/&gt; &lt;s:decorate styleClass="errorwrapper"&gt; &lt;!-- Labelkey ISN'T correctly added into this input. Instead we just get "setting" --&gt; &lt;h:inputText id="#{labelKey}" value="#{currSetting.value}"/&gt; &lt;a4j:outputPanel ajaxRendered="true"&gt; &lt;h:message for="#{labelKey}" styleClass="errormessage" /&gt; &lt;/a4j:outputPanel&gt; &lt;/s:decorate&gt; &lt;/li&gt; &lt;/ui:repeat&gt; </code></pre> <p>Does anyone have any idea how I can get past this?</p>
[ { "answer_id": 318513, "author": "Grant Wagner", "author_id": 9254, "author_profile": "https://Stackoverflow.com/users/9254", "pm_score": 2, "selected": false, "text": "<h:inputText id=\"whatever\" value=\"...\" />\n <script type=\"text/javascript\">\nvar theElement = document.getElementById('<h:outputText value=\"#{pagecode.whateverClientId}\"/ >');\n...\n</script>\n protected HtmlInputText getWhatever() {\n if (whatever == null) {\n whatever = (HtmlInputText) findComponentInRoot(\"whatever\");\n }\n}\n\npublic String getWhateverClientId() {\n return getWhatever().getClientId(getFacesContext());\n}\n" }, { "answer_id": 326389, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 4, "selected": true, "text": "\"form_id:loop_id:loop_index:component_id\" \n <h:inputText id=\"myInput\" .... />\n<h:message for=\"myInput\" ... />\n" }, { "answer_id": 661255, "author": "Martlark", "author_id": 72668, "author_profile": "https://Stackoverflow.com/users/72668", "pm_score": 0, "selected": false, "text": " <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n <html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:ui=\"http://java.sun.com/jsf/facelets\"\n xmlns:h=\"http://java.sun.com/jsf/html\" xmlns:f=\"http://java.sun.com/jsf/core\"\n xmlns:c=\"http://java.sun.com/jstl/core\" xmlns:a4j=\"http://richfaces.org/a4j\"\n xmlns:rich=\"http://richfaces.org/rich\">\n\n <ui:composition>\n\n <c:set var=\"styleClass\" value=\"formPrompt\" />\n <c:set var=\"requiredLabel\" value=\"\" />\n <c:choose>\n <c:when test=\"${required=='true'}\">\n\n <c:set var=\"required\" value=\"true\" />\n <c:set var=\"styleClass\" value=\"formRequiredPrompt\" />\n <c:set var=\"requiredLabel\" value=\"*\" />\n </c:when>\n </c:choose>\n\n <h:panelGroup id=\"#{id}_formRowTemplateLabel_panelGroup\">\n <h:outputLabel for=\"#{id}\" styleClass=\"#{styleClass}\" id=\"#{id}_formRowTemplate_outPut\"\n value=\"#{label}\" />\n <c:if test=\"${required == 'true'}\">\n <h:outputText value=\"#{requiredLabel}\" styleClass=\"formRequiredPromptAsterix\"></h:outputText>\n </c:if>\n </h:panelGroup>\n\n <h:panelGroup id=\"#{id}_textPasswordTemplate_panelGroup\">\n <h:inputSecret required=\"${required}\" id=\"#{id}\" value=\"#{property}\"\n styleClass=\"formText\">\n\n <f:validator validatorId=\"Maserati.Password\" />\n <f:validateLength maximum=\"16\" minimum=\"8\" />\n <ui:insert name=\"additionalTags\"></ui:insert>\n </h:inputSecret>\n\n <h:message styleClass=\"formErrorMsg\" id=\"#{id}_textPasswordTemplate_msg\" for=\"#{id}\" />\n </h:panelGroup>\n\n </ui:composition>\n\n </html>\n <m:textPassword id=\"password\" label=\"#{msgs.passwordPrompt}\"\n property=\"#{individualApplicationMBean.password}\"\n required=\"true\" maxlength=\"16\" />\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1900/" ]
316,807
<p>There are too many method for embedding flash in html, which way is the best? Requirements are:</p> <ul> <li>Cross-browser support</li> <li>Support for alternative content (if flash is not supported by the browser)</li> <li>Possibility to require a specific version of the flash player</li> </ul> <p>I have been reading about <a href="http://code.google.com/p/swfobject/wiki/documentation" rel="nofollow noreferrer">SWFobject</a>, has anyone used it/tested? </p>
[ { "answer_id": 316815, "author": "martinlund", "author_id": 1808, "author_profile": "https://Stackoverflow.com/users/1808", "pm_score": 5, "selected": true, "text": "var fn = function() {\n if(swfobject.hasFlashPlayerVersion(\"9.0.115\"))\n {\n var att = { data:\"flash.swf\", width:\"y\", height:\"x\" };\n var par = { menu: \"false\", flashvars: \"\" };\n signUp = swfobject.createSWF(att, par);\n }\n}\nswfobject.addDomLoadEvent(fn);\n" }, { "answer_id": 316985, "author": "Henrik Ripa", "author_id": 12031, "author_profile": "https://Stackoverflow.com/users/12031", "pm_score": 2, "selected": false, "text": "flashembed(\"frontPageFlash\",\n {\n src: \"img/flash/FrontPage.swf\",\n width: \"480\",\n height: \"600\",\n bgcolor: \"#ebebeb\",\n version: [9,0],\n expressInstall:'scripts/expressinstall.swf'\n },{\n head1: \"<%= frontPageFlashHead1 %>\",\n head2: \"<%= frontPageFlashHead2 %>\",\n pitch1: \"<%= frontPageFlashPitch1 %>\",\n pitch2: \"<%= frontPageFlashPitch2 %>\"\n }\n);\n <div id=\"frontPageFlash\"></div>\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16265/" ]
316,808
<p>Env.: VS 2008, .NET 2.0, WinForms</p> <p>I have a listview in Tile mode. Some items have an associated image. Some don't.</p> <p>The contents (listview items) is often renewed when user clicks some controls. When this happens, it sometimes appears that none of the new items have images. In that case, I would like to get rid of the empty space on the left of items reserved for images. I tried the following pseudo-code to temporarily get rid of the image list</p> <pre><code>list.Items.Clear(); FillList(); list.LargeImageList= (none of the items has image) ? null : MyImageList; </code></pre> <p>But it doesn't work: The empty space is still there. I also try to repaint the control, to no avail.</p> <p><a href="http://apptranslator.com/_so/so_list1.jpg" rel="nofollow noreferrer">alt text http://apptranslator.com/_so/so_list1.jpg</a> <a href="http://apptranslator.com/_so/so_list2.jpg" rel="nofollow noreferrer">alt text http://apptranslator.com/_so/so_list2.jpg</a> <a href="http://apptranslator.com/_so/so_list3.jpg" rel="nofollow noreferrer">alt text http://apptranslator.com/_so/so_list3.jpg</a></p> <p>Left: list with images.</p> <p>Middle: List without images. Space for images is visible.</p> <p>Right: How I would like it to be when there's no images.</p> <p>EDIT: I also made this test: Don't assign the image list in the designer. If the first display doesn't contain any images, then I get the expected result. I then click to display images (I get them). I click again to come back to a no images selection: the image space doesn't disappear.</p> <p>Also, Hath, no I don't use small images or state images. Only large images.</p> <p>What can I do? TIA.</p>
[ { "answer_id": 317249, "author": "Hath", "author_id": 5186, "author_profile": "https://Stackoverflow.com/users/5186", "pm_score": 2, "selected": true, "text": "using System;\nusing System.Windows.Forms;\npublic class MainForm : Form\n{\n private System.ComponentModel.IContainer components = null;\n private System.Windows.Forms.ListView listView;\n private System.Windows.Forms.ImageList emptySmallImageList;\n private System.Windows.Forms.ImageList largeImageList;\n private System.Windows.Forms.Button imageListSmallButton;\n private System.Windows.Forms.Button imageListLargeButton;\n\n public MainForm()\n {\n InitializeComponent();\n }\n\n private void OnImageListSmallButtonClick(object sender, EventArgs e)\n {\n this.listView.LargeImageList = emptySmallImageList; \n }\n\n private void OnImageListLargeButtonClick(object sender, EventArgs e)\n {\n this.listView.LargeImageList = largeImageList;\n }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing && (components != null))\n {\n components.Dispose();\n }\n base.Dispose(disposing);\n }\n\n private void InitializeComponent()\n {\n this.components = new System.ComponentModel.Container();\n System.Windows.Forms.ListViewItem listViewItem5 = new System.Windows.Forms.ListViewItem(\"fgsdfg\");\n System.Windows.Forms.ListViewItem listViewItem6 = new System.Windows.Forms.ListViewItem(\"sdfgsdfg\");\n System.Windows.Forms.ListViewItem listViewItem7 = new System.Windows.Forms.ListViewItem(\"sdfgsdfgsdfg\");\n System.Windows.Forms.ListViewItem listViewItem8 = new System.Windows.Forms.ListViewItem(\"sdfgsdfg\");\n this.listView = new System.Windows.Forms.ListView();\n this.largeImageList = new System.Windows.Forms.ImageList(this.components);\n this.emptySmallImageList = new System.Windows.Forms.ImageList(this.components);\n this.imageListSmallButton = new System.Windows.Forms.Button();\n this.imageListLargeButton = new System.Windows.Forms.Button();\n this.SuspendLayout();\n // \n // listView\n // \n this.listView.Dock = System.Windows.Forms.DockStyle.Fill;\n this.listView.Items.AddRange(new System.Windows.Forms.ListViewItem[] {\n listViewItem5,\n listViewItem6,\n listViewItem7,\n listViewItem8});\n this.listView.LargeImageList = this.largeImageList;\n this.listView.Location = new System.Drawing.Point(0, 0);\n this.listView.Name = \"listView\";\n this.listView.Size = new System.Drawing.Size(292, 266);\n this.listView.TabIndex = 0;\n this.listView.UseCompatibleStateImageBehavior = false;\n this.listView.View = System.Windows.Forms.View.Tile;\n // \n // largeImageList\n // \n this.largeImageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;\n this.largeImageList.ImageSize = new System.Drawing.Size(32, 32);\n this.largeImageList.TransparentColor = System.Drawing.Color.Transparent;\n // \n // emptySmallImageList\n // \n this.emptySmallImageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;\n this.emptySmallImageList.ImageSize = new System.Drawing.Size(1, 1);\n this.emptySmallImageList.TransparentColor = System.Drawing.Color.Transparent;\n // \n // imageListSmallButton\n // \n this.imageListSmallButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));\n this.imageListSmallButton.Location = new System.Drawing.Point(175, 12);\n this.imageListSmallButton.Name = \"imageListSmallButton\";\n this.imageListSmallButton.Size = new System.Drawing.Size(95, 23);\n this.imageListSmallButton.TabIndex = 1;\n this.imageListSmallButton.Text = \"ImageList 1x1\";\n this.imageListSmallButton.UseVisualStyleBackColor = true;\n this.imageListSmallButton.Click += new System.EventHandler(this.OnImageListSmallButtonClick);\n // \n // imageListLargeButton\n // \n this.imageListLargeButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));\n this.imageListLargeButton.Location = new System.Drawing.Point(175, 53);\n this.imageListLargeButton.Name = \"imageListLargeButton\";\n this.imageListLargeButton.Size = new System.Drawing.Size(95, 23);\n this.imageListLargeButton.TabIndex = 2;\n this.imageListLargeButton.Text = \"ImageList 32x32\";\n this.imageListLargeButton.UseVisualStyleBackColor = true;\n this.imageListLargeButton.Click += new System.EventHandler(this.OnImageListLargeButtonClick);\n // \n // MainForm\n // \n this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);\n this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;\n this.ClientSize = new System.Drawing.Size(292, 266);\n this.Controls.Add(this.imageListLargeButton);\n this.Controls.Add(this.imageListSmallButton);\n this.Controls.Add(this.listView);\n this.Name = \"MainForm\";\n this.Text = \"Form1\";\n this.ResumeLayout(false);\n\n }\n\n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new MainForm());\n }\n}\n imageList1.ImageSize = new Size(1,1);\n StateImageList StateImageList" }, { "answer_id": 2003664, "author": "jocull", "author_id": 97964, "author_profile": "https://Stackoverflow.com/users/97964", "pm_score": 0, "selected": false, "text": " public frmMain()\n {\n InitializeComponent();\n this.Text = Program.AppName;\n\n lstSightings.SmallImageList = new ImageList();\n lstSightings.SmallImageList.ImageSize = new Size(1, 1);\n\n RefreshItems();\n }\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12379/" ]
316,812
<p>How can I find poor performing SQL queries in Oracle?</p> <p>Oracle maintains statistics on shared SQL area and contains one row per SQL string(v$sqlarea). But how can we identify which one of them are badly performing?</p>
[ { "answer_id": 316881, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 6, "selected": false, "text": "SELECT * FROM\n(SELECT\n sql_fulltext,\n sql_id,\n elapsed_time,\n child_number,\n disk_reads,\n executions,\n first_load_time,\n last_load_time\nFROM v$sql\nORDER BY elapsed_time DESC)\nWHERE ROWNUM < 10\n/\n sql_id child_number SELECT * FROM table(DBMS_XPLAN.DISPLAY_CURSOR('&sql_id', &child));\n" }, { "answer_id": 344627, "author": "Guille", "author_id": 43655, "author_profile": "https://Stackoverflow.com/users/43655", "pm_score": 3, "selected": false, "text": "SELECT username,\n buffer_gets,\n disk_reads,\n executions,\n buffer_get_per_exec,\n parse_calls,\n sorts,\n rows_processed,\n hit_ratio,\n module,\n sql_text\n -- elapsed_time, cpu_time, user_io_wait_time, ,\n FROM (SELECT sql_text,\n b.username,\n a.disk_reads,\n a.buffer_gets,\n trunc(a.buffer_gets / a.executions) buffer_get_per_exec,\n a.parse_calls,\n a.sorts,\n a.executions,\n a.rows_processed,\n 100 - ROUND (100 * a.disk_reads / a.buffer_gets, 2) hit_ratio,\n module\n -- cpu_time, elapsed_time, user_io_wait_time\n FROM v$sqlarea a, dba_users b\n WHERE a.parsing_user_id = b.user_id\n AND b.username NOT IN ('SYS', 'SYSTEM', 'RMAN','SYSMAN')\n AND a.buffer_gets > 10000\n ORDER BY buffer_get_per_exec DESC)\n WHERE ROWNUM <= 20\n" }, { "answer_id": 345388, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 4, "selected": false, "text": "SELECT Disk_Reads DiskReads, Executions, SQL_ID, SQL_Text SQLText, \n SQL_FullText SQLFullText \nFROM\n(\n SELECT Disk_Reads, Executions, SQL_ID, LTRIM(SQL_Text) SQL_Text, \n SQL_FullText, Operation, Options, \n Row_Number() OVER \n (Partition By sql_text ORDER BY Disk_Reads * Executions DESC) \n KeepHighSQL\n FROM\n (\n SELECT Avg(Disk_Reads) OVER (Partition By sql_text) Disk_Reads, \n Max(Executions) OVER (Partition By sql_text) Executions, \n t.SQL_ID, sql_text, sql_fulltext, p.operation,p.options\n FROM v$sql t, v$sql_plan p\n WHERE t.hash_value=p.hash_value AND p.operation='TABLE ACCESS' \n AND p.options='FULL' AND p.object_owner NOT IN ('SYS','SYSTEM')\n AND t.Executions > 1\n ) \n ORDER BY DISK_READS * EXECUTIONS DESC\n)\nWHERE KeepHighSQL = 1\nAND rownum <=5;\n" }, { "answer_id": 27974000, "author": "Steven", "author_id": 1996306, "author_profile": "https://Stackoverflow.com/users/1996306", "pm_score": 2, "selected": false, "text": "SELECT t2.username, t1.disk_reads, t1.executions,\n t1.disk_reads / DECODE(t1.executions, 0, 1, t1.executions) as exec_ratio,\n t1.command_type, t1.sql_text\n FROM v$sqlarea t1, dba_users t2\n WHERE t1.parsing_user_id = t2.user_id\n AND t1.disk_reads > 100000\n ORDER BY t1.disk_reads DESC\n Explain Plans" }, { "answer_id": 41117021, "author": "Ras Rass", "author_id": 1425503, "author_profile": "https://Stackoverflow.com/users/1425503", "pm_score": 2, "selected": false, "text": "select * \nfrom v$sql \nwhere buffer_gets > 1000000 \nor disk_reads > 100000 \nor executions > 50000 \n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34058/" ]
316,820
<p>I need to launch a media file from a URL from within my c# .NET application. Is there any way to do this natively in .NET? I don't need an embedded player, I just need the default player to launch. I have tried </p> <pre><code>System.Diagnostics.Process.Start("File URL"); </code></pre> <p>but it launches the default browser and downloads the file, instead of attempting to play it in WMP/VLC/whatever the default media player is. Any ideas?</p>
[ { "answer_id": 316915, "author": "Stefan", "author_id": 19307, "author_profile": "https://Stackoverflow.com/users/19307", "pm_score": 2, "selected": false, "text": "System.Diagnostics.Process.Start(\"Local File\");\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13877/" ]
316,831
<p>Can we have a SQL query which will basically help in viewing table and index sizes in SQl Server.</p> <p>How SQL server maintains memory usage for tables/indexes?</p>
[ { "answer_id": 316893, "author": "Ben R", "author_id": 27705, "author_profile": "https://Stackoverflow.com/users/27705", "pm_score": 4, "selected": false, "text": "EXEC sp_MSforeachtable @command1=\"EXEC sp_spaceused '?'\"\n" }, { "answer_id": 316895, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 0, "selected": false, "text": "sp_spaceused" }, { "answer_id": 316957, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 7, "selected": true, "text": "exec sp_spaceused sp_spaceused create table #t\n(\n name nvarchar(128),\n rows varchar(50),\n reserved varchar(50),\n data varchar(50),\n index_size varchar(50),\n unused varchar(50)\n)\n\ndeclare @id nvarchar(128)\ndeclare c cursor for\nselect '[' + sc.name + '].[' + s.name + ']' FROM sysobjects s INNER JOIN sys.schemas sc ON s.uid = sc.schema_id where s.xtype='U'\n\nopen c\nfetch c into @id\n\nwhile @@fetch_status = 0 begin\n\n insert into #t\n exec sp_spaceused @id\n\n fetch c into @id\nend\n\nclose c\ndeallocate c\n\nselect * from #t\norder by convert(int, substring(data, 1, len(data)-3)) desc\n\ndrop table #t\n" }, { "answer_id": 635213, "author": "Rob Garrison", "author_id": 76740, "author_profile": "https://Stackoverflow.com/users/76740", "pm_score": 7, "selected": false, "text": "SELECT\n i.name AS IndexName,\n SUM(s.used_page_count) * 8 AS IndexSizeKB\nFROM sys.dm_db_partition_stats AS s \nJOIN sys.indexes AS i\nON s.[object_id] = i.[object_id] AND s.index_id = i.index_id\nWHERE s.[object_id] = object_id('dbo.TableName')\nGROUP BY i.name\nORDER BY i.name\n\nSELECT\n i.name AS IndexName,\n SUM(page_count * 8) AS IndexSizeKB\nFROM sys.dm_db_index_physical_stats(\n db_id(), object_id('dbo.TableName'), NULL, NULL, 'DETAILED') AS s\nJOIN sys.indexes AS i\nON s.[object_id] = i.[object_id] AND s.index_id = i.index_id\nGROUP BY i.name\nORDER BY i.name\n" }, { "answer_id": 33703104, "author": "alpav", "author_id": 195446, "author_profile": "https://Stackoverflow.com/users/195446", "pm_score": 2, "selected": false, "text": "create table #tbl(\n name nvarchar(128),\n rows varchar(50),\n reserved varchar(50),\n data varchar(50),\n index_size varchar(50),\n unused varchar(50)\n)\n\nexec sp_msforeachtable 'insert into #tbl exec sp_spaceused [?]'\n\nselect * from #tbl\n order by convert(int, substring(data, 1, len(data)-3)) desc\n\ndrop table #tbl\n" }, { "answer_id": 37824697, "author": "jthalliens", "author_id": 5062821, "author_profile": "https://Stackoverflow.com/users/5062821", "pm_score": 3, "selected": false, "text": "WITH CteIndex\nAS\n(\nSELECT \n reservedpages = (reserved_page_count)\n ,usedpages = (used_page_count)\n ,pages = (\n CASE\n WHEN (s.index_id < 2) THEN (in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)\n ELSE lob_used_page_count + row_overflow_used_page_count\n END\n ) \n ,s.object_id \n ,i.index_id \n ,i.type_desc AS IndexType\n ,i.name AS indexname\n FROM sys.dm_db_partition_stats s\n INNER JOIN sys.indexes i ON s.[object_id] = i.[object_id] AND s.index_id = i.index_id \n)\nSELECT DISTINCT\nDB_NAME(DB_ID()) AS DatabaseName\n,o.name AS TableName\n,o.object_id\n,ct.indexname\n,ct.IndexType\n,ct.index_id\n, IndexSpace = LTRIM (STR ((CASE WHEN usedpages > pages THEN CASE WHEN ct.index_id < 2 THEN pages ELSE (usedpages - pages) END ELSE 0 END) * 8, 15, 0) + ' KB')\nFROM CteIndex ct\nINNER JOIN sys.objects o ON o.object_id = ct.object_id\nINNER JOIN sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL , NULL) ps ON ps.object_id = o.object_id\nAND ps.index_id = ct.index_id\nORDER BY name ASC\n" }, { "answer_id": 39244446, "author": "Alex", "author_id": 2397221, "author_profile": "https://Stackoverflow.com/users/2397221", "pm_score": 3, "selected": false, "text": "--Gets the size of each index for the specified table\nDECLARE @TableName sysname = N'SomeTable';\n\nSELECT i.name AS IndexName\n ,8 * SUM(s.used_page_count) AS IndexSizeKB\nFROM sys.indexes AS i\n INNER JOIN sys.dm_db_partition_stats AS s \n ON i.[object_id] = s.[object_id] AND i.index_id = s.index_id\nWHERE s.[object_id] = OBJECT_ID(@TableName, N'U')\nGROUP BY i.name\nORDER BY i.name;\n\nSELECT i.name AS IndexName\n ,8 * SUM(a.used_pages) AS IndexSizeKB\nFROM sys.indexes AS i\n INNER JOIN sys.partitions AS p \n ON i.[object_id] = p.[object_id] AND i.index_id = p.index_id\n INNER JOIN sys.allocation_units AS a \n ON p.partition_id = a.container_id\nWHERE i.[object_id] = OBJECT_ID(@TableName, N'U')\nGROUP BY i.name\nORDER BY i.name;\n" }, { "answer_id": 49533647, "author": "Jakub P", "author_id": 3388511, "author_profile": "https://Stackoverflow.com/users/3388511", "pm_score": 2, "selected": false, "text": "sys.objects SELECT \n s.NAME as SCHEMA_NAME,\n t.NAME AS OBJ_NAME,\n t.type_desc as OBJ_TYPE,\n i.name as indexName,\n sum(p.rows) as RowCounts,\n sum(a.total_pages) as TotalPages, \n sum(a.used_pages) as UsedPages, \n sum(a.data_pages) as DataPages,\n (sum(a.total_pages) * 8) / 1024 as TotalSpaceMB, \n (sum(a.used_pages) * 8) / 1024 as UsedSpaceMB, \n (sum(a.data_pages) * 8) / 1024 as DataSpaceMB\nFROM \n sys.objects t\nINNER JOIN\n sys.schemas s ON t.SCHEMA_ID = s.SCHEMA_ID \nINNER JOIN \n sys.indexes i ON t.OBJECT_ID = i.object_id\nINNER JOIN \n sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id\nINNER JOIN \n sys.allocation_units a ON p.partition_id = a.container_id\nWHERE \n t.NAME NOT LIKE 'dt%' AND\n i.OBJECT_ID > 255 AND \n i.index_id <= 1\nGROUP BY \n s.NAME, t.NAME, t.type_desc, i.object_id, i.index_id, i.name \nORDER BY\n sum(a.total_pages) DESC\n;\n" }, { "answer_id": 65440196, "author": "OfirD", "author_id": 3002584, "author_profile": "https://Stackoverflow.com/users/3002584", "pm_score": 0, "selected": false, "text": "exec sp_spaceused MyTable\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316831", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34058/" ]
316,835
<p>I got this page, and have some problems with ie &lt; 7 and opera 7.11</p> <p><a href="http://browsershots.org/png/original/c5/c5bac9b3838ba30cfebae2f03f896548.png" rel="nofollow noreferrer">This</a> is what i hoped to be the layout in all browsers, and these are the IE ones instead: <a href="http://browsershots.org/screenshots/97347e42778e88203c896cc3f30134bd/" rel="nofollow noreferrer">ie 5.5</a> and <a href="http://browsershots.org/screenshots/b53d6391290363ea1e7ada0e77bdca20/" rel="nofollow noreferrer">ie 6.0</a>.</p> <p>the xhtml is quite simple:</p> <pre><code>print "&lt;div id=\"page\"&gt; &lt;div id=\"header\"&gt; &lt;ul id=\"nav\"&gt; &lt;li&gt;&lt;a href=\"/\" class=\"first\"&gt;Címlap&lt;div&gt;Az oldal címlapja&lt;/div&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=\"/blog\"&gt;Blogok&lt;div&gt;Minden bejegyzés&lt;/div&gt;&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=\"/friss\"&gt;Friss tartalom&lt;div&gt;Aktuális témák&lt;/div&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;!-- header --&gt; &lt;div id=\"main\"&gt;&lt;div id=\"main-in\"&gt; &lt;div id=\"right\"&gt;"; do_boxes(); print " &lt;/div&gt; &lt;!-- right --&gt; &lt;div id=\"left\"&gt;"; do_content(); print"&lt;/div&gt; &lt;!-- left --&gt; &lt;/div&gt;&lt;/div&gt;&lt;!-- main --&gt; &lt;/div&gt;"; </code></pre> <p>Where a the content made from posts and a post looks like: </p> <pre><code> &lt;div class="post"&gt; &lt;h2&gt;&lt;a href="/blog/2/252/newcastleben-betiltottak-a-ketreces-tojast"&gt;Newcastleben betiltották a ketreces tojást&lt;/a&gt;&lt;/h2&gt; &lt;div class="author"&gt;warnew | 2008. october 16. 20:26 &lt;/div&gt; &lt;p&gt;Az angliai Newcastle Városi Tanácsa kitiltotta a ketreces baromfitartásból származó tojásokat az iskolai étkeztetésből, személyzeti éttermekből, rendezvényekről es a "hospitality outletekből".&lt;/p&gt; &lt;p&gt;A ketreces csirke- és pulykahúst még nem tiltották be, de vizsgálják a kérdést, ahogy a &lt;a href="http://en.wikipedia.org/wiki/Halal"&gt;Halal&lt;/a&gt; hús és a ketreces tojásból készült sütemények és tésztafélék tiltását is.&lt;/p&gt; &lt;ul class="postnav"&gt; &lt;li&gt;&lt;a href="/blog/2/252/newcastleben-betiltottak-a-ketreces-tojast%7D"&gt;Tovább&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="/blog/2/252/newcastleben-betiltottak-a-ketreces-tojast#comments"&gt;Hozzászólások (0)&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;!-- post --&gt; </code></pre> <p>and a box is like this: </p> <pre><code>&lt;div id="ownadbox" class="box"&gt; &lt;h5&gt;Viridis matrica&lt;/h5&gt; &lt;a href="http://viridis.hu/blog/2/172/nepszerusits-minket" title="Népszerűsíts minket"&gt;&lt;img src="http://viridis.hu/files/viridis_matrica_jobb.png" alt="viridis matrica"/&gt;&lt;/a&gt; &lt;/div&gt; </code></pre> <p>The -what i think is - relevan css:</p> <pre><code>body { background : transparent url(/images/design/background.png) repeat; } #page { margin : 0px auto; width : 994px; background : transparent url(/images/design/header.jpg) no-repeat top left; } div#header { width : 746px; margin : 0px auto; } div#header ul#nav { padding-top : 170px; margin-left : 3px; margin-right : 3px; border-bottom : #896e51 solid 7px; overflow : hidden; } div#header ul#nav li { display : block; float : left; width : 120px; margin-bottom : 7px; } div#main { width : 746px; margin : 0px auto; } div#main div#main-in { padding : 30px 20px; background : transparent url(/images/design/content-background.png) repeat-y top left; overflow : hidden; } div#main div#main-in div#left { width : 460px; overflow : hidden; float : left; } div#main div#main-in div#left div.post { clear : left; margin-bottom : 35px; } div#main div#main-in div#right { width : 215px; float : right; } div#main div#main-in div#right div.box { margin-bottom : 30px; clear : both; } </code></pre> <p>The live version is <a href="http://viridis.hu/index3.php" rel="nofollow noreferrer">here</a>, but after I got it fixed it's gona move - thats the reason behind the long codes in the post.</p>
[ { "answer_id": 316901, "author": "jalf", "author_id": 33213, "author_profile": "https://Stackoverflow.com/users/33213", "pm_score": 3, "selected": false, "text": "<!--[if lt IE 7]><script src=\"http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE7.js\" type=\"text/javascript\"></script><![endif]-->\n<!--[if lt IE 8]><script src=\"http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js\" type=\"text/javascript\"></script><![endif]-->\n <?xml" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/553923/" ]
316,837
<p>I'm recoding an old site that contains a chart similar to this:</p> <p><a href="http://dl.getdropbox.com/u/240752/rental-chart.gif" rel="nofollow noreferrer">alt text http://dl.getdropbox.com/u/240752/rental-chart.gif</a></p> <p>How would this chart be represented with pure HTML? I'm loathed to just include it as an image.</p> <p>I'm thinking a table, just replaced with an image, or perhaps overlaid with absolutely positioned table rows, but I think that may be a bit fragile.</p> <p>Any suggestions welcomed.</p>
[ { "answer_id": 316877, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "<div class=\"chart\">\n <h3>Price for two weeks</h3>\n <div class=\"companies\">\n <div class=\"company_scale\"></div>\n <div class=\"company1\">\n <span class=\"name\">Company 1</span><span class=\"cost\"> $78</span>\n </div>\n <div class=\"company2\">\n <span class=\"name\">Company 2</span><span class=\"cost\"> $74</span>\n </div>\n <div class=\"company3\">\n <span class=\"name\">Company 3</span><span class=\"cost\"> $60</span>\n </div>\n <div class=\"company4\">\n <span class=\"name\">Company 4</span><span class=\"cost\"> $55</span>\n </div>\n <div class=\"acme\">\n <span class=\"name\">Acme Product</span><span class=\"cost\"> $49.95</span>\n </div>\n </div>\n</div>\n <div class=\"chart\">\n <h3>Price for two weeks</h3>\n <table class=\"companies\">\n <thead>\n <tr class=\"titles\">\n <td>Company</td><td>Price</td>\n </tr>\n </thead>\n <tbody>\n <tr class=\"company1\">\n <td class=\"name\">Company 1</td>\n <td class=\"cost\">$78</td>\n </tr>\n <tr class=\"company2\">\n <td class=\"name\">Company 2</td>\n <td class=\"cost\">$74</td>\n </tr>\n <tr class=\"company3\">\n <td class=\"name\">Company 3</td>\n <td class=\"cost\">$60</td>\n </tr>\n <tr class=\"company4\">\n <td class=\"name\">Company 4</td>\n <td class=\"cost\">$55</td>\n </tr>\n <tr class=\"acme\">\n <td class=\"name\">Acme Product</td>\n <td class=\"cost\">$49.95</td>\n </tr>\n </tbody>\n </table>\n</div>\n div.chart \n{ \n border: 1px solid #DDD;\n}\ndiv.chart table, \ndiv.chart tbody, \ndiv.chart thead,\ndiv.chart tr \n{ \n display: block; \n}\ndiv.chart td \n{ \n display: inline-block;\n overflow-x: hidden;\n}\ndiv.chart {\n padding: 10px;\n}\ndiv.chart td.cost, div.chart thead td { \n display: none;\n}\n\ndiv.chart tbody tr td { \n background-color: #999;\n padding: 4px;\n margin-top: 16px;\n text-align: right;\n}\n\ndiv.chart tr.company1 td { \n width:260px;\n}\ndiv.chart tr.company2 td { \n width:246px;\n}\ndiv.chart tr.company3 td { \n width:200px;\n}\ndiv.chart tr.company4 td { \n width:183px;\n}\n\ndiv.chart tbody tr td.cost { \n display: inline-block;\n background-color: inherit;\n color: #F00;\n font-size: 80%;\n width: 80px;\n}\ndiv.chart tr.acme td { \n background-color: #99F;\n width: 166px;\n}\ndiv.chart tbody tr.acme td.cost {\n color: #000;\n background-color: #FF9;\n}\n" }, { "answer_id": 316914, "author": "Stein G. Strindhaug", "author_id": 26115, "author_profile": "https://Stackoverflow.com/users/26115", "pm_score": 2, "selected": false, "text": "<table> <img alt=\"The price for two weeks is 80 dollars at rental company 1, \n73 dollars at ... The best service and price of 48 dollars \nyou get at acme product, plus you can keep it for life\" />\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26107/" ]
316,847
<p>How can I access the apache basic-auth username in a PHP script?</p>
[ { "answer_id": 39879024, "author": "William Entriken", "author_id": 300224, "author_profile": "https://Stackoverflow.com/users/300224", "pm_score": 4, "selected": false, "text": "$_SERVER['PHP_AUTH_USER']\n" }, { "answer_id": 65130656, "author": "Alexandar Penkin", "author_id": 2424141, "author_profile": "https://Stackoverflow.com/users/2424141", "pm_score": 2, "selected": false, "text": "if (isset($_SERVER[\"HTTP_AUTHORIZATION\"]) {\n $auth = $_SERVER[\"HTTP_AUTHORIZATION\"];\n $auth_array = explode(\" \", $auth);\n $un_pw = explode(\":\", base64_decode($auth_array[1]));\n $un = $un_pw[0];\n $pw = $un_pw[1];\n }\n" }, { "answer_id": 71161659, "author": "Phil", "author_id": 2010598, "author_profile": "https://Stackoverflow.com/users/2010598", "pm_score": 1, "selected": false, "text": "$_SERVER['PHP_AUTH_USER'] $_SERVER[\"HTTP_AUTHORIZATION\"] $_SERVER[\"REMOTE_USER\"] if ($_SERVER[\"REMOTE_USER\"] == \"admin\")\n echo \"Welcome, admin!\";\nelse\n echo \"Access denied\";\n" }, { "answer_id": 73728814, "author": "domsson", "author_id": 3316645, "author_profile": "https://Stackoverflow.com/users/3316645", "pm_score": 2, "selected": false, "text": "$_SERVER[\"REMOTE_USER\"] $_SERVER[\"PHP_AUTH_USER\"] $_SERVER[\"AUTH_USER\"]" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316847", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11522/" ]
316,855
<p>I have the following string:</p> <pre><code>&lt;SEM&gt;electric&lt;/SEM&gt; cu &lt;SEM&gt;hello&lt;/SEM&gt; rent &lt;SEM&gt;is&lt;I&gt;love&lt;/I&gt;, &lt;PARTITION /&gt;mind </code></pre> <p>I want to find the last "SEM" start tag before the "PARTITION" tag. not the SEM end tag but the start tag. The result should be:</p> <pre><code>&lt;SEM&gt;is &lt;Im&gt;love&lt;/Im&gt;, &lt;PARTITION /&gt; </code></pre> <p>I have tried this regular expression:</p> <pre><code>&lt;SEM&gt;[^&lt;]*&lt;PARTITION[ ]/&gt; </code></pre> <p>but it only works if the final "SEM" and "PARTITION" tags do not have any other tag between them. Any ideas?</p>
[ { "answer_id": 316869, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 0, "selected": false, "text": "<EM>.*<PARTITION\\s*/>\n" }, { "answer_id": 316872, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "int partitionIndex = text.IndexOf(\"<PARTITION\");\nint emIndex = text.LastIndexOf(\"<SEM>\", partitionIndex);\n" }, { "answer_id": 316932, "author": "Brent.Longborough", "author_id": 9634, "author_profile": "https://Stackoverflow.com/users/9634", "pm_score": 0, "selected": false, "text": "(<SEM>.*?</SEM>.*?)*(<SEM>.*?<PARTITION)\n" }, { "answer_id": 317075, "author": "Timothy Khouri", "author_id": 11917, "author_profile": "https://Stackoverflow.com/users/11917", "pm_score": 3, "selected": true, "text": "(?=[\\s\\S]*?\\<PARTITION)(?![\\s\\S]+?\\<SEM\\>)\\<SEM\\>\n (?=[\\s\\S]*?\\<PARTITION) means \"While ahead somewhere is a PARTITION tag\"\n(?![\\s\\S]+?\\<SEM\\>) means \"While ahead somewhere is not a SEM tag\"\n\\<SEM\\> means \"Match a SEM tag\"\n" }, { "answer_id": 317181, "author": "netadictos", "author_id": 31791, "author_profile": "https://Stackoverflow.com/users/31791", "pm_score": 1, "selected": false, "text": "<\\s*SEM\\s*>(?!.*</SEM>.*).*<\\s*PARTITION\\s*/> \n </SEM> <SEM> or <PARTITION/> </SEM> (?!.*</SEM>.*)\n" }, { "answer_id": 319580, "author": "Pent Ploompuu", "author_id": 17122, "author_profile": "https://Stackoverflow.com/users/17122", "pm_score": 2, "selected": false, "text": "new Regex(\"...\", RegexOptions.RightToLeft);\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40570/" ]
316,864
<p>is it possible to develop DLL for both win32 console and MFC GUI. If yes please explain.</p> <p>What i want to do is to create dll that contains certain API's for both win32 console and MFC GUI.</p>
[ { "answer_id": 316887, "author": "John Sibly", "author_id": 1078, "author_profile": "https://Stackoverflow.com/users/1078", "pm_score": 3, "selected": true, "text": "#ifdef TEST_EXPORTS\n#define TEST_API __declspec(dllexport)\n#else\n#define TEST_API __declspec(dllimport)\n#endif\n TEST_API int fnTest(void);\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38038/" ]
316,866
<p>How do I ping a website or IP address with Python?</p>
[ { "answer_id": 316974, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 6, "selected": false, "text": "import subprocess\n\nhost = \"www.google.com\"\n\nping = subprocess.Popen(\n [\"ping\", \"-c\", \"4\", host],\n stdout = subprocess.PIPE,\n stderr = subprocess.PIPE\n)\n\nout, error = ping.communicate()\nprint out\n host = \"google.com; `echo test`\n out round-trip min/avg/max/stddev = 248.139/249.474/250.530/0.896 ms\n import re\nmatcher = re.compile(\"round-trip min/avg/max/stddev = (\\d+.\\d+)/(\\d+.\\d+)/(\\d+.\\d+)/(\\d+.\\d+)\")\nprint matcher.search(out).groups()\n\n# ('248.139', '249.474', '250.530', '0.896')\n ping" }, { "answer_id": 317021, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 3, "selected": false, "text": "os.system(\"ping \" + ip ) \"\\r\\n\" /index.html" }, { "answer_id": 317172, "author": "Ryan Cox", "author_id": 620, "author_profile": "https://Stackoverflow.com/users/620", "pm_score": 5, "selected": false, "text": "#!/usr/bin/env python2.5\nfrom threading import Thread\nimport subprocess\nfrom Queue import Queue\n\nnum_threads = 4\nqueue = Queue()\nips = [\"10.0.1.1\", \"10.0.1.3\", \"10.0.1.11\", \"10.0.1.51\"]\n#wraps system ping command\ndef pinger(i, q):\n \"\"\"Pings subnet\"\"\"\n while True:\n ip = q.get()\n print \"Thread %s: Pinging %s\" % (i, ip)\n ret = subprocess.call(\"ping -c 1 %s\" % ip,\n shell=True,\n stdout=open('/dev/null', 'w'),\n stderr=subprocess.STDOUT)\n if ret == 0:\n print \"%s: is alive\" % ip\n else:\n print \"%s: did not respond\" % ip\n q.task_done()\n#Spawn thread pool\nfor i in range(num_threads):\n\n worker = Thread(target=pinger, args=(i, queue))\n worker.setDaemon(True)\n worker.start()\n#Place work in queue\nfor ip in ips:\n queue.put(ip)\n#Wait until worker threads are done to exit \nqueue.join()\n" }, { "answer_id": 317206, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 6, "selected": false, "text": "import ping, socket\ntry:\n ping.verbose_ping('www.google.com', count=3)\n delay = ping.Ping('www.wikipedia.org', timeout=2000).do()\nexcept socket.error, e:\n print \"Ping Error:\", e\n verbose_ping Ping.do" }, { "answer_id": 318142, "author": "Corey Goldberg", "author_id": 16148, "author_profile": "https://Stackoverflow.com/users/16148", "pm_score": 0, "selected": false, "text": "import re\nfrom subprocess import Popen, PIPE\nfrom threading import Thread\n\n\nclass Pinger(object):\n def __init__(self, hosts):\n for host in hosts:\n pa = PingAgent(host)\n pa.start()\n\nclass PingAgent(Thread):\n def __init__(self, host):\n Thread.__init__(self) \n self.host = host\n\n def run(self):\n p = Popen('ping -n 1 ' + self.host, stdout=PIPE)\n m = re.search('Average = (.*)ms', p.stdout.read())\n if m: print 'Round Trip Time: %s ms -' % m.group(1), self.host\n else: print 'Error: Invalid Response -', self.host\n\n\nif __name__ == '__main__':\n hosts = [\n 'www.pylot.org',\n 'www.goldb.org',\n 'www.google.com',\n 'www.yahoo.com',\n 'www.techcrunch.com',\n 'www.this_one_wont_work.com'\n ]\n Pinger(hosts)\n" }, { "answer_id": 1165094, "author": "Harald Schilly", "author_id": 54236, "author_profile": "https://Stackoverflow.com/users/54236", "pm_score": 3, "selected": false, "text": "import urllib\nimport threading\nimport time\n\ndef pinger_urllib(host):\n \"\"\"\n helper function timing the retrival of index.html \n TODO: should there be a 1MB bogus file?\n \"\"\"\n t1 = time.time()\n urllib.urlopen(host + '/index.html').read()\n return (time.time() - t1) * 1000.0\n\n\ndef task(m):\n \"\"\"\n the actual task\n \"\"\"\n delay = float(pinger_urllib(m))\n print '%-30s %5.0f [ms]' % (m, delay)\n\n# parallelization\ntasks = []\nURLs = ['google.com', 'wikipedia.org']\nfor m in URLs:\n t = threading.Thread(target=task, args=(m,))\n t.start()\n tasks.append(t)\n\n# synchronization point\nfor t in tasks:\n t.join()\n" }, { "answer_id": 12490356, "author": "Moondoggy", "author_id": 1682337, "author_profile": "https://Stackoverflow.com/users/1682337", "pm_score": 3, "selected": false, "text": "subprocess check_call shlex import subprocess\n import shlex\n\n command_line = \"ping -c 1 www.google.comsldjkflksj\"\n args = shlex.split(command_line)\n try:\n subprocess.check_call(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n print \"Website is there.\"\n except subprocess.CalledProcessError:\n print \"Couldn't get a ping.\"\n" }, { "answer_id": 13659790, "author": "hustljian", "author_id": 1048072, "author_profile": "https://Stackoverflow.com/users/1048072", "pm_score": 2, "selected": false, "text": "http://www.poolsaboveground.com/apache/hadoop/core/\nhttp://mirrors.sonic.net/apache/hadoop/core/\n python url.py urls.txt\n Round Trip Time: 253 ms - mirrors.sonic.net\nRound Trip Time: 245 ms - www.globalish.com\nRound Trip Time: 327 ms - www.poolsaboveground.com\n import re\nimport sys\nimport urlparse\nfrom subprocess import Popen, PIPE\nfrom threading import Thread\n\n\nclass Pinger(object):\n def __init__(self, hosts):\n for host in hosts:\n hostname = urlparse.urlparse(host).hostname\n if hostname:\n pa = PingAgent(hostname)\n pa.start()\n else:\n continue\n\nclass PingAgent(Thread):\n def __init__(self, host):\n Thread.__init__(self) \n self.host = host\n\n def run(self):\n p = Popen('ping -n 1 ' + self.host, stdout=PIPE)\n m = re.search('Average = (.*)ms', p.stdout.read())\n if m: print 'Round Trip Time: %s ms -' % m.group(1), self.host\n else: print 'Error: Invalid Response -', self.host\n\n\nif __name__ == '__main__':\n with open(sys.argv[1]) as f:\n content = f.readlines() \n Pinger(content)\n" }, { "answer_id": 28896872, "author": "Ibrahim Kasim", "author_id": 5010017, "author_profile": "https://Stackoverflow.com/users/5010017", "pm_score": 2, "selected": false, "text": "import subprocess as s\nip=raw_input(\"Enter the IP/Domain name:\")\nif(s.call([\"ping\",ip])==0):\n print \"your IP is alive\"\nelse:\n print \"Check ur IP\"\n" }, { "answer_id": 29580669, "author": "MSS", "author_id": 4238323, "author_profile": "https://Stackoverflow.com/users/4238323", "pm_score": -1, "selected": false, "text": "import platform,subproccess,re\ndef Ping(hostname,timeout):\n if platform.system() == \"Windows\":\n command=\"ping \"+hostname+\" -n 1 -w \"+str(timeout*1000)\n else:\n command=\"ping -i \"+str(timeout)+\" -c 1 \" + hostname\n proccess = subprocess.Popen(command, stdout=subprocess.PIPE)\n matches=re.match('.*time=([0-9]+)ms.*', proccess.stdout.read(),re.DOTALL)\n if matches:\n return matches.group(1)\n else: \n return False\n" }, { "answer_id": 56806793, "author": "Cukic0d", "author_id": 5459467, "author_profile": "https://Stackoverflow.com/users/5459467", "pm_score": 2, "selected": false, "text": "from scapy.all import *\nrequest = IP(dst=\"www.google.com\")/ICMP()\nanswer = sr1(request)\n" }, { "answer_id": 61897900, "author": "Lotus", "author_id": 12847387, "author_profile": "https://Stackoverflow.com/users/12847387", "pm_score": 3, "selected": false, "text": "import os\nos.system(\"ping google.com\") \n" }, { "answer_id": 63291064, "author": "user14062446", "author_id": 14062446, "author_profile": "https://Stackoverflow.com/users/14062446", "pm_score": 0, "selected": false, "text": "import subprocess\nping_response = subprocess.Popen([\"ping\", \"-a\", \"google.com\"], stdout=subprocess.PIPE).stdout.read()\nresult = ping_response.decode('utf-8')\nprint(result)\n" }, { "answer_id": 64947534, "author": "Valentin", "author_id": 14682996, "author_profile": "https://Stackoverflow.com/users/14682996", "pm_score": 2, "selected": false, "text": "pip3 install icmplib\n host = ping('1.1.1.1', count=4, interval=1, timeout=2, privileged=True)\n\nif host.is_alive:\n print(f'{host.address} is alive! avg_rtt={host.avg_rtt} ms')\nelse:\n print(f'{host.address} is dead')\n" }, { "answer_id": 65334325, "author": "xiaojueguan", "author_id": 7663663, "author_profile": "https://Stackoverflow.com/users/7663663", "pm_score": 0, "selected": false, "text": "import gevent\nfrom gevent import monkey\n# monkey.patch_all() should be executed before any library that will\n# standard library\nmonkey.patch_all()\n\nimport socket\nfrom scapy.all import IP, ICMP, sr1\n\n\ndef ping_site(fqdn):\n ip = socket.gethostbyaddr(fqdn)[-1][0]\n print(fqdn, ip, '\\n')\n icmp = IP(dst=ip)/ICMP()\n resp = sr1(icmp, timeout=10)\n if resp:\n return (fqdn, False)\n else:\n return (fqdn, True)\n\n\nsites = ['www.google.com', 'www.baidu.com', 'www.bing.com']\njobs = [gevent.spawn(ping_site, fqdn) for fqdn in sites]\ngevent.joinall(jobs)\nprint([job.value for job in jobs])\n" }, { "answer_id": 71020234, "author": "Jacques MALAPRADE", "author_id": 1491879, "author_profile": "https://Stackoverflow.com/users/1491879", "pm_score": 0, "selected": false, "text": "from ping3 import ping, verbose_ping\nip-host = '8.8.8.8'\nif not ping(ip-host):\n raise ValueError('{} is not available.'.format(ip-host))\n" }, { "answer_id": 72648222, "author": "Madhav Goyal", "author_id": 18724973, "author_profile": "https://Stackoverflow.com/users/18724973", "pm_score": 0, "selected": false, "text": "import socket\ns = socket.socket()\ntry:\n s.connect((\"192.168.1.123\", 1234)) # You can use any port number here\nexcept Exception as e:\n print(e.errno, e)\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40572/" ]
316,879
<p>I have a method in an objective-C class. It has 2 callback functions written in C. The class pointer i.e. <code>self</code> is passed to these functions as <code>void *</code>. In the C functions I create a pointer of type class and assign the <code>void *</code> parameter. The first callback function executes successfully. But the <code>void *</code> pointer becomes <code>nil</code> in the 2nd callback function. Note that I haven't tweaked pointer in the first callback but still I get <code>nil</code> in 2nd callback.</p> <p>Any ideas what might be going wrong?</p> <p>For example:</p> <pre><code>kr = IOServiceAddMatchingNotification(gNotifyPort, kIOFirstMatchNotification, matchingDict, RawDeviceAdded, NULL, &amp;gRawAddedIter); RawDeviceAdded(NULL, gRawAddedIter, self); </code></pre> <p>This works fine. But below function receives <code>self</code> as <code>nil</code>.</p> <pre><code>kr = IOServiceAddMatchingNotification(gNotifyPort, kIOFirstMatchNotification, matchingDict, BulkTestDeviceAdded, NULL, &amp;gBulkTestAddedIter); BulkTestDeviceAdded(NULL, gBulkTestAddedIter, self); </code></pre>
[ { "answer_id": 316947, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 1, "selected": false, "text": "- (void)logMessage:(NSString *)message\n delegate:(id)delegate\n didLogSelector:(SEL)didLogSelector\n{\n NSLog(@\"%@\", message);\n\n if (delegate && didLogSelector && [delegate respondsToSelector:didLogSelector]) {\n (void) [delegate performSelector:didLogSelector\n withObject:self\n withObject:message];\n }\n}\n - (void)sayHello\n{\n [logger logMessage:@\"Hello, world\"\n delegate:self\n didLogSelector:@selector(messageLogger:didLogMessage:)];\n}\n\n- (void)messageLogger:(id)logger\n didLogMessage:(NSString *)message\n{\n NSLog(@\"Message logger %@ logged message '%@'\", logger, message);\n}\n objc_msgSend() []" }, { "answer_id": 317818, "author": "Boaz Stuller", "author_id": 1464654, "author_profile": "https://Stackoverflow.com/users/1464654", "pm_score": 4, "selected": false, "text": "static RawDeviceAdded(void* refcon, io_iterator_t iterator)\n{\n [(MyClass*)refcon rawDeviceAdded:iterator];\n}\n\n@implementation MyClass\n- (void)setupCallbacks\n{\n // ... all preceding setup snipped\n kr = IOServiceAddMatchingNotification(gNotifyPort,kIOFirstMatchNotification, matchingDict,RawDeviceAdded,(void*)self,&gRawAddedIter );\n // call the callback method once to 'arm' the iterator\n [self rawDeviceAdded:gRawAddedIterator];\n}\n- (void)rawDeviceAdded:(io_iterator_t)iterator\n{\n // take care of the iterator here, making sure to complete iteration to re-arm it\n}\n@end\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39270/" ]
316,889
<p>I can't seem to retrieve an ID I'm sending in a html.ActionLink in my controller, here is what I'm trying to do</p> <pre><code>&lt;li&gt; &lt;%= Html.ActionLink(&quot;Modify Villa&quot;, &quot;Modify&quot;, &quot;Villa&quot;, new { @id = &quot;1&quot; })%&gt;&lt;/li&gt; public ActionResult Modify(string ID) { ViewData[&quot;Title&quot;] =ID; return View(); } </code></pre> <p>That's what a tutorial I followed recommended, but it's not working, it's also putting ?Length=5 at the end of the URL!</p> <p>Here is the route I'm using, it's default</p> <pre><code> routes.MapRoute( &quot;Default&quot;, // Route name &quot;{controller}/{action}/{id}&quot;, // URL with parameters new { controller = &quot;Home&quot;, action = &quot;Index&quot;, id = &quot;&quot; } // Parameter defaults ); </code></pre>
[ { "answer_id": 316970, "author": "Davide Vosti", "author_id": 1812, "author_profile": "https://Stackoverflow.com/users/1812", "pm_score": 4, "selected": false, "text": "new { id = \"1\" }\n" }, { "answer_id": 316996, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 9, "selected": true, "text": "<%=Html.ActionLink(\"Modify Villa\", \"Modify\", new {id = \"1\"})%>\n <%=Html.ActionLink(\"Modify Villa\", \"Modify\", \"Villa\", new {id = \"1\"}, null)%>\n" }, { "answer_id": 13780579, "author": "Oracular Man", "author_id": 1812892, "author_profile": "https://Stackoverflow.com/users/1812892", "pm_score": 5, "selected": false, "text": "@Html.ActionLink(\"Select\", \"Create\", \"StudentApplication\", new { id=item.PersonId }, null) \n" }, { "answer_id": 36514477, "author": "ebsom", "author_id": 3406303, "author_profile": "https://Stackoverflow.com/users/3406303", "pm_score": 2, "selected": false, "text": "@ null @Html.ActionLink(\"Label Name\", \"Name_Of_Page_To_Redirect\", \"Controller\", new {@id=\"Id_Value\"}, null)\n" }, { "answer_id": 37188240, "author": "César León", "author_id": 4905197, "author_profile": "https://Stackoverflow.com/users/4905197", "pm_score": 3, "selected": false, "text": "@Html.ActionLink(\"LinkText\", \"ActionName\", new { id = \"id\" })\n" }, { "answer_id": 74124471, "author": "Ali Issa", "author_id": 15336921, "author_profile": "https://Stackoverflow.com/users/15336921", "pm_score": 0, "selected": false, "text": "This should generate a link like the following:\n\n/movies/index/1\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316889", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29445/" ]
316,899
<p>I want to change the behavior of a JavaScript used to display a banner, coming from a central source.</p> <p>Today I include a script-tag inline in code, like this:</p> <pre><code>&lt;script type=&quot;text/javascript&quot; src=&quot;http://banner.com/b?id=1234&quot;&gt;&lt;/script&gt; </code></pre> <p>But what that returns is code which uses <code>document.write</code>, like this:</p> <pre><code>if(condition) { document.write('&lt;a href=&quot;...&quot;&gt;&lt;img src=&quot;...&quot; /&gt;&lt;/a&gt;') } </code></pre> <p>I want to somehow override this <code>document.write</code> and maybe evaluate the returned code and instead use a JavaScript-framework to bind code to a div-element at DOM ready.</p> <p>Is there a way to do that? Something like this?:</p> <pre><code>OnDOMReady() { BindBanner(1234); } BindBanner(bannerId) { var divTag = document.getElementById('banner_' + bannerId); divTag.innerHtml = ManipulatedReturenedCode(bannerId); } </code></pre> <p>Can JavaScript's prototyping handle something like this?</p> <p><strong>Edit</strong>: It has to be somewhat waterproof cross-platform, cross-browser-compatible, so I don't know if changing <code>document.write</code> is ok.</p>
[ { "answer_id": 316906, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 1, "selected": false, "text": "var foo = document.write;\nvar bannerCode = '';\ndocument.write = function(str) { bannerCode += str; };\n document.write = foo;\nalert(bannerCode);\n" }, { "answer_id": 316971, "author": "kgiannakakis", "author_id": 24054, "author_profile": "https://Stackoverflow.com/users/24054", "pm_score": -1, "selected": false, "text": "$.ready(function() {\n\n});\n $(\"#div_id\").html\n" }, { "answer_id": 317057, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 2, "selected": true, "text": "<div id=\"advertgoeshere\"></div>\n\n<script type=\"text/javascript\">\n function rewrite(w) {\n document.getElementById('advertgoeshere').innerHTML+= w;\n }\n\n window.onload= function() {\n document.write= rewrite;\n var script= document.createElement('script');\n script.type= 'text/javascript';\n script.src= 'http://externalsite/ads.js';\n document.body.appendChild(script);\n }\n</script>\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2429/" ]
316,900
<p>I'm working on a windows client written in WPF with C# on .Net 3.5 Sp1, where a requirement is that data from emails received by clients can be stored in the database. Right now the easiest way to handle this is to copy and paste the text, subject, contact information and time received manually using an arthritis-inducing amount of ctrl-c/ctrl-v.</p> <p>I thought that a simple way to handle this would be to allow the user to drag one or more emails from Outlook (they are all using Outlook 2007 currently) into the window, allowing my app to extract the necessary information and send it to the backend system for storage.</p> <p>However, a few hours googling for information on this seem to indicate a shocking lack of information about this seemingly basic task. I would think that something like this would be useful in a lot of different settings, but all I've been able to find so far have been half-baked non-solutions. </p> <p>Does anyone have any advice on how to do this? Since I am just going to read the mails and not send anything out or do anything evil, it would be nice with a solution that didn't involve the hated security pop ups, but anything beats not being able to do it at all.</p> <p>Basically, if I could get a list of all the mail items that were selected, dragged and dropped from Outlook, I will be able to handle the rest myself!</p> <p>Thanks!</p> <p>Rune</p>
[ { "answer_id": 318045, "author": "cgreeno", "author_id": 6088, "author_profile": "https://Stackoverflow.com/users/6088", "pm_score": 2, "selected": false, "text": "<TextBlock\n Name=\"myTextBlock\" \n Text=\"Drag something into here\"\n AllowDrop=\"True\" \n DragDrop.Drop=\"myTextBlock_Drop\"\n />\n private void myTextBlock_Drop(object sender, DragEventArgs e)\n{\n // Mark the event as handled, so TextBox's native Drop handler is not called.\n e.Handled = true;\n Stream sr;\n\n //Explorer \n if (e.Data.GetDataPresent(DataFormats.FileDrop, true))\n //Do somthing\n\n //Email Message Subject \n if (e.Data.GetDataPresent(\"FileGroupDescriptor\"))\n {\n sr = e.Data.GetData(\"FileGroupDescriptor\") as Stream;\n StreamReader sr = new StreamReader(sr2);//new StreamReader(strPath, Encoding.Default);\n //Message Subject\n string strFullString = sr.ReadToEnd();\n }\n\n\n}\n" }, { "answer_id": 972867, "author": "Bryce Kahle", "author_id": 73509, "author_profile": "https://Stackoverflow.com/users/73509", "pm_score": 6, "selected": true, "text": "FieldInfo innerDataField = this.underlyingDataObject.GetType().GetField(\"innerData\", BindingFlags.NonPublic | BindingFlags.Instance);\n FieldInfo innerDataField = this.underlyingDataObject.GetType().GetField(\"_innerData\", BindingFlags.NonPublic | BindingFlags.Instance);\n public void SetData(string format, bool autoConvert, object data)\n{\n this.underlyingDataObject.SetData(format, autoConvert, data);\n}\n public void SetData(string format, object data, bool autoConvert)\n{\n this.underlyingDataObject.SetData(format, data, autoConvert);\n}\n" }, { "answer_id": 4656231, "author": "Zolomon", "author_id": 182153, "author_profile": "https://Stackoverflow.com/users/182153", "pm_score": 1, "selected": false, "text": "EntryID StoreID Imports Microsoft.Office.Interop\n\nPublic Class OutlookClientHandler\n\nPrivate _application As Outlook.Application\nPrivate _namespace As Outlook.NameSpace\n\nPublic Sub New()\n If Process.GetProcessesByName(\"outlook\".ToLower).Length > 0 Then\n _application = New Outlook.Application\n Else\n Dim startInfo As ProcessStartInfo = New ProcessStartInfo(\"outlook.exe\")\n startInfo.WindowStyle = ProcessWindowStyle.Minimized\n Process.Start(startInfo)\n\n _application = New Outlook.Application\n End If\nEnd Sub\n\n' Retrieves the specified e-mail from Outlook/Exchange via the MAPI\nPublic Function GetMailItem(ByVal entryID as String, ByVal storeID as String) As Outlook.MailItem\n _namespace = _application.GetNamespace(\"MAPI\")\n Dim item As Outlook.MailItem\n Try\n item = _namespace.GetItemFromID(entryID, storeID)\n Catch comex As COMException\n item = Nothing ' Fugly, e-mail wasn't found!\n End Try\n\n Return item\nEnd Function\nEnd Class\n Public Function GetSelectedItems() As List(Of Object) \n Dim items As List(Of Object) = New List(Of Object)\n\n For Each item As Object In _application.ActiveExplorer().Selection\n items.Add(item)\n Next\n\n Return items\nEnd Function\n EntryID StoreID EntryID StoreID" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2122/" ]
316,903
<p>I need to know if I can create a file in a specific folder, but there are too many things to check such as permissions, duplicate files, etc. I'm looking for something like <code>File.CanCreate(@"C:\myfolder\myfile.aaa"</code>), but haven't found such a method. The only thing I thought is to try to create a dummy file and check for exceptions but this is an ungly solution that also affects performance. Do you know a better solution?</p>
[ { "answer_id": 316913, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "string file = Path.Combine(dir, Guid.NewGuid().ToString() + \".tmp\");\n// perhaps check File.Exists(file), but it would be a long-shot...\nbool canCreate;\ntry\n{\n using (File.Create(file)) { }\n File.Delete(file);\n canCreate = true;\n}\ncatch\n{\n canCreate = false;\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30729/" ]
316,911
<p>Aloha</p> <p>I have a method with (pseudo) signature:</p> <pre><code>public static T Parse&lt;T&gt;(string datadictionary) where T : List&lt;U&gt; </code></pre> <p>This doesn't build. How can I restrict the in the method to accept only generic List&lt;> objects (which should of cource not contain T's but something else :)</p> <p>I need to restrict the type of T because I need to call a method on it in this code. The type passed in is a custom collection (based on List).</p> <pre><code>public class MyCollection&lt;T&gt; : List&lt;T&gt; where T: MyClass, new() { public void Foo(); } public static T Parse&lt;T&gt;(string datadictionary) where T : MyCollection&lt;U&gt; { T.Foo(); } </code></pre> <p>-Edoode</p>
[ { "answer_id": 316925, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": true, "text": "public static T Parse<T, U>(string datadictionary) where T : List<U>\n public static List<T> Parse<T>(string datadictionary)\n List<int> data = Parse<int>(whatever);\n List<T> IList<T>" }, { "answer_id": 316952, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "T T : List<U> T U List<T> List<T> Collection<T> IList<T> : new() public static TList Parse<TList, TItem>(string datadictionary)\n where TList : IList<TItem>, new() {...}\n" }, { "answer_id": 316953, "author": "Pop Catalin", "author_id": 4685, "author_profile": "https://Stackoverflow.com/users/4685", "pm_score": 2, "selected": false, "text": "List<u> public static List<T> Parse<T>(string datadictionary) ...\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6399/" ]
316,921
<p>i`m currently playing around with WPF and now i wonder what would be the layout for a typical dataentry window (20+ textboxes and stuff).</p> <p>atm i`m using a grid object like this (basic sample)</p> <pre><code> &lt;Grid Margin="2,2,2,2"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="Auto"&gt;&lt;/ColumnDefinition&gt; &lt;ColumnDefinition Width="*"&gt;&lt;/ColumnDefinition&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid.RowDefinitions &gt; &lt;RowDefinition Height="Auto"&gt;&lt;/RowDefinition&gt; &lt;RowDefinition Height="Auto"&gt;&lt;/RowDefinition&gt; &lt;RowDefinition Height="Auto"&gt;&lt;/RowDefinition&gt; &lt;RowDefinition Height="Auto"&gt;&lt;/RowDefinition&gt; &lt;RowDefinition Height="Auto"&gt;&lt;/RowDefinition&gt; &lt;RowDefinition Height="Auto"&gt;&lt;/RowDefinition&gt; &lt;RowDefinition Height="Auto"&gt;&lt;/RowDefinition&gt; &lt;RowDefinition Height="Auto"&gt;&lt;/RowDefinition&gt; &lt;/Grid.RowDefinitions&gt; &lt;Label Grid.Row="0" Grid.Column="0"&gt;Vorname:&lt;/Label&gt; &lt;TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Path=Surname, UpdateSourceTrigger=PropertyChanged}" &gt;&lt;/TextBox&gt; &lt;Label Grid.Row="1" Grid.Column="0"&gt;Nachname:&lt;/Label&gt; &lt;TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Path=ChristianName, UpdateSourceTrigger=PropertyChanged}"&gt;&lt;/TextBox&gt; &lt;Label Grid.Row="2" Grid.Column="0"&gt;Strasse (Wohnsitz):&lt;/Label&gt; &lt;TextBox Grid.Row="2" Grid.Column="1" Text="{Binding Path=Street1, UpdateSourceTrigger=PropertyChanged}"&gt;&lt;/TextBox&gt; &lt;Label Grid.Row="3" Grid.Column="0"&gt;Ort (Wohnsitz):&lt;/Label&gt; &lt;TextBox Grid.Row="3" Grid.Column="1" Text="{Binding Path=Town1, UpdateSourceTrigger=PropertyChanged}"&gt;&lt;/TextBox&gt; &lt;Label Grid.Row="4" Grid.Column="0"&gt;Postleitzahl (Wohnsitz):&lt;/Label&gt; &lt;TextBox Grid.Row="4" Grid.Column="1" Text="{Binding Path=PostalCode1, UpdateSourceTrigger=PropertyChanged}"&gt;&lt;/TextBox&gt; &lt;Label Grid.Row="5" Grid.Column="0"&gt;Bundesland (Wohnsitz):&lt;/Label&gt; &lt;TextBox Grid.Row="5" Grid.Column="1" Text="{Binding Path=State1, UpdateSourceTrigger=PropertyChanged}"&gt;&lt;/TextBox&gt; &lt;Label Grid.Row="6" Grid.Column="0"&gt;Land (Wohnsitz):&lt;/Label&gt; &lt;TextBox Grid.Row="6" Grid.Column="1" Text="{Binding Path=Country1, UpdateSourceTrigger=PropertyChanged}"&gt;&lt;/TextBox&gt; &lt;Label Grid.Row="7" Grid.Column="0"&gt;Zusatz (Wohnsitz):&lt;/Label&gt; &lt;TextBox Grid.Row="7" Grid.Column="1" Text="{Binding Path=AdditionalAdrInfo1, UpdateSourceTrigger=PropertyChanged}"&gt;&lt;/TextBox&gt; &lt;/Grid&gt; </code></pre> <p>basically this satisfies all my layout needs, but what if i wish to change something, like adding a new textbox in row 3?</p> <p>currently i have to change every single Grid.Row property greater then 3, but that cant be the intended WPF way!? </p> <p>how do others layout complex dataentry windows?</p> <p>tia</p>
[ { "answer_id": 316948, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 2, "selected": false, "text": "StackPanel <local:FieldPanel>\n <Label>Field 1:</Label>\n <TextBox/>\n\n <Label>Field 2:</Label>\n <TextBox/>\n\n <Label>Field 3:</Label>\n <TextBox/>\n</local:FieldPanel>\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12406/" ]
316,924
<p>If you have a route:</p> <pre><code>routes.MapRoute("search", "{controller}/{action}/{filter1}/{filter2}/{filter3}", _ New With {.filter1 = "", .filter2 = "", .filter3 = ""}) </code></pre> <p>then in a view satisfied by the route pattern with a url of <code>/member/search/dev/phil/hoy</code>, when you attempt to create another route url with only <code>filter1</code> present i.e.</p> <pre><code>&lt;%=Url.RouteUrl(New RouteValueDictionary( New With {.controller="member",.action="search", .filter1="dev"}))%&gt; </code></pre> <p>the result is the current route <code>/member/search/dev/phil/hoy</code>, not the expected trimmed route <code>/member/search/dev</code> </p> <p>I have managed to work round the issue by using <code>RouteTable.Routes.GetVirtualPath</code> method directly, but does anyone know why it works this way or is it perhaps a bug?</p>
[ { "answer_id": 316948, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 2, "selected": false, "text": "StackPanel <local:FieldPanel>\n <Label>Field 1:</Label>\n <TextBox/>\n\n <Label>Field 2:</Label>\n <TextBox/>\n\n <Label>Field 3:</Label>\n <TextBox/>\n</local:FieldPanel>\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316924", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29547/" ]
316,931
<ul> <li>I autoformat a GridView in ASP.NET.</li> <li><p>It looks nice but the headers all run together like this:</p> <p><strong>idfirstNamelastNameage</strong></p></li> <li><p>I set CellPadding="5" but it does nothing.</p></li> </ul> <p>How can I set the cell padding of the headers and all cells?</p> <p>A D D E N D U M :</p> <p>Thanks Andrew, I fixed it with this. Works in Firefox and Explorer 7:</p> <pre><code>.gridview2 tr td { padding: 5px; border: 1px solid #ddd; } .gridview2 tr th { padding: 5px; } </code></pre>
[ { "answer_id": 316955, "author": "Andrew Bullock", "author_id": 28543, "author_profile": "https://Stackoverflow.com/users/28543", "pm_score": 5, "selected": true, "text": ".myTableClass tr th {\n padding: 5px;\n}\n" }, { "answer_id": 11330757, "author": "jumxozizi", "author_id": 1495317, "author_profile": "https://Stackoverflow.com/users/1495317", "pm_score": 0, "selected": false, "text": "#YourTableIdFoo th , #YourTableIdFoo td \n{\n padding-right: 1em;\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
316,940
<p>I'm looking for a generic method to implement a wait screen during long operations. I have used threading a few times before, but I have the feeling that I implemented it either very poorly, or with way too much hassle (and copy/pasting - the horror!).</p> <p>I want to keep this as generic and simple as possible, so I won't have to implement loads of <code>BackgroundWorker</code>s handling all kinds of crap, making things hard to maintain.</p> <p>Here's what I would like to do -- please note this might differ from what's actually possible/best practise/whatever -- using VB.NET, Framework 2.0 (so no anonymous methods):</p> <pre><code> Private Sub HandleBtnClick(sender as Object, e as EventArgs) Handles Button.Click LoadingScreen.Show() 'Do stuff here, this takes a while!' Dim Result as Object = DoSomethingTakingALongTime(SomeControl.SelectedObject) LoadingScreen.Hide() ProcessResults(Result) End Sub </code></pre> <p>The application is now completely single-threaded, so everything runs on the GUI thread. I need to be able to access objects in <code>DoSomethingTakingALongTime()</code> without getting cross-thread exceptions. The GUI thread waits for some method (which takes a long time) to complete, while the <code>LoadingScreen</code> Form should stay responsive (it's animated/has a progressbar/etc.).</p> <p>Is this a doable/good approach or am I seeing this way too simplistic? What is the best practise concerning this matter? And most importantly: how could I implement such a system? As I already mentioned, I have very little experience with threading, so be gentle please :-)</p>
[ { "answer_id": 330806, "author": "Hath", "author_id": 5186, "author_profile": "https://Stackoverflow.com/users/5186", "pm_score": 3, "selected": true, "text": "Private Sub work_CrossThreadEvent(ByVal sender As Object, ByVal e As System.EventArgs) Handles work.CrossThreadEvent\n\n If Me.InvokeRequired Then\n Me.BeginInvoke(New EventHandler(AddressOf work_CrossThreadEvent), New Object() {sender, e})\n Return\n End If\n\n Me.Text = \"Cross Thread\"\n\nEnd Sub\n New EventHandler Public MustInherit Class Worker\n\n Protected WithEvents worker As BackgroundWorker\n\n Public Sub New()\n\n worker = New BackgroundWorker()\n worker.WorkerReportsProgress = True\n worker.WorkerSupportsCancellation = True\n\n End Sub\n\n Public Sub Start()\n\n If (Not worker.IsBusy AndAlso Not worker.CancellationPending) Then\n worker.RunWorkerAsync()\n End If\n\n End Sub\n\n Public Sub Cancel()\n If (worker.IsBusy AndAlso Not worker.CancellationPending) Then\n worker.CancelAsync()\n End If\n End Sub\n\n Protected MustOverride Sub Work()\n\n Private Sub OnDoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles worker.DoWork\n Work()\n End Sub\n\n Public Event WorkCompelted As RunWorkerCompletedEventHandler\n Private Sub OnRunWorkerCompleted(ByVal sender As Object, ByVal e As RunWorkerCompletedEventArgs) Handles worker.RunWorkerCompleted\n OnRunWorkerCompleted(e)\n End Sub\n Protected Overridable Sub OnRunWorkerCompleted(ByVal e As RunWorkerCompletedEventArgs)\n RaiseEvent WorkCompelted(Me, e)\n End Sub\n\n Public Event ProgressChanged As ProgressChangedEventHandler\n Private Sub OnProgressChanged(ByVal sender As Object, ByVal e As ProgressChangedEventArgs) Handles worker.ProgressChanged\n OnProgressChanged(e)\n End Sub\n Protected Overridable Sub OnProgressChanged(ByVal e As ProgressChangedEventArgs)\n RaiseEvent ProgressChanged(Me, e)\n End Sub\n\nEnd Class\n\nPublic Class ActualWork\n Inherits Worker\n\n Public Event CrossThreadEvent As EventHandler\n\n Protected Overrides Sub Work()\n\n 'do work here'\n WorkABit()\n worker.ReportProgress(25)\n\n WorkABit()\n worker.ReportProgress(50)\n\n WorkABit()\n worker.ReportProgress(75)\n\n WorkABit()\n worker.ReportProgress(100)\n\n End Sub\n\n Private Sub WorkABit()\n\n If worker.CancellationPending Then Return\n Thread.Sleep(1000)\n RaiseEvent CrossThreadEvent(Me, EventArgs.Empty)\n\n End Sub\n\nEnd Class\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39259/" ]
316,965
<p>I can only think of Peek() and ReadNoAdvance() atm, but I wonder if there are better or standard options.</p> <p>Thanks.</p>
[ { "answer_id": 5839282, "author": "hippietrail", "author_id": 527702, "author_profile": "https://Stackoverflow.com/users/527702", "pm_score": 1, "selected": false, "text": "lookahead" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7839/" ]
316,967
<p>I have need to select a number of 'master' rows from a table, also returning for each result a number of detail rows from another table. What is a good way of achieving this without multiple queries (one for the master rows and one per result to get the detail rows).</p> <p>For example, with a database structure like below:</p> <pre><code>MasterTable: - MasterId BIGINT - Name NVARCHAR(100) DetailTable: - DetailId BIGINT - MasterId BIGINT - Amount MONEY </code></pre> <p>How would I most efficiently populate the <code>data</code> object below?</p> <pre><code>IList&lt;MasterDetail&gt; data; public class Master { private readonly List&lt;Detail&gt; _details = new List&lt;Detail&gt;(); public long MasterId { get; set; } public string Name { get; set; } public IList&lt;Detail&gt; Details { get { return _details; } } } public class Detail { public long DetailId { get; set; } public decimal Amount { get; set; } } </code></pre>
[ { "answer_id": 317041, "author": "Wolfwyrd", "author_id": 15570, "author_profile": "https://Stackoverflow.com/users/15570", "pm_score": 0, "selected": false, "text": "List<Master> allMasters = GetAllMasters();\nList<Detail> allDetail = getAllDetail();\n\nforeach (Master m in allMasters)\n m.Details.Add(allDetail.FindAll(delegate (Detail d) { return d.MasterId==m.MasterId });\n GetAllMasters GetAllDetail" }, { "answer_id": 317076, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "SELECT parent.*,\n (SELECT * FROM child\n WHERE child.parentid = parent.id FOR XML PATH('child'), TYPE)\nFROM parent\nFOR XML PATH('parent')\n // sample from MSDN\nNorthwnd db = new Northwnd(@\"c:\\northwnd.mdf\");\nDataLoadOptions dlo = new DataLoadOptions();\ndlo.LoadWith<Customer>(c => c.Orders);\ndb.LoadOptions = dlo;\n\nvar londonCustomers =\n from cust in db.Customers\n where cust.City == \"London\"\n select cust;\n\nforeach (var custObj in londonCustomers)\n{\n Console.WriteLine(custObj.CustomerID);\n}\n LoadWith" }, { "answer_id": 317091, "author": "Garry Shutler", "author_id": 6369, "author_profile": "https://Stackoverflow.com/users/6369", "pm_score": 2, "selected": false, "text": "select MasterTable.MasterId,\n MasterTable.Name,\n DetailTable.DetailId,\n DetailTable.Amount\nfrom MasterTable\n inner join\n DetailTable\n on MasterTable.MasterId = DetailTable.MasterId\norder by MasterTable.MasterId\n foreach(row in result)\n{\n if (row.MasterId != currentMaster.MasterId)\n {\n list.Add(currentMaster);\n currentMaster = new Master { MasterId = row.MasterId, Name = row.Name };\n }\n currentMaster.Details.Add(new Detail { DetailId = row.DetailId, Amount = row.Amount});\n}\nlist.Add(currentMaster);\n" }, { "answer_id": 326993, "author": "Scott Whitlock", "author_id": 17635, "author_profile": "https://Stackoverflow.com/users/17635", "pm_score": 0, "selected": false, "text": "Dim master as New BusinessObjects.Master\nmaster.LoadByPrimaryKey(43)\nConsole.PrintLine(master.Name)\nFor Each detail as BusinessObjects.Detail in master.DetailCollectionByMasterId\n Console.PrintLine(detail.Amount)\n detail.Amount *= 1.15\nEnd For\nWith master.DetailCollectionByMasterId.AddNew\n .Amount = 13\nEnd With\nmaster.Save()\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4048/" ]
316,978
<p>I have a bunch of rows in Excel that I want to paste into a new table in MS SQL. Is there a simple way ?</p>
[ { "answer_id": 317003, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 6, "selected": true, "text": "=\"insert into tblyourtablename (yourkeyID_pk, intmine, strval) values (\"&A4&\", \"&B4&\", N'\"&C4&\"')\"" }, { "answer_id": 26219806, "author": "BriFri238", "author_id": 4113930, "author_profile": "https://Stackoverflow.com/users/4113930", "pm_score": 2, "selected": false, "text": "Sub TransferToSQL()\n'\n' TransferToSQL Macro\n' This macro prepares data for pasting into SQL Server and posts it to the clipboard for inserting into SSMS\n' It attempts to automatically detect header rows and does a basic analysis of the first 15 rows to determine the most appropriate datatype to use handling text entries upto 1000 chars.\n'\n' Max Number of Columns: 200\n'\n' Keyboard Shortcut: Ctrl+Shift+X\n'\n' ver Date Reason\n' === ==== ======\n\n' 1.6 06/2012 Fixed bug that prevented auto exit if no selection made / auto exit if blank Tablename entered or 'cancel' button pressed\n' 1.5 02/2012 made use of function fn_ColLetter to retrieve the Column Letter for a specified column\n' 1.4 02/2012 Replaces any Tabs in text data to spaces to prevent Double quotes being output in final results\n' 1.3 02/2012 Place the 'drop table if already exists' code into a separate batch to prevent errors when inserting new table with same name but different shape and > 100 rows\n' 1.2 01/2012 If null dates encountered code to cast it as Null rather than '00-Jan-1900'\n' 1.1 10/2011 Code to drop the table if already exists\n' 1.0 03/2011 Created\n\nDim intLastRow As Long\nDim intlastColumn As Integer\nDim intRow As Long\nDim intDataStartRow As Long\nDim intColumn As Integer\nDim strKeyWord As String\nDim intPos As Integer\nDim strDataTypeLevel(4) As String\nDim strColumnHeader(200) As String\nDim strDataType(200) As String\nDim intRowCheck As Integer\nDim strFormula(20) As String\nDim intHasHeaderRow As Integer\nDim strCellRef As String\nDim intFormulaCount As Integer\nDim strSQLTableName As String\nDim strSQLTableName_Encap As String\nDim intdataTypelevel As Integer\nConst strConstHeaderKeyword As String = \"ID,URN,name,Title,Job,Company,Contact,Address,Post,Town,Email,Tele,phone,Area,Region,Business,Total,Month,Week,Year,\"\nConst intConstMaxBatchSize As Integer = 100\n Const intConstNumberRowsToAnalyse As Integer = 100\nintHasHeaderRow = 0\n\nstrDataTypeLevel(1) = \"VARCHAR(1000)\"\nstrDataTypeLevel(2) = \"FLOAT\"\nstrDataTypeLevel(3) = \"INTEGER\"\nstrDataTypeLevel(4) = \"DATETIME\"\n\n\n\n' Use current selection and paste to new temp worksheet\n\n Selection.Copy\n Workbooks.Add ' add temp 'Working' Workbook\n ' Paste \"Values Only\" back into new temp workbook\n Range(\"A3\").Select ' Goto 3rd Row\n Selection.PasteSpecial Paste:=xlFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False ' Copy Format of Selection\n Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False ' Copy Values of Selection\n ActiveCell.SpecialCells(xlLastCell).Select ' Goto last cell\n intLastRow = ActiveCell.Row\n intlastColumn = ActiveCell.Column\n\n\n' Check to make sure that there are cells which are selected\nIf intLastRow = 3 And intlastColumn = 1 Then\n Application.DisplayAlerts = False ' Temporarily switch off Display Alerts\n ActiveWindow.Close ' Delete newly created worksheet\n Application.DisplayAlerts = True ' Switch display alerts back on\n MsgBox \"*** Please Make selection before running macro - Terminating ***\", vbOKOnly, \"Transfer Data to SQL Server\"\n Exit Sub\nEnd If\n\n' Prompt user for Name of SQL Server table\nstrSQLTableName = InputBox(\"SQL Server Table Name?\", \"Transfer Excel Data To SQL\", \"##Table\")\n\n' if blank table name entered or 'Cancel' selected then exit\nIf strSQLTableName = \"\" Then\n Application.DisplayAlerts = False ' Temporarily switch off Display Alerts\n ActiveWindow.Close ' Delete newly created worksheet\n Application.DisplayAlerts = True ' Switch display alerts back on\n Exit Sub\nEnd If\n\n\n\n' encapsulate tablename with square brackets if user has not already done so\nstrSQLTableName_Encap = Replace(Replace(Replace(\"[\" & Replace(strSQLTableName, \".\", \"].[\") & \"]\", \"[]\", \"\"), \"[[\", \"[\"), \"]]\", \"]\")\n\n' Try to determine if the First Row is a header row or contains data and if a header load names of Columns\nRange(\"A3\").Select\nFor intColumn = 1 To intlastColumn\n ' first check to see if the first row contains any pure numbers or pure dates\n If IsNumeric(ActiveCell.Value) Or IsDate(ActiveCell.Value) Then\n intHasHeaderRow = vbNo\n intDataStartRow = 3\n Exit For\n Else\n strColumnHeader(intColumn) = ActiveCell.Value\n ActiveCell.Offset(1, 0).Range(\"A1\").Select ' go to the row below\n If IsNumeric(ActiveCell.Value) Or IsDate(ActiveCell.Value) Then\n intHasHeaderRow = vbYes\n intDataStartRow = 4\n End If\n ActiveCell.Offset(-1, 0).Range(\"A1\").Select ' go back up to the first row\n If intHasHeaderRow = 0 Then ' if still not determined if header exists: Look for header using keywords\n intPos = 1\n While intPos < Len(strConstHeaderKeyword) And intHasHeaderRow = 0\n strKeyWord = Mid$(strConstHeaderKeyword, intPos, InStr(intPos, strConstHeaderKeyword, \",\") - intPos)\n If InStr(1, ActiveCell.Value, strKeyWord) > 0 Then\n intHasHeaderRow = vbYes\n intDataStartRow = 4\n End If\n intPos = InStr(intPos, strConstHeaderKeyword, \",\") + 1\n Wend\n End If\n End If\n ActiveCell.Offset(0, 1).Range(\"A1\").Select ' Goto next column\nNext intColumn\n\n' If auto header row detection has failed ask the user to manually select\nIf intHasHeaderRow = 0 Then\n intHasHeaderRow = MsgBox(\"Does current selection have a header row?\", vbYesNo, \"Auto header row detection failure\")\n If intHasHeaderRow = vbYes Then\n intDataStartRow = 4\n Else\n intDataStartRow = 3\n End If\n\nEnd If\n\n\n\n\n' *** Determine the Data Type of each Column ***\n\n' Go thru each Column to find Data types\nIf intLastRow < intConstNumberRowsToAnalyse Then ' Check the first intConstNumberRowsToAnalyse rows or to end of selection whichever is less\n intRowCheck = intLastRow\nElse\n intRowCheck = intConstNumberRowsToAnalyse \nEnd If\n\nFor intColumn = 1 To intlastColumn\n intdataTypelevel = 5\n\n For intRow = intDataStartRow To intRowCheck\n Application.Goto Reference:=\"R\" & CStr(intRow) & \"C\" & CStr(intColumn)\n If ActiveCell.Value = \"\" Then ' ignore blank (null) values\n ElseIf IsDate(ActiveCell.Value) = True And Len(ActiveCell.Value) >= 8 Then\n If intdataTypelevel > 4 Then intdataTypelevel = 4\n ElseIf IsNumeric(ActiveCell.Value) = True And InStr(1, CStr(ActiveCell.Value), \".\") = 0 And (Left(CStr(ActiveCell.Value), 1) <> \"0\" Or ActiveCell.Value = \"0\") And Len(ActiveCell.Value) < 10 Then\n If intdataTypelevel > 3 Then intdataTypelevel = 3\n ElseIf IsNumeric(ActiveCell.Value) = True And InStr(1, CStr(ActiveCell.Value), \".\") >= 1 Then\n If intdataTypelevel > 2 Then intdataTypelevel = 2\n Else\n intdataTypelevel = 1\n Exit For\n End If\n Next intRow\n If intdataTypelevel = 5 Then intdataTypelevel = 1\n strDataType(intColumn) = strDataTypeLevel(intdataTypelevel)\nNext intColumn\n\n\n' *** Build up the SQL\nintFormulaCount = 1\nIf intHasHeaderRow = vbYes Then ' *** Header Row ***\n Application.Goto Reference:=\"R4\" & \"C\" & CStr(intlastColumn + 1) ' Goto next column in first data row of selection\n strFormula(intFormulaCount) = \"= \"\"SELECT \"\n For intColumn = 1 To intlastColumn\n If strDataType(intColumn) = \"DATETIME\" Then ' Code to take Excel Dates back to text\n strCellRef = \"Text(\" & fn_ColLetter(intColumn) & \"4,\"\"dd-mmm-yyyy hh:mm:ss\"\")\"\n ElseIf strDataType(intColumn) = \"VARCHAR(1000)\" Then\n strCellRef = \"SUBSTITUTE(\" & fn_ColLetter(intColumn) & \"4,\"\"'\"\",\"\"''\"\")\" ' Convert any single ' to double ''\n Else\n strCellRef = fn_ColLetter(intColumn) & \"4\"\n End If\n\n\n strFormula(intFormulaCount) = strFormula(intFormulaCount) & \"CAST('\"\"& \" & strCellRef & \" & \"\"' AS \" & strDataType(intColumn) & \") AS [\" & strColumnHeader(intColumn) & \"]\"\n If intColumn < intlastColumn Then\n strFormula(intFormulaCount) = strFormula(intFormulaCount) + \", \"\n Else\n strFormula(intFormulaCount) = strFormula(intFormulaCount) + \" UNION ALL \"\"\"\n End If\n ' since each cell can only hold a maximum no. of chars if Formula string gets too big continue formula in adjacent cell\n If Len(strFormula(intFormulaCount)) > 700 And intColumn < intlastColumn Then\n strFormula(intFormulaCount) = strFormula(intFormulaCount) + \"\"\"\"\n intFormulaCount = intFormulaCount + 1\n strFormula(intFormulaCount) = \"= \"\"\"\n End If\n Next intColumn\n\n ' Assign the formula to the cell(s) just right of the selection\n For intColumn = 1 To intFormulaCount\n ActiveCell.Value = strFormula(intColumn)\n If intColumn < intFormulaCount Then ActiveCell.Offset(0, 1).Range(\"A1\").Select ' Goto next column\n Next intColumn\n\n\n ' Auto Fill the formula for the full length of the selection\n ActiveCell.Offset(0, -intFormulaCount + 1).Range(\"A1:\" & fn_ColLetter(intFormulaCount) & \"1\").Select\n If intLastRow > 4 Then Selection.AutoFill Destination:=Range(fn_ColLetter(intlastColumn + 1) & \"4:\" & fn_ColLetter(intlastColumn + intFormulaCount) & CStr(intLastRow)), Type:=xlFillDefault\n\n ' Go to start row of data selection to add 'Select into' code\n ActiveCell.Value = \"SELECT * INTO \" & strSQLTableName_Encap & \" FROM (\" & ActiveCell.Value\n\n ' Go to cells above data to insert code for deleting old table with the same name in separate SQL batch\n ActiveCell.Offset(-1, 0).Range(\"A1\").Select ' go to the row above\n ActiveCell.Value = \"GO\"\n ActiveCell.Offset(-1, 0).Range(\"A1\").Select ' go to the row above\n If Left(strSQLTableName, 1) = \"#\" Then ' temp table\n ActiveCell.Value = \"IF OBJECT_ID('tempdb..\" & strSQLTableName & \"') IS NOT NULL DROP TABLE \" & strSQLTableName_Encap\n Else\n ActiveCell.Value = \"IF OBJECT_ID('\" & strSQLTableName & \"') IS NOT NULL DROP TABLE \" & strSQLTableName_Encap\n End If\n\n\n\n' For Big selections (i.e. several 100 or 1000 rows) SQL Server takes a very long time to do a multiple union - Split up the table creation into many inserts\n intRow = intConstMaxBatchSize + 4 ' add 4 to make sure 1st batch = Max Batch Size\n While intRow < intLastRow\n Application.Goto Reference:=\"R\" & CStr(intRow - 1) & \"C\" & CStr(intlastColumn + intFormulaCount) ' Goto Row before intRow and the last column in formula selection\n ActiveCell.Value = Replace(ActiveCell.Value, \" UNION ALL \", \" ) a\") ' Remove last 'UNION ALL'\n\n Application.Goto Reference:=\"R\" & CStr(intRow) & \"C\" & CStr(intlastColumn + 1) ' Goto intRow and the first column in formula selection\n ActiveCell.Value = \"INSERT \" & strSQLTableName_Encap & \" SELECT * FROM (\" & ActiveCell.Value\n intRow = intRow + intConstMaxBatchSize ' increment intRow by intConstMaxBatchSize\n Wend\n\n\n ' Delete the last 'UNION AlL' replacing it with brackets to mark the end of the last insert\n Application.Goto Reference:=\"R\" & CStr(intLastRow) & \"C\" & CStr(intlastColumn + intFormulaCount)\n ActiveCell.Value = Replace(ActiveCell.Value, \" UNION ALL \", \" ) a\")\n\n ' Select all the formula cells\n ActiveCell.Offset(-intLastRow + 2, 1 - intFormulaCount).Range(\"A1:\" & fn_ColLetter(intFormulaCount + 1) & CStr(intLastRow - 1)).Select\nElse ' *** No Header Row ***\n Application.Goto Reference:=\"R3\" & \"C\" & CStr(intlastColumn + 1) ' Goto next column in first data row of selection\n strFormula(intFormulaCount) = \"= \"\"SELECT \"\n\n For intColumn = 1 To intlastColumn\n If strDataType(intColumn) = \"DATETIME\" Then\n strCellRef = \"Text(\" & fn_ColLetter(intColumn) & \"3,\"\"dd-mmm-yyyy hh:mm:ss\"\")\" ' Format Excel dates into a text Date format that SQL will pick up\n ElseIf strDataType(intColumn) = \"VARCHAR(1000)\" Then\n strCellRef = \"SUBSTITUTE(\" & fn_ColLetter(intColumn) & \"3,\"\"'\"\",\"\"''\"\")\" ' Change all single ' to double ''\n Else\n strCellRef = fn_ColLetter(intColumn) & \"3\"\n End If\n\n ' Since no column headers: Name each column \"Column001\",Column002\"..\n strFormula(intFormulaCount) = strFormula(intFormulaCount) & \"CAST('\"\"& \" & strCellRef & \" & \"\"' AS \" & strDataType(intColumn) & \") AS [Column\" & CStr(intColumn) & \"]\"\n If intColumn < intlastColumn Then\n strFormula(intFormulaCount) = strFormula(intFormulaCount) + \", \"\n Else\n strFormula(intFormulaCount) = strFormula(intFormulaCount) + \" UNION ALL \"\"\"\n End If\n\n ' since each cell can only hold a maximum no. of chars if Formula string gets too big continue formula in adjacent cell\n If Len(strFormula(intFormulaCount)) > 700 And intColumn < intlastColumn Then\n strFormula(intFormulaCount) = strFormula(intFormulaCount) + \"\"\"\"\n intFormulaCount = intFormulaCount + 1\n strFormula(intFormulaCount) = \"= \"\"\"\n End If\n Next intColumn\n\n ' Assign the formula to the cell(s) just right of the selection\n For intColumn = 1 To intFormulaCount\n ActiveCell.Value = strFormula(intColumn)\n If intColumn < intFormulaCount Then ActiveCell.Offset(0, 1).Range(\"A1\").Select ' Goto next column\n Next intColumn\n\n ' Auto Fill the formula for the full length of the selection\n ActiveCell.Offset(0, -intFormulaCount + 1).Range(\"A1:\" & fn_ColLetter(intFormulaCount) & \"1\").Select\n If intLastRow > 4 Then Selection.AutoFill Destination:=Range(fn_ColLetter(intlastColumn + 1) & \"3:\" & fn_ColLetter(intlastColumn + intFormulaCount) & CStr(intLastRow)), Type:=xlFillDefault\n\n ' Go to start row of data selection to add 'Select into' code\n ActiveCell.Value = \"SELECT * INTO \" & strSQLTableName_Encap & \" FROM (\" & ActiveCell.Value\n\n ' Go to cells above data to insert code for deleting old table with the same name in separate SQL batch\n ActiveCell.Offset(-1, 0).Range(\"A1\").Select ' go to the row above\n ActiveCell.Value = \"GO\"\n ActiveCell.Offset(-1, 0).Range(\"A1\").Select ' go to the row above\n If Left(strSQLTableName, 1) = \"#\" Then ' temp table\n ActiveCell.Value = \"IF OBJECT_ID('tempdb..\" & strSQLTableName & \"') IS NOT NULL DROP TABLE \" & strSQLTableName_Encap\n Else\n ActiveCell.Value = \"IF OBJECT_ID('\" & strSQLTableName & \"') IS NOT NULL DROP TABLE \" & strSQLTableName_Encap\n End If\n\n ' For Big selections (i.e. serveral 100 or 1000 rows) SQL Server takes a very long time to do a multiple union - Split up the table creation into many inserts\n intRow = intConstMaxBatchSize + 3 ' add 3 to make sure 1st batch = Max Batch Size\n While intRow < intLastRow\n Application.Goto Reference:=\"R\" & CStr(intRow - 1) & \"C\" & CStr(intlastColumn + intFormulaCount) ' Goto Row before intRow and the last column in formula selection\n ActiveCell.Value = Replace(ActiveCell.Value, \" UNION ALL \", \" ) a\") ' Remove last 'UNION ALL'\n\n Application.Goto Reference:=\"R\" & CStr(intRow) & \"C\" & CStr(intlastColumn + 1) ' Goto intRow and the first column in formula selection\n ActiveCell.Value = \"INSERT \" & strSQLTableName_Encap & \" SELECT * FROM (\" & ActiveCell.Value\n intRow = intRow + intConstMaxBatchSize ' increment intRow by intConstMaxBatchSize\n Wend\n\n ' Delete the last 'UNION AlL'\n Application.Goto Reference:=\"R\" & CStr(intLastRow) & \"C\" & CStr(intlastColumn + intFormulaCount)\n ActiveCell.Value = Replace(ActiveCell.Value, \" UNION ALL \", \" ) a\")\n\n ' Select all the formula cells\n ActiveCell.Offset(-intLastRow + 1, 1 - intFormulaCount).Range(\"A1:\" & fn_ColLetter(intFormulaCount + 1) & CStr(intLastRow)).Select\nEnd If\n\n\n' Final Selection to clipboard and Cleaning of data\nSelection.Copy\nSelection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False ' Repaste \"Values Only\" back into cells\nSelection.Replace What:=\"CAST('' AS\", Replacement:=\"CAST(NULL AS\", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False ' convert all blank cells to NULL\nSelection.Replace What:=\"'00-Jan-1900 00:00:00'\", Replacement:=\"NULL\", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False ' convert all blank Date cells to NULL\nSelection.Replace What:=\"'NULL'\", Replacement:=\"NULL\", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False ' convert all 'NULL' cells to NULL\nSelection.Replace What:=vbTab, Replacement:=\" \", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False ' Replace all Tabs in cells to Space to prevent Double Quotes occuring in the final paste text\nSelection.Copy\n\n\nMsgBox \"SQL Code has been added to clipboard - Please Paste into SSMS window\", vbOKOnly, \"Transfer to SQL\"\n\nApplication.DisplayAlerts = False ' Temporarily switch off Display Alerts\nActiveWindow.Close ' Delete newly created worksheet\nApplication.DisplayAlerts = True ' Switch display alerts back on\n\n\n\nEnd Sub\n\n\n\n\nFunction fn_ColLetter(Col As Integer) As String\n\nDim strColLetter As String\n\nIf Col > 26 Then\n ' double letter columns\n strColLetter = Chr(Int((Col - 1) / 26) + 64) & _\n Chr(((Col - 1) Mod 26) + 65)\nElse\n ' single letter columns\n strColLetter = Chr(Col + 64)\nEnd If\nfn_ColLetter = strColLetter\nEnd Function\n" }, { "answer_id": 47342116, "author": "taji01", "author_id": 4767245, "author_profile": "https://Stackoverflow.com/users/4767245", "pm_score": 5, "selected": false, "text": "Identity Specification Edit Top 200 Rows" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39426/" ]
316,988
<p>I am developing an application and want to display a form that will be filled in if editing the form, but will not be if the form will be a new entry. I believe the least verbose way of doing this is to have just one form and to suppress any errors for echoing my variables so that nothing will be printed if it is a new form (since the variables will not exist if it is a new form). For example:</p> <pre><code>&lt;?php if ( ! $new_item) { $variable = 'Example'; } ?&gt; &lt;form&gt; &lt;input type="text" name="inputbox" value="&lt;?php echo @$variable; ?&gt;" /&gt; &lt;/form&gt; </code></pre> <p>Is this a good practice, or is there a better way of doing it? Should I make separate views for the new items and for the items to be edited? What are the performance repercussions of doing this?</p>
[ { "answer_id": 316993, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 1, "selected": false, "text": "if ( ! $new_item) {\n $variable = 'Example';\n} else {\n $variable = 'Default value'; \n //or\n $variable = '';\n}\n @ htmlentities() htmlspecialchars() class example {\n public $somefield = 'default value';\n}\n $record = mysql_fetch_object($result, 'example');\n $record = new example(); \n $record->somefield <form>\n <input type=\"text\" name=\"somefield\" value=\"<?php echo htmlspecialchars($record->somefield); ?>\" />\n</form>\n" }, { "answer_id": 316999, "author": "benlumley", "author_id": 39161, "author_profile": "https://Stackoverflow.com/users/39161", "pm_score": 2, "selected": false, "text": "$variable = (isset($new_item) && $new_item) ? 'Example' : 'Default Value';\n" }, { "answer_id": 317068, "author": "Aron Rotteveel", "author_id": 11568, "author_profile": "https://Stackoverflow.com/users/11568", "pm_score": 2, "selected": false, "text": "<?php echo ((isset($value) && $value != '') ? $value : 'Default'); ?>\n function useDefault($value, $default = '')\n{\n if (isset($value) && $value != '')\n {\n return $value;\n }\n else\n {\n return $default;\n }\n}\n <?php echo useDefault($value, 'default value'); ?>\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/316988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3831/" ]
317,001
<p>What are the other ways of achieving auto-increment in oracle other than use of triggers?</p>
[ { "answer_id": 317116, "author": "angus", "author_id": 36925, "author_profile": "https://Stackoverflow.com/users/36925", "pm_score": 4, "selected": false, "text": "CREATE TABLE xxx ( ID RAW(16) DEFAULT SYS_GUID() )\n" }, { "answer_id": 317263, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 4, "selected": false, "text": "create trigger mytable_trg\nbefore insert on mytable\nfor each row\nwhen (new.id is null)\nbegin\n select myseq.nextval into :new.id from dual;\nend;\n insert into mytable (id, data) values (myseq.nextval, 'x');\n mytable_pkg.insert_row (p_data => 'x');\n" }, { "answer_id": 319194, "author": "FerranB", "author_id": 40441, "author_profile": "https://Stackoverflow.com/users/40441", "pm_score": 2, "selected": false, "text": "create sequence seq;\n insert into table (id, other1, other2)\nvalues (seq.nextval, 'hello', 'world');\n" }, { "answer_id": 330714, "author": "kedar kamthe", "author_id": 18709, "author_profile": "https://Stackoverflow.com/users/18709", "pm_score": -1, "selected": false, "text": "SELECT max (id) + 1 \nFROM table\n" }, { "answer_id": 2400900, "author": "XpiritO", "author_id": 76219, "author_profile": "https://Stackoverflow.com/users/76219", "pm_score": 0, "selected": false, "text": "getGeneratedKeys() Statement stmt = null;\nResultSet rs = null;\n\nstmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY,\n java.sql.ResultSet.CONCUR_UPDATABLE);\n\nstmt.executeUpdate(\"DROP TABLE IF EXISTS autoIncTable\");\n\nstmt.executeUpdate(\"CREATE TABLE autoIncTable (\"\n + \"priKey INT NOT NULL AUTO_INCREMENT, \"\n + \"dataField VARCHAR(64), PRIMARY KEY (priKey))\");\n\nstmt.executeUpdate(\"INSERT INTO autoIncTable (dataField) \"\n + \"values ('data field value')\",\n Statement.RETURN_GENERATED_KEYS);\n\nint autoIncKeyFromApi = -1;\n\nrs = stmt.getGeneratedKeys();\n\nif (rs.next()) {\n autoIncKeyFromApi = rs.getInt(1);\n}\nelse {\n // do stuff here \n}\n\nrs.close();\n" }, { "answer_id": 17498058, "author": "Ben", "author_id": 458741, "author_profile": "https://Stackoverflow.com/users/458741", "pm_score": 2, "selected": false, "text": "create table <table_name> ( <column_name> generated as identity );\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40236/" ]
317,002
<p>I have this in my installer and I need to change the name of the ini file.</p> <pre><code>[INI] Filename: {app}\bin\old.ini; Section: Data; Key: key; String: Value; </code></pre> <p>If I just change the filename it will create another ini file and I'll lose the data.</p> <p>Is there some easy way to rename this ini file in the installer?</p>
[ { "answer_id": 331310, "author": "Fabio Gomes", "author_id": 727, "author_profile": "https://Stackoverflow.com/users/727", "pm_score": 2, "selected": true, "text": "procedure CurStepChanged(CurStep: TSetupStep);\nvar\n OldFile: string;\nbegin\n if CurStep = ssInstall then\n begin\n OldFile := ExpandConstant('{app}\\old.ini');\n if FileExists(OldFile) then\n RenameFile(OldFile, ExpandConstant('{app}\\new.ini'));\n end;\nend;\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/727/" ]
317,005
<p>In my routing I would like to have something like not found route handler. </p> <p>For example I have created one mapping like</p> <pre><code>routes.MapRoute( "default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id="" } ); routes.MapRoute( "Catchall", "{*catchall}", new { controller = "Home", action = "Lost" } ); </code></pre> <p>but when user inserts address something like /one/two/three/four/bla/bla it will be cached with the Catchall mapping.</p> <p>But when user inserts something that should match with default mapping, (like /one/two/ ,but this controller or action is not implemented) I would want that Catchall mapping would accept this request, because all other mappings failed. But instead of this I get an error. </p> <p>Should I override some mapping handlers to catch the exception if controller or action getting an exception?</p>
[ { "answer_id": 331310, "author": "Fabio Gomes", "author_id": 727, "author_profile": "https://Stackoverflow.com/users/727", "pm_score": 2, "selected": true, "text": "procedure CurStepChanged(CurStep: TSetupStep);\nvar\n OldFile: string;\nbegin\n if CurStep = ssInstall then\n begin\n OldFile := ExpandConstant('{app}\\old.ini');\n if FileExists(OldFile) then\n RenameFile(OldFile, ExpandConstant('{app}\\new.ini'));\n end;\nend;\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56035/" ]
317,017
<p>How can I validate a SOAP response against an XSD file that defines the response schema. the web service I'm calling has an XMLDocument as input and output, so can't use WSDL for response schema validation.</p>
[ { "answer_id": 29982101, "author": "geek_sandeep", "author_id": 2596815, "author_profile": "https://Stackoverflow.com/users/2596815", "pm_score": 0, "selected": false, "text": "import javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.XMLConstants;\n\n//Read your xsd file and get the conten into a variable like below.\ndef xsdContent = \"Some Schema Standard\";\n\n//Take the response into another variable that you have to validate.\ndef actualXMLResponse = \"Actual XML Response \";\n\n//create a SchemaFactory object\ndef factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\n\n//Create a given schema object with help of factory\ndef schema = factory.newSchema(new StreamSource(new StringReader(xsdContent ));\n\n//Create a validator\ndef validator = schema.newValidator();\n\n//now validate the actual response against the given schema\ntry {\n validator.validate(new StreamSource(new StringReader(actualXMLResponse )));\n\n} catch(Exception e) {\n log.info (e);\n assert false;\n}\n" }, { "answer_id": 64754450, "author": "user12405895", "author_id": 12405895, "author_profile": "https://Stackoverflow.com/users/12405895", "pm_score": -1, "selected": false, "text": "import javax.xml.transform.stream.StreamSource;\nimport javax.xml.validation.SchemaFactory;\nimport javax.xml.XMLConstants;\n\n//Read your xsd file and get the conten into a variable like below.\n// trim - XSD SCHEME no spaces\ndef xsdscheme = context.expand('${Properties-XSD_Scheme_Black_and_White#XSDSchemeWhite}')\ndef xsdscheme2 = xsdscheme.replace(' ', '')\nxsdscheme2 = xsdscheme2.replaceAll(\"[\\n\\r]\", \"\");\nlog.info \"RES2 TRIMED \" + xsdscheme2\ndef xsdContent = xsdscheme2;\n\n//Take the response into another variable that you have to validate.\n\nRes = context.expand('${#TestCase#WhiteListDecoded}');\ndef Res2 = Res.replace(' ', '')\nRes2 = Res2.replaceAll(\"[\\n\\r]\", \"\");\nlog.info \"RES2 TRIMED \" + Res2\ndef actualXMLResponse = Res2\n\n//create a SchemaFactory object\ndef factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);\n\n//Create a given schema object with help of factory\ndef schema = factory.newSchema(new StreamSource(new StringReader(xsdContent ));\n\n//Create a validator\ndef validator = schema.newValidator();\n\n//now validate the actual response against the given schema\ntry {\n validator.validate(new StreamSource(new StringReader(actualXMLResponse )));\n\n} catch(Exception e) {\n log.info (e);\n assert false;\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7722/" ]
317,029
<p>So far i have got the code below which works lovely when trying an update, delete or select statement. However I run into problems when I try to use an insert. If someone could point me in the correct direction i would be grateful.</p> <pre><code>private function escape($value) { if(get_magic_quotes_gpc()) $value = stripslashes($value); return mysql_real_escape_string($value, $this-&gt;dbConn); } /** * Handles connection to the database. * Die functions are used to catch any errors. */ public function connect($dbHost, $dbName, $dbUser, $dbPass) { $this-&gt;dbConn = mysql_connect( $dbHost, $dbUser, $dbPass ) or die(mysql_error()); mysql_select_db($dbName, $this-&gt;dbConn) or die(mysql_error()); } /** * Loads a raw SQL string into the object $dbSql variable */ public function prep($sql) { $this-&gt;dbSql = $sql; } /** * Load bound hooks and values into object variable */ public function bind($hook, $value) { $this-&gt;dbBind[$hook] = $this-&gt;escape($value); } /** * Runs the SQL string in $dbSql object variable */ public function run() { $sql = $this-&gt;dbSql; if(is_array($this-&gt;dbBind)) foreach($this-&gt;dbBind as $hook =&gt; $value) $sql = str_replace($hook, "'" . $value . "'", $sql); $this-&gt;dbQuery = mysql_query($sql) or die(mysql_error()); $this-&gt;dbBind = array(); return $this-&gt;numRows(); } // Load SQL statment into object $MyDB-&gt;prep("INSERT INTO `demo` (`id`, `name`, `score`, `dept`, `date`) VALUES '1','James Kablammo', '1205550', 'Marketing', '$date'"); // Bind a value to our :id hook // Produces: SELECT * FROM demo_table WHERE id = '23' $MyDB-&gt;bind(':id',1); // Run the query $MyDB-&gt;run(); </code></pre>
[ { "answer_id": 317039, "author": "Tim", "author_id": 33914, "author_profile": "https://Stackoverflow.com/users/33914", "pm_score": 1, "selected": false, "text": "$MyDB->prep(\"INSERT INTO `demo` (`id`, `name`, `score`, `dept`, `date`) VALUES ('1','James Kablammo', '1205550', 'Marketing', '$date'\"));\n" }, { "answer_id": 317040, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 3, "selected": true, "text": "VALUES ( a , b , c )\n VALUES a, b , c \n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31677/" ]
317,053
<p>I'm trying to extract the attributes of a anchor tag (<code>&lt;a&gt;</code>). So far I have this expression:</p> <pre><code>(?&lt;name&gt;\b\w+\b)\s*=\s*("(?&lt;value&gt;[^"]*)"|'(?&lt;value&gt;[^']*)'|(?&lt;value&gt;[^"'&lt;&gt; \s]+)\s*)+ </code></pre> <p>which works for strings like</p> <pre><code>&lt;a href="test.html" class="xyz"&gt; </code></pre> <p>and (single quotes)</p> <pre><code>&lt;a href='test.html' class="xyz"&gt; </code></pre> <p>but not for a string without quotes:</p> <pre><code>&lt;a href=test.html class=xyz&gt; </code></pre> <p>How can I modify my regex making it work with attributes without quotes? Or is there a better way to do that?</p> <p><strong>Update:</strong> <em>Thanks for all the good comments and advice so far. There is one thing I didn't mention: I sadly have to patch/modify code not written by me. And there is no time/money to rewrite this stuff from the bottom up.</em></p>
[ { "answer_id": 317069, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 4, "selected": false, "text": "my $foo = Someclass->parse( $xmlstring ); \nmy @links = $foo->getChildrenByTagName(\"a\"); \nmy @srcs = map { $_->getAttribute(\"src\") } @links; \n# @srcs now contains an array of src attributes extracted from the page. \n" }, { "answer_id": 317081, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 8, "selected": true, "text": "regex101.com <a[^>]*?href=([\"\\'])?((?:.(?!\\1|>))*.?)\\1?\n <img src=\"test.png?test=val\" /> (\\w+)=[\"']?((?:.(?![\"']?\\s+(?:\\S+)=|\\s*\\/?[>\"']))+.)[\"']?\n regex101.com (\\S+)=[\"']?((?:.(?![\"']?\\s+(?:\\S+)=|\\s*\\/?[>\"']))+.)[\"']?\n <a href=test.html class=xyz>\n<a href=\"test.html\" class=\"xyz\">\n<a href='test.html' class=\"xyz\">\n<script type=\"text/javascript\" defer async id=\"something\" onload=\"alert('hello');\"></script>\n<img src=\"test.png\">\n<img src=\"a test.png\">\n<img src=test.png />\n<img src=a test.png />\n<img src=test.png >\n<img src=a test.png >\n<img src=test.png alt=crap >\n<img src=a test.png alt=crap >\n <name attribute=value attribute=\"value\" attribute='value'>\n (\\S+)=[\"']?((?:.(?![\"']?\\s+(?:\\S+)=|[>\"']))+.)[\"']?\n <a href=test.html class=xyz>\n<a href=\"test.html\" class=\"xyz\">\n<a href='test.html' class=\"xyz\">\n 'href' => 'test.html'\n'class' => 'xyz'\n <div id=\"1\"> ([^\\r\\n\\t\\f\\v= '\"]+)(?:=([\"'])?((?:.(?!\\2?\\s+(?:\\S+)=|\\2))+.)\\2?)?\n <script type=\"text/javascript\" defer async id=\"something\" onload=\"alert('hello');\"></script>\n 'type' => 'text/javascript'\n'defer' => ''\n'async' => ''\n'id' => 'something'\n'onload' => 'alert(\\'hello\\');'\n" }, { "answer_id": 319378, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 5, "selected": false, "text": "/\n \\G # start where the last match left off\n (?> # begin non-backtracking expression\n .*? # *anything* until...\n <[Aa]\\b # an anchor tag\n )?? # but look ahead to see that the rest of the expression\n # does not match.\n \\s+ # at least one space\n ( \\p{Alpha} # Our first capture, starting with one alpha\n \\p{Alnum}* # followed by any number of alphanumeric characters\n ) # end capture #1\n (?: \\s* = \\s* # a group starting with a '=', possibly surrounded by spaces.\n (?: (['\"]) # capture a single quote character\n (.*?) # anything else\n \\2 # which ever quote character we captured before\n | ( [^>\\s'\"]+ ) # any number of non-( '>', space, quote ) chars\n ) # end group\n )? # attribute value was optional\n/msx;\n . (?:[^<]|<[^!]|<![^-\\[]|<!\\[(?!CDATA)|<!\\[CDATA\\[.*?\\]\\]>|<!--(?:[^-]|-[^-])*-->)\n \\K" }, { "answer_id": 574968, "author": "Gumbo", "author_id": 53114, "author_profile": "https://Stackoverflow.com/users/53114", "pm_score": 4, "selected": false, "text": "(?:(\\b\\w+\\b)\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\"'<>\\s]+)\\s+)+\n (?<name>\\b\\w+\\b)\\s*=\\s*(?<value>\"[^\"]*\"|'[^']*'|[^\"'<>\\s]+)\n bar=' baz='quux foo=\"bar=' baz='quux\"\n" }, { "answer_id": 3303756, "author": "user273314", "author_id": 273314, "author_profile": "https://Stackoverflow.com/users/273314", "pm_score": 2, "selected": false, "text": "'(\\S+)\\s*?=\\s*([\\'\"])(.*?|)\\2\n" }, { "answer_id": 12474741, "author": "Tom Chiverton", "author_id": 466772, "author_profile": "https://Stackoverflow.com/users/466772", "pm_score": -1, "selected": false, "text": "var buttonMatcherRegExp=/<a[\\s\\S]*?>[\\s\\S]*?<\\/a>/;\nhtmlStr=string.match( buttonMatcherRegExp )[0]\n $(htmlStr).attr('style') \n" }, { "answer_id": 13618472, "author": "fedmich", "author_id": 227618, "author_profile": "https://Stackoverflow.com/users/227618", "pm_score": 2, "selected": false, "text": "$pat_attributes = \"(\\S+)=(\\\"|'| |)(.*)(\\\"|'| |>)\"\n <?php\n$pat_attributes = \"(\\S+)=(\\\"|'| |)(.*)(\\\"|'| |>)\"\n\n$code = ' <IMG title=09.jpg alt=09.jpg src=\"http://example.com.jpg?v=185579\" border=0 mce_src=\"example.com.jpg?v=185579\"\n ';\n\npreg_match_all( \"@$pat_attributes@isU\", $code, $ms);\nvar_dump( $ms );\n\n$code = '\n<a href=test.html class=xyz>\n<a href=\"test.html\" class=\"xyz\">\n<a href=\\'test.html\\' class=\"xyz\">\n<img src=\"http://\"/> ';\n\npreg_match_all( \"@$pat_attributes@isU\", $code, $ms);\n\nvar_dump( $ms );\n $keys = $ms[1];\n$values = $ms[2];\n" }, { "answer_id": 28264917, "author": "Taufik Nurrohman", "author_id": 1163000, "author_profile": "https://Stackoverflow.com/users/1163000", "pm_score": 0, "selected": false, "text": "disabled content /*! Based on <https://github.com/mecha-cms/cms/blob/master/system/kernel/converter.php> */\nfunction extract_html_attributes($input) {\n if( ! preg_match('#^(<)([a-z0-9\\-._:]+)((\\s)+(.*?))?((>)([\\s\\S]*?)((<)\\/\\2(>))|(\\s)*\\/?(>))$#im', $input, $matches)) return false;\n $matches[5] = preg_replace('#(^|(\\s)+)([a-z0-9\\-]+)(=)(\")(\")#i', '$1$2$3$4$5<attr:value>$6', $matches[5]);\n $results = array(\n 'element' => $matches[2],\n 'attributes' => null,\n 'content' => isset($matches[8]) && $matches[9] == '</' . $matches[2] . '>' ? $matches[8] : null\n );\n if(preg_match_all('#([a-z0-9\\-]+)((=)(\")(.*?)(\"))?(?:(\\s)|$)#i', $matches[5], $attrs)) {\n $results['attributes'] = array();\n foreach($attrs[1] as $i => $attr) {\n $results['attributes'][$attr] = isset($attrs[5][$i]) && ! empty($attrs[5][$i]) ? ($attrs[5][$i] != '<attr:value>' ? $attrs[5][$i] : \"\") : $attr;\n }\n }\n return $results;\n}\n $test = array(\n '<div class=\"foo\" id=\"bar\" data-test=\"1000\">',\n '<div>',\n '<div class=\"foo\" id=\"bar\" data-test=\"1000\">test content</div>',\n '<div>test content</div>',\n '<div>test content</span>',\n '<div>test content',\n '<div></div>',\n '<div class=\"foo\" id=\"bar\" data-test=\"1000\"/>',\n '<div class=\"foo\" id=\"bar\" data-test=\"1000\" />',\n '< div class=\"foo\" id=\"bar\" data-test=\"1000\" />',\n '<div class id data-test>',\n '<id=\"foo\" data-test=\"1000\">',\n '<id data-test>',\n '<select name=\"foo\" id=\"bar\" empty-value-test=\"\" selected disabled><option value=\"1\">Option 1</option></select>'\n);\n\nforeach($test as $t) {\n var_dump($t, extract_html_attributes($t));\n echo '<hr>';\n}\n" }, { "answer_id": 38305337, "author": "Ivan Chaer", "author_id": 1204332, "author_profile": "https://Stackoverflow.com/users/1204332", "pm_score": 3, "selected": false, "text": "((?:(?!\\s|=).)*)\\s*?=\\s*?[\"']?((?:(?<=\")(?:(?<=\\\\)\"|[^\"])*|(?<=')(?:(?<=\\\\)'|[^'])*)|(?:(?!\"|')(?:(?!\\/>|>|\\s).)+))\n (?:\\<\\!\\-\\-(?:(?!\\-\\-\\>)\\r\\n?|\\n|.)*?-\\-\\>)|(?:<(\\S+)\\s+(?=.*>)|(?<=[=\\s])\\G)(?:((?:(?!\\s|=).)*)\\s*?=\\s*?[\\\"']?((?:(?<=\\\")(?:(?<=\\\\)\\\"|[^\\\"])*|(?<=')(?:(?<=\\\\)'|[^'])*)|(?:(?!\\\"|')(?:(?!\\/>|>|\\s).)+))[\\\"']?\\s*)\n Javascript (\\S+)=[\\'\"]?((?:(?!\\/>|>|\"|\\'|\\s).)+)\n" }, { "answer_id": 40891461, "author": "Roei Sabag", "author_id": 7163302, "author_profile": "https://Stackoverflow.com/users/7163302", "pm_score": 0, "selected": false, "text": "(?<=\\s)[^><:\\s]*=*(?=[>,\\s])\n" }, { "answer_id": 46626231, "author": "Israel Alberto RV", "author_id": 1727383, "author_profile": "https://Stackoverflow.com/users/1727383", "pm_score": 3, "selected": false, "text": "(\\S+)\\s*=\\s*([']|[\"])\\s*([\\W\\w]*?)\\s*\\2\n (\\S+)\\s*=\\s*([']|[\"])([\\W\\w]*?)\\2\n <div title=\"You're\"> <div <span <[^/]+?(?:\\\".*?\\\"|'.*?'|.*?)*?>\n <div title=\"a>b=c<d\" data-type='a>b=c<d'>Hello</div>\n<span style=\"color: >=<red\">Nothing</span>\n# Returns \n# <div title=\"a>b=c<d\" data-type='a>b=c<d'>\n# <span style=\"color: >=<red\">\n <div[^/]+?(?:\\\".*?\\\"|'.*?'|.*?)*?>\n <article title=\"a>b=c<d\" data-type='a>b=c<div '>Hello</article>\n <div '> Match: <div '>\n [^/]+? <div(?:\\\".*?\\\"|'.*?'|.*?)*?>\n <div id=\"a\"> # It returns \"a instead of a\n<div style=\"\"> # It doesn't match instead of return only an empty property\n<div title = \"c\"> # It not recognize the space between the equal (=)\n (\\S+)\\s*=\\s*[\"']?((?:.(?![\"']?\\s+(?:\\S+)=|[>\"']))?[^\"']*)[\"']?\n (\\S+)=[\"']?((?:.(?![\"']?\\s+(?:\\S+)=|[>\"']))+.)[\"']?\n" }, { "answer_id": 56635204, "author": "Dietrich Baumgarten", "author_id": 7453065, "author_profile": "https://Stackoverflow.com/users/7453065", "pm_score": 3, "selected": false, "text": "<tag \n attrnovalue \n attrnoquote=bli \n attrdoublequote=\"blah 'blah'\"\n attrsinglequote='bloob \"bloob\"' >\n attr attr(?=(attr)*\\s*/?\\s*>)\n attr \\s+(\\w+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^><\"'\\s]+)))?\n $1 $2 $3 $4 $2$3$4 \\s+(\\w+)(?:\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)'|([^><\"'\\s]+)))?(?=(?:\\s+\\w+(?:\\s*=\\s*(?:\"[^\"]*\"|'[^']*'|[^><\"'\\s]+))?)*\\s*/?\\s*>)\n" }, { "answer_id": 71684630, "author": "KJ. Estevez", "author_id": 11006140, "author_profile": "https://Stackoverflow.com/users/11006140", "pm_score": 1, "selected": false, "text": "<input autofocus='' disabled /> /(\\w+)=[\"']((?:.(?![\"']\\s+(?:\\S+)=|\\s*\\/[>\"']))+.)[\"']|(\\w+)=[\"'][\"']|(\\w+)/g" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317053", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6461/" ]
317,070
<p>For the purposes of tracking non-HTML documents via google analytics, I need the mentioned algorithm. It should:</p> <ul><li>not hard-code the domain</li> <li>ignore the protocol (i.e. http/https)</li> <li>not worry about the presence/absence of "www" (any absolute links WILL prefix with "www" and all pages WILL be served via "www")</li></ul> <p>This is complicated by the fact that I need to access it via a function called from the IE-only 'attachEvent'.</p> <p><strong>UPDATE</strong> Sorry, I've worded this question <em>really</em> badly. The real problem is getting this to work via an event, since IE has its own made-up world of event handling. Take the following:</p> <pre><code>function add_event(obj) { if (obj.addEventListener) obj.addEventListener('click', track_file, true); else if (obj.attachEvent) obj.attachEvent("on" + 'click', track_file); } function track_file(obj) { } </code></pre> <p>It seems as if the "obj" in track_file is not the same across browsers - how can I refer to what was clicked in IE?</p>
[ { "answer_id": 317157, "author": "annakata", "author_id": 13018, "author_profile": "https://Stackoverflow.com/users/13018", "pm_score": 2, "selected": false, "text": "$('a.external')\n" }, { "answer_id": 317195, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 2, "selected": false, "text": "function bindtolinks() {\n for (var i= document.links.length; i-->0;)\n document.links.onclick= clicklink;\n}\n\nfunction clicklink() {\n if (this.host==window.location.host) {\n dosomething();\n return true; // I'm an internal link. Follow me.\n } else {\n dosomethingelse();\n return false; // I'm an external link. Don't follow, only do something else.\n }\n}\n" }, { "answer_id": 317199, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 1, "selected": false, "text": "function track_file(evt)\n{\n if (evt == undefined)\n {\n evt = window.event; // For IE\n }\n // Use evt\n}\n function CheckTarget(evt)\n{\n if (evt == undefined)\n {\n // For IE\n evt = window.event;\n//~ event.returnValue = false;\n var target = evt.srcElement;\n var console = { log: alert };\n }\n else\n {\n target = evt.target;\n//~ preventDefault();\n }\n alert(target.hostname + \" vs. \" + window.location.hostname);\n var re = /^https?:\\/\\/[\\w.-]*?([\\w-]+\\.[a-z]+)\\/.*$/;\n var strippedURL = window.location.href.match(re);\n if (strippedURL == null)\n {\n // Oops! (?)\n alert(\"Where are we?\");\n return false;\n }\n alert(window.location.href + \" => \" + strippedURL);\n var strippedTarget = target.href.match(re);\n if (strippedTarget == null)\n {\n // Oops! (?)\n alert(\"What is it?\");\n return false;\n }\n alert(target + \" => \" + strippedTarget);\n if (strippedURL[1] == strippedTarget[1])\n {\n//~ window.location.href = target.href; // Go there\n return true; // Accept the jump\n }\n return false;\n}\n" }, { "answer_id": 317207, "author": "Thomas Hansen", "author_id": 29746, "author_profile": "https://Stackoverflow.com/users/29746", "pm_score": -1, "selected": false, "text": "if( someDomElementWhichIsALink.href.indexOf(window.location) != -1 ) {\n // this is targeting your domain\n}\n" }, { "answer_id": 3969894, "author": "Jerod Venema", "author_id": 25330, "author_profile": "https://Stackoverflow.com/users/25330", "pm_score": 0, "selected": false, "text": "if(target.protocol == window.location.protocol && target.host == window.location.host){\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5058/" ]
317,071
<p>I've seen several of answers about using <a href="http://technet.microsoft.com/en-us/sysinternals/bb896655.aspx" rel="noreferrer">Handle</a> or <a href="http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx" rel="noreferrer">Process Monitor</a>, but I would like to be able to find out in my own code (C#) which process is locking a file.</p> <p>I have a nasty feeling that I'm going to have to spelunk around in the win32 API, but if anyone has already done this and can put me on the right track, I'd really appreciate the help.</p> <h2>Update</h2> <h3>Links to similar questions</h3> <ul> <li><a href="https://stackoverflow.com/questions/860656/how-does-one-figure-out-what-process-locked-a-file-using-c">How does one figure out what process locked a file using c#?</a></li> <li><a href="https://stackoverflow.com/questions/241178/command-line-tool-for-finding-out-who-is-locking-a-file">Command line tool</a></li> <li><a href="https://stackoverflow.com/questions/208283/is-it-possible-to-programatically-find-out-what-process-is-locking-a-file-acros">Across a Network</a></li> <li><a href="https://stackoverflow.com/questions/23197/find-out-which-process-has-an-exclusive-lock-on-a-usb-device-handle">Locking a USB device</a></li> <li><a href="https://stackoverflow.com/questions/305843/determining-what-process-has-a-lock-on-a-file">Unit test fails with locked file</a></li> <li><a href="https://stackoverflow.com/questions/1040/how-do-i-delete-a-file-which-is-locked-by-another-process-in-c">deleting locked file</a></li> </ul>
[ { "answer_id": 317104, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 6, "selected": true, "text": "handle.exe" }, { "answer_id": 317209, "author": "Stefan", "author_id": 19307, "author_profile": "https://Stackoverflow.com/users/19307", "pm_score": 3, "selected": false, "text": "using System.Management; \nusing System.IO; \n\nstatic class Module1 \n{ \nstatic internal ArrayList myProcessArray = new ArrayList(); \nprivate static Process myProcess; \n\npublic static void Main() \n{ \n\n string strFile = \"c:\\\\windows\\\\system32\\\\msi.dll\"; \n ArrayList a = getFileProcesses(strFile); \n foreach (Process p in a) { \n Debug.Print(p.ProcessName); \n } \n} \n\n\nprivate static ArrayList getFileProcesses(string strFile) \n{ \n myProcessArray.Clear(); \n Process[] processes = Process.GetProcesses; \n int i = 0; \n for (i = 0; i <= processes.GetUpperBound(0) - 1; i++) { \n myProcess = processes(i); \n if (!myProcess.HasExited) { \n try { \n ProcessModuleCollection modules = myProcess.Modules; \n int j = 0; \n for (j = 0; j <= modules.Count - 1; j++) { \n if ((modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) == 0)) { \n myProcessArray.Add(myProcess); \n break; // TODO: might not be correct. Was : Exit For \n } \n } \n } \n catch (Exception exception) { \n } \n //MsgBox((\"Error : \" & exception.Message)) \n } \n } \n return myProcessArray; \n} \n} \n Imports System.Management\nImports System.IO\n\nModule Module1\nFriend myProcessArray As New ArrayList\nPrivate myProcess As Process\n\nSub Main()\n\n Dim strFile As String = \"c:\\windows\\system32\\msi.dll\"\n Dim a As ArrayList = getFileProcesses(strFile)\n For Each p As Process In a\n Debug.Print(p.ProcessName)\n Next\nEnd Sub\n\n\nPrivate Function getFileProcesses(ByVal strFile As String) As ArrayList\n myProcessArray.Clear()\n Dim processes As Process() = Process.GetProcesses\n Dim i As Integer\n For i = 0 To processes.GetUpperBound(0) - 1\n myProcess = processes(i)\n If Not myProcess.HasExited Then\n Try\n Dim modules As ProcessModuleCollection = myProcess.Modules\n Dim j As Integer\n For j = 0 To modules.Count - 1\n If (modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) = 0) Then\n myProcessArray.Add(myProcess)\n Exit For\n End If\n Next j\n Catch exception As Exception\n 'MsgBox((\"Error : \" & exception.Message))\n End Try\n End If\n Next i\n Return myProcessArray\nEnd Function\nEnd Module\n" }, { "answer_id": 1121236, "author": "user137604", "author_id": 137604, "author_profile": "https://Stackoverflow.com/users/137604", "pm_score": 3, "selected": false, "text": "using System;\nusing System.Collections;\nusing System.Diagnostics;\nusing System.Management;\nusing System.IO;\n\nstatic class Module1\n{\n static internal ArrayList myProcessArray = new ArrayList();\n private static Process myProcess;\n\n public static void Main()\n {\n string strFile = \"c:\\\\windows\\\\system32\\\\msi.dll\";\n ArrayList a = getFileProcesses(strFile);\n foreach (Process p in a)\n {\n Debug.Print(p.ProcessName);\n }\n }\n\n private static ArrayList getFileProcesses(string strFile)\n {\n myProcessArray.Clear();\n Process[] processes = Process.GetProcesses();\n int i = 0;\n for (i = 0; i <= processes.GetUpperBound(0) - 1; i++)\n {\n myProcess = processes[i];\n //if (!myProcess.HasExited) //This will cause an \"Access is denied\" error\n if (myProcess.Threads.Count > 0)\n {\n try\n {\n ProcessModuleCollection modules = myProcess.Modules;\n int j = 0;\n for (j = 0; j <= modules.Count - 1; j++)\n {\n if ((modules[j].FileName.ToLower().CompareTo(strFile.ToLower()) == 0))\n {\n myProcessArray.Add(myProcess);\n break;\n // TODO: might not be correct. Was : Exit For\n }\n }\n }\n catch (Exception exception)\n {\n //MsgBox((\"Error : \" & exception.Message)) \n }\n }\n }\n\n return myProcessArray;\n }\n}\n tasklist /m YourDllName.dll" }, { "answer_id": 1263609, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "string fileName = @\"c:\\aaa.doc\";//Path to locked file\n\nProcess tool = new Process();\ntool.StartInfo.FileName = \"handle.exe\";\ntool.StartInfo.Arguments = fileName+\" /accepteula\";\ntool.StartInfo.UseShellExecute = false;\ntool.StartInfo.RedirectStandardOutput = true;\ntool.Start(); \ntool.WaitForExit();\nstring outputTool = tool.StandardOutput.ReadToEnd();\n\nstring matchPattern = @\"(?<=\\s+pid:\\s+)\\b(\\d+)\\b(?=\\s+)\";\nforeach(Match match in Regex.Matches(outputTool, matchPattern))\n{\n Process.GetProcessById(int.Parse(match.Value)).Kill();\n}\n" }, { "answer_id": 20623311, "author": "Eric J.", "author_id": 141172, "author_profile": "https://Stackoverflow.com/users/141172", "pm_score": 7, "selected": false, "text": "List<Process> using System.Runtime.InteropServices;\nusing System.Diagnostics;\nusing System;\nusing System.Collections.Generic;\n\nstatic public class FileUtil\n{\n [StructLayout(LayoutKind.Sequential)]\n struct RM_UNIQUE_PROCESS\n {\n public int dwProcessId;\n public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;\n }\n\n const int RmRebootReasonNone = 0;\n const int CCH_RM_MAX_APP_NAME = 255;\n const int CCH_RM_MAX_SVC_NAME = 63;\n\n enum RM_APP_TYPE\n {\n RmUnknownApp = 0,\n RmMainWindow = 1,\n RmOtherWindow = 2,\n RmService = 3,\n RmExplorer = 4,\n RmConsole = 5,\n RmCritical = 1000\n }\n\n [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]\n struct RM_PROCESS_INFO\n {\n public RM_UNIQUE_PROCESS Process;\n\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]\n public string strAppName;\n\n [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]\n public string strServiceShortName;\n\n public RM_APP_TYPE ApplicationType;\n public uint AppStatus;\n public uint TSSessionId;\n [MarshalAs(UnmanagedType.Bool)]\n public bool bRestartable;\n }\n\n [DllImport(\"rstrtmgr.dll\", CharSet = CharSet.Unicode)]\n static extern int RmRegisterResources(uint pSessionHandle,\n UInt32 nFiles,\n string[] rgsFilenames,\n UInt32 nApplications,\n [In] RM_UNIQUE_PROCESS[] rgApplications,\n UInt32 nServices,\n string[] rgsServiceNames);\n\n [DllImport(\"rstrtmgr.dll\", CharSet = CharSet.Auto)]\n static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);\n\n [DllImport(\"rstrtmgr.dll\")]\n static extern int RmEndSession(uint pSessionHandle);\n\n [DllImport(\"rstrtmgr.dll\")]\n static extern int RmGetList(uint dwSessionHandle,\n out uint pnProcInfoNeeded,\n ref uint pnProcInfo,\n [In, Out] RM_PROCESS_INFO[] rgAffectedApps,\n ref uint lpdwRebootReasons);\n\n /// <summary>\n /// Find out what process(es) have a lock on the specified file.\n /// </summary>\n /// <param name=\"path\">Path of the file.</param>\n /// <returns>Processes locking the file</returns>\n /// <remarks>See also:\n /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx\n /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)\n /// \n /// </remarks>\n static public List<Process> WhoIsLocking(string path)\n {\n uint handle;\n string key = Guid.NewGuid().ToString();\n List<Process> processes = new List<Process>();\n\n int res = RmStartSession(out handle, 0, key);\n if (res != 0) throw new Exception(\"Could not begin restart session. Unable to determine file locker.\");\n\n try\n {\n const int ERROR_MORE_DATA = 234;\n uint pnProcInfoNeeded = 0,\n pnProcInfo = 0,\n lpdwRebootReasons = RmRebootReasonNone;\n\n string[] resources = new string[] { path }; // Just checking on one resource.\n\n res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);\n\n if (res != 0) throw new Exception(\"Could not register resource.\"); \n\n //Note: there's a race condition here -- the first call to RmGetList() returns\n // the total number of process. However, when we call RmGetList() again to get\n // the actual processes this number may have increased.\n res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);\n\n if (res == ERROR_MORE_DATA)\n {\n // Create an array to store the process results\n RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];\n pnProcInfo = pnProcInfoNeeded;\n\n // Get the list\n res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);\n if (res == 0)\n {\n processes = new List<Process>((int)pnProcInfo);\n\n // Enumerate all of the results and add them to the \n // list to be returned\n for (int i = 0; i < pnProcInfo; i++)\n {\n try\n {\n processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));\n }\n // catch the error -- in case the process is no longer running\n catch (ArgumentException) { }\n }\n }\n else throw new Exception(\"Could not list processes locking resource.\"); \n }\n else if (res != 0) throw new Exception(\"Could not list processes locking resource. Failed to get size of result.\"); \n }\n finally\n {\n RmEndSession(handle);\n }\n\n return processes;\n }\n}\n An operation was unable to read or write to the registry" }, { "answer_id": 38507312, "author": "Gabriele Gindro", "author_id": 6620485, "author_profile": "https://Stackoverflow.com/users/6620485", "pm_score": -1, "selected": false, "text": "public void KillProcessesAssociatedToFile(string file)\n {\n GetProcessesAssociatedToFile(file).ForEach(x =>\n {\n x.Kill();\n x.WaitForExit(10000);\n });\n }\n\n public List<Process> GetProcessesAssociatedToFile(string file)\n {\n return Process.GetProcesses()\n .Where(x => !x.HasExited\n && x.Modules.Cast<ProcessModule>().ToList()\n .Exists(y => y.FileName.ToLowerInvariant() == file.ToLowerInvariant())\n ).ToList();\n }\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7211/" ]
317,087
<p>Does anybody know why</p> <pre><code> vector&lt;int&gt; test(10); int a=0; for_each(test.begin(),test.end(),(_1+=var(a),++var(a))); for_each(test.begin(),test.end(),(cout &lt;&lt; _1 &lt;&lt; " ")); cout &lt;&lt; "\n" </code></pre> <p>Gives : "0 1 2 3 4 5 6 7 8 9"</p> <p>but </p> <pre><code> transform(test.begin(),test.end(),test.begin(), (_1+=var(a),++var(a))); ...(as before) </code></pre> <p>Gives : "1 2 3 4 5 6 7 8 9 10"</p> <p>?</p>
[ { "answer_id": 317100, "author": "Pieter", "author_id": 5822, "author_profile": "https://Stackoverflow.com/users/5822", "pm_score": 4, "selected": true, "text": "_1+=var(a), ++var(a)\n" }, { "answer_id": 317138, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 2, "selected": false, "text": "for_each transform operator +=" }, { "answer_id": 317163, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "int doit(int & elem) {\n elem += a;\n return ++a;\n}\n\nfor each elem : elem = doit(elem);\n void doit(int & elem) {\n elem += a;\n ++a;\n}\n\nfor each elem : doit(elem);\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24508/" ]
317,089
<p>I have a table which consists of 200 Companies Stock prices for 5 years. This is one large table which consists of Company Name, Stock Open, High, Low, Close, Date</p> <p>I am now required to do some processing on the same and also let users [up to 10] access this database to fetch reports on different sets of parameters and queries.</p> <p>Should I use the database as it is or do you have any suggestion to make it more optimized.</p> <p>Thanks.</p>
[ { "answer_id": 317178, "author": "Henrik Gustafsson", "author_id": 2010, "author_profile": "https://Stackoverflow.com/users/2010", "pm_score": 0, "selected": false, "text": "CREATE TABLE company (\n id INTEGER PRIMARY KEY, -- Well, this would be a serial, but that works different in different DBMS\n name VARCHAR(256) UNIQUE\n);\n\nCREATE TABLE price (\n company_id INTEGER REFERENCES company(id) NOT NULL,\n date TIMESTAMP NOT NULL,\n open DECIMAL, -- Just grabbed a type here, probably not right for you.\n high DECIMAL,\n low DECIMAL,\n close DECIMAL,\n\n PRIMARY KEY(company_id, date)\n);\n" }, { "answer_id": 317188, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 1, "selected": false, "text": "make it more optimized" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32289/" ]
317,095
<p>As the question says, how do I add a new option to a DropDownList using jQuery?</p> <p>Thanks</p>
[ { "answer_id": 317101, "author": "cgreeno", "author_id": 6088, "author_profile": "https://Stackoverflow.com/users/6088", "pm_score": 4, "selected": false, "text": "var myOptions = {\n \"Value 1\" : \"Text 1\",\n \"Value 2\" : \"Text 2\",\n \"Value 3\" : \"Text 3\"\n }\n $(\"#myselect2\").addOption(myOptions, false); \n" }, { "answer_id": 317115, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 10, "selected": true, "text": "var myOptions = {\n val1 : 'text1',\n val2 : 'text2'\n};\nvar mySelect = $('#mySelect');\n$.each(myOptions, function(val, text) {\n mySelect.append(\n $('<option></option>').val(val).html(text)\n );\n});\n DocumentFragment document.createElement('option') var myOptions = {\n val1 : 'text1',\n val2 : 'text2'\n};\nvar _select = $('<select>');\n$.each(myOptions, function(val, text) {\n _select.append(\n $('<option></option>').val(val).html(text)\n );\n});\n$('#mySelect').append(_select.html());\n" }, { "answer_id": 2553045, "author": "Phrogz", "author_id": 405017, "author_profile": "https://Stackoverflow.com/users/405017", "pm_score": 7, "selected": false, "text": "var myOptions = {\n val1 : 'text1',\n val2 : 'text2'\n};\n$.each(myOptions, function(val, text) {\n $('#mySelect').append( new Option(text,val) );\n});\n var defaultSelected = false;\n var nowSelected = true;\n $('#mySelect').append( new Option(text,val,defaultSelected,nowSelected) );\n" }, { "answer_id": 3750025, "author": "Jay", "author_id": 452531, "author_profile": "https://Stackoverflow.com/users/452531", "pm_score": 2, "selected": false, "text": "$\"(.ddlClassName\").Html(\"<option selected=\\\"selected\\\" value=\\\"1\\\">1</option><option value=\\\"2\\\">2</option>\")" }, { "answer_id": 5716408, "author": "Sebastian Mach", "author_id": 363299, "author_profile": "https://Stackoverflow.com/users/363299", "pm_score": -1, "selected": false, "text": "function addtoselect(param,value){\n $('#mySelectBox').append('&lt;option value='+value+'&gt;'+param+'&lt;/option&gt;');\n}\n" }, { "answer_id": 7142293, "author": "Marshal", "author_id": 548098, "author_profile": "https://Stackoverflow.com/users/548098", "pm_score": 2, "selected": false, "text": "$.each(myOptions, function(val, text) {\n $(\"#mySelect\").append($(\"&lt;option/&gt;\").attr(\"value\", val).text(text));\n});\n" }, { "answer_id": 8978256, "author": "Har", "author_id": 1071527, "author_profile": "https://Stackoverflow.com/users/1071527", "pm_score": 4, "selected": false, "text": "$('#DropDownQuality').append(\n $('<option></option>').val(data[0].Value).html(data[0].Text)); \n" }, { "answer_id": 26883742, "author": "chopss", "author_id": 3392249, "author_profile": "https://Stackoverflow.com/users/3392249", "pm_score": 0, "selected": false, "text": " this.$('select#myid').append('<option>newvalue</option>');\n" }, { "answer_id": 27030764, "author": "vapcguy", "author_id": 1181535, "author_profile": "https://Stackoverflow.com/users/1181535", "pm_score": 0, "selected": false, "text": "function myAppender(obj, value, text){\n obj.append($('<option></option>').val(value).html(text));\n}\n\n$(document).ready(function() {\n var counter = 0;\n var builder = 0;\n // Get the number of dropdowns\n $('[id*=\"ddlPosition_\"]').each(function() {\n counter++;\n });\n\n // Add the options for each dropdown\n $('[id*=\"ddlPosition_\"]').each(function() {\n var myId = this.id.split('_')[1];\n\n // Add each option in a loop for the specific dropdown we are on\n for (var i=0; i<counter; i++) {\n myAppender($('[id*=\"ddlPosition_'+myId+'\"]'), i, i+1);\n }\n $('[id*=\"ddlPosition_'+myId+'\"]').val(builder);\n builder++;\n });\n});\n this this.Object $.obj .each()" }, { "answer_id": 29967367, "author": "Zakaria", "author_id": 822274, "author_profile": "https://Stackoverflow.com/users/822274", "pm_score": 3, "selected": false, "text": "$(\"#ddlList\").prepend('<option selected=\"selected\" value=\"0\"> Select </option>');\n $('<option value=\"6\">Java Script</option>').appendTo(\"#ddlList\");\n" }, { "answer_id": 60143832, "author": "Du-Lacoste", "author_id": 3600553, "author_profile": "https://Stackoverflow.com/users/3600553", "pm_score": 0, "selected": false, "text": "success: function (successData) {\nvar sizeOfData = successData.length;\nif (sizeOfData == 0) {\n // NO DATA, throw an alert ...\n alert (\"No Data Found\");\n} else {\n $.each(successData, function(val, text) {\n mySelect.append(\n $('<option></option>').val(val).html(text)\n );\n });\n} }\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317095", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27805/" ]
317,114
<p>In my application I have several DataContexts that connects to different databases with different schemas. In a custom user control I display the results of the query and let the user edit them, and when the user edits the data I want to persist the changes to the database. To do that I need a reference to the source DataContext (or at least the source datacontext type) so I can do a <code>DataContext.SubmitChanges();</code></p> <p>Is there any way to determine which DataContext a query comes from? The DataQuery class itself is marked as internal, so I can't access its context property without resorting to ugly reflection hacks, so I'm looking for a cleaner approach. </p> <p>There are (several) ways around this problem, passing along a reference to the source DataContext for instance, but I imagine there must be a simpler way to do this. </p> <p>Edit: The following code works, but it's ugly:</p> <pre><code>FieldInfo contextField = query.GetType().GetField("context", BindingFlags.Instance | BindingFlags.NonPublic); if (query != null) { queryContext = contextField.GetValue(value) as DataContext; } </code></pre>
[ { "answer_id": 986122, "author": "Mark", "author_id": 64084, "author_profile": "https://Stackoverflow.com/users/64084", "pm_score": 2, "selected": false, "text": "Private Const StandardChangeTrackerName As String = \"System.Data.Linq.ChangeTracker+StandardChangeTracker\"\n\nPrivate _context As DataClasses1DataContext\nPublic Property Context() As DataClasses1DataContext\n Get\n Dim hasContext As Boolean = False\n Dim myType As Type = Me.GetType()\n Dim propertyChangingField As FieldInfo = myType.GetField(\"PropertyChangingEvent\", BindingFlags.NonPublic Or BindingFlags.Instance)\n Dim propertyChangingDelegate As PropertyChangingEventHandler = propertyChangingField.GetValue(Me)\n Dim delegateType As Type = Nothing\n\n For Each thisDelegate In propertyChangingDelegate.GetInvocationList()\n delegateType = thisDelegate.Target.GetType()\n If delegateType.FullName.Equals(StandardChangeTrackerName) Then\n propertyChangingDelegate = thisDelegate\n hasContext = True\n Exit For\n End If\n Next\n\n If hasContext Then\n Dim targetField = propertyChangingDelegate.Target\n Dim servicesField As FieldInfo = targetField.GetType().GetField(\"services\", BindingFlags.NonPublic Or BindingFlags.Instance)\n If servicesField IsNot Nothing Then\n\n Dim servicesObject = servicesField.GetValue(targetField)\n\n Dim contextField As FieldInfo = servicesObject.GetType.GetField(\"context\", BindingFlags.NonPublic Or BindingFlags.Instance)\n\n _context = contextField.GetValue(servicesObject)\n\n End If\n End If\n \n Return _context\n End Get\n Set(ByVal value As DataClasses1DataContext)\n\n _context = value\n\n End Set\n\nEnd Property\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30366/" ]
317,127
<p>How to set the CVSROOT environment variable in WinCVS?</p>
[ { "answer_id": 317555, "author": "Oliver Giesen", "author_id": 9784, "author_profile": "https://Stackoverflow.com/users/9784", "pm_score": 4, "selected": true, "text": "CVSROOT -d login init import checkout rtag CVSROOT" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40236/" ]
317,134
<p>There seem to be many options to create an XML document in .NET. What's the best approach?</p>
[ { "answer_id": 317137, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "& <" }, { "answer_id": 317159, "author": "Serge Wautier", "author_id": 12379, "author_profile": "https://Stackoverflow.com/users/12379", "pm_score": 2, "selected": false, "text": "public class Car\n{\n public string Make;\n public string Model;\n}\n\n\npublic class Cars\n{\n [XmlElement(\"Car\")]\n public Car[] cars;\n}\n\n\nclass Program\n{\n public static void Save(Cars cars, string sFilename)\n {\n try\n {\n XmlSerializer ser = new XmlSerializer(cars.GetType());\n FileStream fs = new FileStream(sFilename, FileMode.Create);\n ser.Serialize(fs, cars);\n fs.Close();\n }\n catch (Exception ex)\n { // Failed to save data to disk.\n Debug.WriteLine(string.Format(\"Failed to save contents of {0}: {1}\", sFilename ,ex.Message));\n }\n }\n}\n" }, { "answer_id": 317162, "author": "Dirk Vollmar", "author_id": 40347, "author_profile": "https://Stackoverflow.com/users/40347", "pm_score": 3, "selected": false, "text": "XmlWriter // Create an XmlWriterSettings object with the correct options.\nvar settings = new XmlWriterSettings();\nsettings.Indent = true;\nsettings.IndentChars = (\"\\t\");\nsettings.OmitXmlDeclaration = true;\n\n// Create the XmlWriter object and write some content.\nusing (var writer = XmlWriter.Create(\"data.xml\", settings))\n{\n writer.WriteStartElement(\"book\");\n writer.WriteElementString(\"item\", \"tesing\");\n writer.WriteEndElement();\n writer.Flush();\n}\n" }, { "answer_id": 318205, "author": "Sheraz", "author_id": 40723, "author_profile": "https://Stackoverflow.com/users/40723", "pm_score": 0, "selected": false, "text": " List<string> hierarchyList = new List<string>();\n hierarchyList.Add(\"Book\");\n hierarchyList.Add(\"Product\");\n ConfigurationManager manager = new ConfigurationManager();\n manager.FileName = \"deleteme.xml\";\n\n expression = new ConfigurationManagerExpression(manager);\n expression.AddNode(\"HierarchySet\");\n\n // ROOT_NODE_CONSTANT is the root node of document\n string nodePath = manager.ROOT_NODE_CONSTANT + \"/HierarchySet\";\n\n foreach (string name in hierarchyList)\n {\n expression.UsingNode(nodePath).AddNode(\"HierarchyName\").AssignValue(name);\n }\n\n string panelPrefix = \"PE\";\n string pathWithFileName = \"define your path here\";\n manager.SaveSettings(pathWithFileName );\nLet me know if you need code and I\"ll post it on my blog (which I need to do eventually).\n" }, { "answer_id": 542150, "author": "Alex Angas", "author_id": 6651, "author_profile": "https://Stackoverflow.com/users/6651", "pm_score": 0, "selected": false, "text": "XmlNode carNode = xmlDocument.CreateElement(\"Car\");\nxmlDocument.DocumentElement.AppendChild(carNode);\nXmlNode makeNode = xmlDocument.CreateElement(\"Make\");\ncarNode.AppendChild(makeNode);\n...\n" }, { "answer_id": 542152, "author": "Alex Angas", "author_id": 6651, "author_profile": "https://Stackoverflow.com/users/6651", "pm_score": 0, "selected": false, "text": "string carString =\n \"<Car>\" +\n \" <Make>{0}</Make>\" +\n \" <Model>{1}</Model>\" +\n \"</Car>\";\nXmlDocument carDoc = new XmlDocument();\ncarDoc.LoadXml(String.Format(carString, make, model));\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6651/" ]
317,140
<p>I need to get the image dimensions of a JPEG in C++. I'm looking for either a fairly simple way to do it or a smallish library that provides that functionality. I'm working in C++ on OpenVMS, so any external libraries may have to be adapted to compile on our systems - so please don't post me links to big, closed source libraries!</p> <p>Has anyone come across anything that might do the trick, or understand the JPEG file format (I think I probably mean the JFIF file format here) to tell me how I might go about rolling my own solution?</p>
[ { "answer_id": 317145, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 5, "selected": true, "text": "boost::gil::jpeg_read_dimensions (const char *filename)\n" }, { "answer_id": 2101460, "author": "mloskot", "author_id": 151641, "author_profile": "https://Stackoverflow.com/users/151641", "pm_score": 0, "selected": false, "text": "#include <gdal_priv.h>\n\nGDALAllRegister(); // call ones in your application\n\nGDALDataset* ds = (GDALDataset*)GDALOpen(\"my.jpeg\", GA_ReadOnly);\nint width = ds->GetRasterXSize();\nint height = ds->GetRasterYSize(),\nint nbands = ds->GetRasterCount();\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20972/" ]
317,154
<p>I have a legacy database and I am trying to create a NHibernate DAL. I have a problem with a mapping on Many-To-Many table.</p> <p>The Database tables:</p> <ul> <li><code>studio_Subscribers</code></li> <li><code>studio_Groups</code> (contains a IList of Subscribers)</li> <li><code>studio_Subscribers_Groups</code> - Many-To-Many table with primary keys</li> </ul> <p>The problem is when I create a <code>SubscriberGroup</code> instance and fill it with Subscribers they gets saved to the <code>studio_Subscribers</code> table but not to the Many-To-Many table.</p> <p>I cant figure out whats wrong? </p> <p><code>studio_Subscribers</code> table mapping:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Meridix.Studio.Common" namespace="Meridix.Studio.Common"&gt; &lt;class name="SubscriberItem" table="studio_Subscribers"&gt; &lt;id name="StorageId" column="Id" unsaved-value="0" access="nosetter.camelcase"&gt; &lt;generator class="identity" /&gt; &lt;/id&gt; &lt;property name="Id" column="DomainId" not-null="true" /&gt; &lt;property name="Subscriber" column="Subscriber" not-null="true" length="50" /&gt; &lt;property name="Description" column="Description" not-null="false" length="100" /&gt; &lt;property name="Type" column="Type" not-null="true" length="40" type="Meridix.Studio.Data.Repositories.EnumStringTypes.SubscriberTypeEst, Meridix.Studio.Data.Repositories" /&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre> <p><code>studio_Groups</code> table mapping:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="Meridix.Studio.Common" namespace="Meridix.Studio.Common"&gt; &lt;class name="SubscriberGroup" table="studio_Groups"&gt; &lt;id name="StorageId" column="Id" unsaved-value="0" access="nosetter.camelcase"&gt; &lt;generator class="identity" /&gt; &lt;/id&gt; &lt;property name="Id" column="DomainId" not-null="true" /&gt; &lt;property name="Name" column="Name" not-null="true" length="200" /&gt; &lt;property name="Description" column="Description" not-null="false" length="300" /&gt; &lt;bag name="Subscribers" table="studio_Groups_Subscribers" access="nosetter.camelcase"&gt; &lt;key column="GroupId"&gt;&lt;/key&gt; &lt;many-to-many column="SubscriberId" class="SubscriberItem" /&gt; &lt;/bag&gt; &lt;/class&gt; &lt;/hibernate-mapping&gt; </code></pre>
[ { "answer_id": 317200, "author": "jishi", "author_id": 33663, "author_profile": "https://Stackoverflow.com/users/33663", "pm_score": 2, "selected": false, "text": "<bag name=\"Groups\" table=\"studio_Groups_Subscribers\" access=\"nosetter.camelcase\">\n <key column=\"SubscriberId\"></key>\n <many-to-many column=\"GroupId\" class=\"GroupItem\" />\n</bag>\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317154", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29906/" ]
317,170
<p>I would like to change all the names of the attributes where <code>class="testingCase"</code> throughout all my whole html document.</p> <p>e.g. Change:</p> <pre><code>&lt;a class="testingCase" href="#" title="name of testing case"&gt;Blabla&lt;/a&gt; &lt;a class="testingCase" href="#" title="name of another testing case"&gt;Bloo&lt;/a&gt; </code></pre> <p>To this: </p> <pre><code>&lt;a class="testingCase" href="#" newTitleName="name of testing case"&gt;Blabla&lt;/a&gt;` &lt;a class="testingCase" href="#" newTitleName="name of another testing case"&gt;Bloo&lt;/a&gt;` </code></pre> <p>I was thinking of a find and replace but that seems a lot of code for something so easy. Is there a jQuery function for this or a simple method?</p>
[ { "answer_id": 317179, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 6, "selected": false, "text": "$('a.testingCase[title]').each(function() {\n var $t = $(this);\n $t.attr({\n newTitleName: $t.attr('title')\n })\n .removeAttr('title');\n}); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<a class=\"testingCase\" href=\"#\" title=\"name of testing case\">Blabla</a>\n<a class=\"testingCase\" href=\"#\" title=\"name of another testing case\">Bloo</a> a" }, { "answer_id": 317186, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 3, "selected": false, "text": "<a> /* get all <a> with a \"title\" attribute that are testingCase\nthen apply an anonymous function on each of them */\n\n$('a.testingCase[title]').each(function() { \n\n /* create a jquery object from the <a> DOM object */\n var $a_with_title = $(this); \n\n /* add the new attribute with the title value */\n $a_with_title.attr(\"newTitleName\", $a_with_title.getAttribute('title'));\n\n /* remove the old attribute */\n $a_with_title.removeAttr('title'); \n\n});\n" }, { "answer_id": 16750759, "author": "jfrprr", "author_id": 1402303, "author_profile": "https://Stackoverflow.com/users/1402303", "pm_score": 2, "selected": false, "text": "// Rename an entity attribute\njQuery.fn.renameAttr = function(oldName, newName) {\n var args = arguments[0] || {}; \n var o = $(this[0]) \n\n o\n .attr(\n newName, o.attr(oldName)\n )\n .removeAttr(oldName)\n ;\n};\n" }, { "answer_id": 17749123, "author": "Anthony Graglia", "author_id": 491044, "author_profile": "https://Stackoverflow.com/users/491044", "pm_score": 3, "selected": false, "text": "jQuery.fn.extend({\n  renameAttr: function( name, newName, removeData ) {\n    var val;\n    return this.each(function() {\n      val = jQuery.attr( this, name );\n      jQuery.attr( this, newName, val );\n      jQuery.removeAttr( this, name );\n      // remove original data\n      if (removeData !== false){\n        jQuery.removeData( this, name.replace('data-','') );\n      }\n    });\n  }\n});\n // $(selector).renameAttr(original-attr, new-attr, removeData);\n \n// removeData flag is true by default\n$('#test').renameAttr('data-test', 'data-new' );\n \n// removeData flag set to false will not remove the\n// .data(\"test\") value\n$('#test').renameAttr('data-test', 'data-new', false );\n" }, { "answer_id": 22769883, "author": "chiliNUT", "author_id": 2079345, "author_profile": "https://Stackoverflow.com/users/2079345", "pm_score": 1, "selected": false, "text": "$('selector').replaceWith($('selector')[0].outerHTML.replace(\"oldName=\",\"newName=\"));\n $('selector').replaceWith($('selector')[0].outerHTML.(/prefix\\-/g,\"\"));\n" }, { "answer_id": 49976005, "author": "warch", "author_id": 3742743, "author_profile": "https://Stackoverflow.com/users/3742743", "pm_score": -1, "selected": false, "text": "$('a.testingCase[title]').each(function() {\n var curElem = $(this);\n curElem.attr(\"newTitleName\", curElem.attr('title')).removeAttr('title');\n});\n" }, { "answer_id": 50391645, "author": "Maksoud Rodrigues", "author_id": 5733046, "author_profile": "https://Stackoverflow.com/users/5733046", "pm_score": -1, "selected": false, "text": "$('input[name=\"descricao\"]').attr('name', 'title');\n" }, { "answer_id": 73978200, "author": "Александр Бельчиков", "author_id": 17274704, "author_profile": "https://Stackoverflow.com/users/17274704", "pm_score": 0, "selected": false, "text": "<input class=\"form-control\" type=\"date\" value=\"<?=$arRes[\"FORM\"][\"STAT\"]?>\" name=\"STAT\" <?=($arRes[\"MIN_DATE\"]) ? \"min='\".$arRes[\"MIN_DATE\"].\"'\" : \"\" ?> <?=($arRes[\"MAX_DATE\"]) ? \"max='\".$arRes[\"MAX_DATE\"].\"'\" : \"\" ?>>\n\n$(document).on(\"change\", \"#chek_min_max\", function(event){\n var input_field = $(\"[name=STAT]\");\n if(event.target.checked){\n input_field.attr(\"min\", input_field.attr('data-min')).removeAttr('data-min');\n input_field.attr(\"max\", input_field.attr('data-max')).removeAttr('data-max');\n }\n if(!event.target.checked){\n input_field.attr(\"data-min\", input_field.attr('min')).removeAttr('min');\n input_field.attr(\"data-max\", input_field.attr('max')).removeAttr('max');\n }\n });\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
317,175
<p>On Apache/PHP sites if I want to put a senstive file within my website folders, I put a .htaccess file in that folder so users can't download the sensitive file.</p> <p><strong>Is there a similar practice for IIS/ASP.NET sites</strong>, i.e. if I have a shared hosting account and don't have access to IIS server. Can I do this in web.config for instance?</p> <p>e.g. the ASPNETDB.MDF file that ASP.NET Configuration put in the App_Data directory. I would assume this is protected by default but where can I change the settings for this folder as I could with a .htaccess file?</p>
[ { "answer_id": 317662, "author": "JamesEggers", "author_id": 28540, "author_profile": "https://Stackoverflow.com/users/28540", "pm_score": 4, "selected": true, "text": "<location path=\"Secret\" allowOverride=\"false\">\n <system.web>\n <authorization>\n <deny users=\"*\" />\n </authorization>\n <httpHandlers>\n <remove path=\"*.*\" verb=\"*\"/>\n </httpHandlers>\n </system.web>\n</location>\n" }, { "answer_id": 2212825, "author": "Zhaph - Ben Duguid", "author_id": 33051, "author_profile": "https://Stackoverflow.com/users/33051", "pm_score": 0, "selected": false, "text": "[documentation on Application Folders][1] /app_data" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
317,176
<p>I am looking for any tool which will allow the performance testing/tuning of Sybase nested stored procedures. There are many tools around and of course Sybase's own for performance tuning and testing SQL but none of these can handle nested stored procedures (i.e. a stored proc calling another stored proc). Does anyone have/know of such a tool?</p>
[ { "answer_id": 317662, "author": "JamesEggers", "author_id": 28540, "author_profile": "https://Stackoverflow.com/users/28540", "pm_score": 4, "selected": true, "text": "<location path=\"Secret\" allowOverride=\"false\">\n <system.web>\n <authorization>\n <deny users=\"*\" />\n </authorization>\n <httpHandlers>\n <remove path=\"*.*\" verb=\"*\"/>\n </httpHandlers>\n </system.web>\n</location>\n" }, { "answer_id": 2212825, "author": "Zhaph - Ben Duguid", "author_id": 33051, "author_profile": "https://Stackoverflow.com/users/33051", "pm_score": 0, "selected": false, "text": "[documentation on Application Folders][1] /app_data" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317176", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
317,184
<p>I'd like to know when i should and shouldn't be wrapping things in a USING block.</p> <p>From what I understand, the compiler translates it into a try/finally, where the finally calls Dispose() on the object.</p> <p>I always use a USING around database connections and file access, but its more out of habit rather than a 100% understanding. I know you should explicity (or with a using) Dispose() objects which control resources, to ensure they are released instantly rather than whenever the CLR feels like it, but thats where my understanding breaks down.</p> <p>Are IDisposables not disposed of when they go out of scope?</p> <p>Do I only need to use a USING when my object makes use of Dispose to tidy itself up?</p> <p>Thanks</p> <p>Edit: I know there are a couple of other posts on the USING keyword, but I'm more interested in answers relating the the CLR and exactly whats going on internally</p> <p>Andrew</p>
[ { "answer_id": 317201, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 6, "selected": true, "text": "IDisposable IDisposable Dispose() IDisposable #if DEBUG\n ~Foo() {\n // complain loudly that smoebody forgot to dispose...\n }\n#endif\n Dispose GC.SuppressFinalize" }, { "answer_id": 317240, "author": "babbageclunk", "author_id": 38851, "author_profile": "https://Stackoverflow.com/users/38851", "pm_score": 2, "selected": false, "text": "using" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28543/" ]
317,194
<p>On some websites or forums I usually go to, entries that I havn't read yet are marked as "new". I would like to implement this feature on a website I have developed (with news being posted from time to time) -- php/mySQL. How is this usually done ? Does it require using a cookie remembering the last visit date/time ? Or the last viewed posts/urls ? How can I identify the users ?</p>
[ { "answer_id": 317264, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": 0, "selected": false, "text": "function drawPage\n if (isLoggedIn) \n get dbUser from database\n lastUserDateTime = dbUser.LastCommentTime\n else \n lastUserDateTime = yesterdaye\n end if\n\n for each post\n get date of post \n if post->date < lastUserDateTime mark it as new\n draw the post\n loop\n\n if (isLoggedIn) \n if (lastUserDateTime + 10 mins) < now \n dbUser.LastCommentTime = now\n update dbUser in database\n end if\n end if\nend function\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39474/" ]
317,198
<p>I mainly use the MySQL GUI tools. This allows me to easily see the results in a table as well as to quick edits and bookmark frequently run queries. This suits my needs far better than the command line.</p> <p>I remember when I used to do this on Oracle DBs years ago I could put variables in the query itself, so that when running the query I got prompted for the variable.</p> <p>e.g.</p> <pre><code>select email from users where login = [VAR] </code></pre> <p>And when you run the query the system prompts you for VAR and you can type in <code>john_smith14</code> and it executes the query. This is really useful for adhoc queries which you run a lot.</p> <p>Yes I know using shell scripts and the command line this could be done more easily, but for several reasons aside from this, shell scripts are not a good solution for me.</p>
[ { "answer_id": 317210, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 0, "selected": false, "text": "SET @myVar='john_smith14';\nSELECT email FROM users WHERE login = @myVar;\n" }, { "answer_id": 317226, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 1, "selected": false, "text": "SELECT email FROM users WHERE login = :myTest;" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317198", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11660/" ]
317,225
<pre><code> &lt;form action="/Villa/Add" method="post"&gt; &lt;table&gt; &lt;tr&gt; &lt;td&gt; Name: &lt;/td&gt; &lt;td&gt; &lt;%= Html.TextBox("name") %&gt; &lt;%= Html.ValidationMessage("Name") %&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;/td&gt; &lt;td&gt; &lt;input type="submit" value="Add" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/form&gt; </code></pre> <p>My form is above, how do I retrieve the values in my controller?</p> <p>Thanks a lot in advance! Hard to find the right material because of different Previews of MVC being released and being different.</p>
[ { "answer_id": 317236, "author": "Jeff Sheldon", "author_id": 33910, "author_profile": "https://Stackoverflow.com/users/33910", "pm_score": 3, "selected": false, "text": "public class VillaController : Controller \n{\n public ActionResult Add(string name)\n {\n // Code...\n }\n}\n" }, { "answer_id": 317248, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 5, "selected": true, "text": " public ActionResult Add( string name ) {\n ....\n }\n\n or\n\n public ActionResult Add( FormCollection form ) {\n string name = form[\"Name\"];\n }\n\n or\n\n public ActionResult Add( [Bind(Prefix=\"\")]Villa villa ) {\n villa.Name ...\n }\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29445/" ]
317,259
<p>I am using NetBeans for PHP 6.5.</p> <p>In my code I frequently use the following type of command:</p> <pre><code>if (($row = $db-&gt;get_row($sql))) { return $row-&gt;folder; } else { return FALSE; } </code></pre> <p>Netbeans tells me that I should not be using assignments in the IF statement.</p> <p>Why ?</p>
[ { "answer_id": 317268, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 3, "selected": false, "text": "if(a = b)\n //logic error\n" }, { "answer_id": 317272, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 7, "selected": true, "text": "if (a = 1) { .. }\n if (a == 1) { .. }\n if (1 == a) { .. }\n if (a = 1) { .. }\n" }, { "answer_id": 317275, "author": "Tim", "author_id": 33914, "author_profile": "https://Stackoverflow.com/users/33914", "pm_score": 0, "selected": false, "text": "$counter = 0;\nwhile( $getWhateverDataObj = mysql_fetch_object( $sqlResult )) {\n $getWhateverObj->firstName[$counter] = $getWhateverDataObj->firstName;\n $getWhateverObj->lastName[$counter] = $getWhateverDataObj->lastName;\n $counter++;\n}\n" }, { "answer_id": 317285, "author": "rev", "author_id": 30455, "author_profile": "https://Stackoverflow.com/users/30455", "pm_score": 3, "selected": false, "text": "if ( a=func(x) && b=func(y) )\n{\n // do this\n}\n >0 func(y) if ( a==func(x) && b==func(y) ) ...\n" }, { "answer_id": 1108721, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "$next = mysql_fetch_assoc($result)\ndo{\n...\n...\n...\n\n$next = mysql_fetch_assoc($result) or break;\n}while ($next)\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2725/" ]
317,279
<p>I'm currently having a problem with a ShoppingCart for my customer.</p> <p>He wants to be able to add Text between the CartItems so I was wondering if there is some way to still only have one List.</p> <p>My solution would be to have two lists, one of type IList that gets iterated over when calculating Weight and overall Price of the Cart while having another IList that only exposes the necessary fields for displaying it in the ListView and that is a SuperType of CartItem. (But how do I then access additional fields for the listView, defaulting weight and price to 0 in the Description-Text-Class would break LSP).</p> <p>But having two lists somehow feels a bit odd (and still gives me problems), so I was wondering if I could do some sort of a TypedList where I specify the Type of each item.</p> <p>Any suggestions are welcome, I'm not really happy with both options.</p>
[ { "answer_id": 317293, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 5, "selected": true, "text": " ICartListItem\n List<ICartListItem>\n" }, { "answer_id": 12401533, "author": "Sid", "author_id": 1667881, "author_profile": "https://Stackoverflow.com/users/1667881", "pm_score": 1, "selected": false, "text": "string bool" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21699/" ]
317,281
<p>I have this query in LINQ to Entities.</p> <pre><code> var query = (from s in db.ForumStatsSet where s.LogDate &gt;= date1 &amp;&amp; s.LogDate &lt;= date2 group s by new { s.Topic.topicID, s.Topic.subject, s.Topic.Forum.forumName, s.Topic.datum, s.Topic.Forum.ForumGroup.name, s.Topic.Forum.forumID } into g orderby g.Count() descending select new TopicStatsData { TopicId = g.Key.topicID, Count = g.Count(), Subject = g.Key.subject, ForumGroupName = g.Key.name, ForumName = g.Key.forumName, ForumId = g.Key.forumID }); </code></pre> <p>I know it is kind of an "Evil" query but it is only used in a admin interface. But the SQL it generated is absolutely horrifying. Have a look at this baby.</p> <pre><code> exec sp_executesql N'SELECT TOP (50) [Project6].[C1] AS [C1], [Project6].[TopicId] AS [TopicId], [Project6].[C4] AS [C2], [Project6].[subject] AS [subject], [Project6].[name] AS [name], [Project6].[forumName] AS [forumName], [Project6].[C2] AS [C3] FROM ( SELECT [Project5].[TopicId] AS [TopicId], [Project5].[subject] AS [subject], [Project5].[forumName] AS [forumName], [Project5].[name] AS [name], 1 AS [C1], CAST( [Project5].[forumID] AS int) AS [C2], [Project5].[C1] AS [C3], [Project5].[C2] AS [C4] FROM ( SELECT [Project4].[TopicId] AS [TopicId], [Project4].[forumID] AS [forumID], [Project4].[subject] AS [subject], [Project4].[forumName] AS [forumName], [Project4].[name] AS [name], [Project4].[C1] AS [C1], (SELECT COUNT(cast(1 as bit)) AS [A1] FROM [dbo].[tForumStats] AS [Extent14] LEFT OUTER JOIN [dbo].[tTopic] AS [Extent15] ON [Extent14].[TopicId] = [Extent15].[topicID] LEFT OUTER JOIN [dbo].[tForum] AS [Extent16] ON [Extent15].[forumID] = [Extent16].[forumID] LEFT OUTER JOIN [dbo].[tForum] AS [Extent17] ON [Extent15].[forumID] = [Extent17].[forumID] LEFT OUTER JOIN [dbo].[tForum] AS [Extent18] ON [Extent15].[forumID] = [Extent18].[forumID] LEFT OUTER JOIN [dbo].[tForumGroup] AS [Extent19] ON [Extent18].[forumGroupID] = [Extent19].[forumGroupID] LEFT OUTER JOIN [dbo].[tForum] AS [Extent20] ON [Extent15].[forumID] = [Extent20].[forumID] LEFT OUTER JOIN [dbo].[tForumGroup] AS [Extent21] ON [Extent20].[forumGroupID] = [Extent21].[forumGroupID] WHERE ([Extent14].[LogDate] >= @p__linq__25) AND ([Extent14].[LogDate] = @p__linq__25) AND ([Extent6].[LogDate] = @p__linq__25) AND ([Extent1].[LogDate] </pre> <p>I do not as anyone to explain that query but it would be great to get some tips on how to optimze the query so that it just do a simple regular join. Something like this works as fine if I write the SQL myself.</p> <pre>SELECT COUNT(*) AS NumberOfViews, s.topicid AS topicId, t.subject AS TopicSubject, g.[name] AS ForumGroupName, f.forumName AS ForumName FROM tForumStats s join tTopic t on s.topicid = t.topicid join tForum f on f.forumid = t.forumid JOIN tForumGroup g ON f.forumGroupID = g.forumGroupID WHERE s.[LogDate] between @date1 AND @date2 group by s.topicid, t.subject, f.Forumname, t.Datum, g.[name] order by count(*) desc </code></pre> <p>Btw, i LOVE this site. Amazing design and usability! Hope it works good to get some help to :)</p>
[ { "answer_id": 317307, "author": "Ali Ersöz", "author_id": 4215, "author_profile": "https://Stackoverflow.com/users/4215", "pm_score": 4, "selected": true, "text": "from s in db.ForumStatsSet\njoin t in db.Topics on t.TopicId == s.TopicId\njoin f in db.Forums on f.ForumId == t.ForumId\njoin fg in db.ForumGroups on fg.ForumGroupId == f.ForumGroupId\nwhere s.LogDate >= date1 && s.LogDate <= \ngroup s by new { t.TopicId, t.subject, f.forumName, t.datum, fg.name, f.forumID } into g\norderby g.Count() descending\nselect new TopicStatsData\n{\n TopicId = g.Key.topicID,\n Count = g.Count(),\n Subject = g.Key.subject,\n ForumGroupName = g.Key.name,\n ForumName = g.Key.forumName,\n ForumId = g.Key.forumID\n });\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40609/" ]
317,282
<p>I am trying to build a server control that, depending on a "QuestionTypeId" display either a text box, date picker or Yes-No radio buttons. </p> <p>I have my control displaying how I want it to, but when the submit button is pressed on the form, the text box, date picker or radio buttons that were generated in the RenderContents method are all null.</p> <p>I have attempted to store the generated controls in view state, that stopped them being null, but the user inputs were not being stored.</p> <p>I will post code if it is needed. Just ask.</p>
[ { "answer_id": 317324, "author": "dexter", "author_id": 2703984, "author_profile": "https://Stackoverflow.com/users/2703984", "pm_score": 0, "selected": false, "text": "MyProperty = Request.Form(\"myControl\");\n" }, { "answer_id": 317435, "author": "Yona", "author_id": 40007, "author_profile": "https://Stackoverflow.com/users/40007", "pm_score": 0, "selected": false, "text": "protected void Page_Load(object sender, EventArgs e)\n{\n txtBox.Visible = QuestionTypeID == 1;\n chkBox.Visible = QuestionTypeID == 2;\n}\n protected void Page_Load(object sender, EventArgs e)\n{\n var questionId = ViewState[\"QuestionTypeID\"];\n\n if(questionId == /* Value to create TextBox */) {\n var txt = new TextBox { ID = \"txt\" };\n placeHolder.Controls.Add(txt);\n } else if(questionId == /* Value to create Calender */) {\n var cal = new Calender { ID = \"cal\" };\n placeHolder.Controls.Add(cal);\n }\n\n /* Once the controls are added they will be populated with the posted values */\n}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30357/" ]
317,295
<p>Is there any setting using which the iPhone keyboard won't appear for a particular textbox in web page? May be some css kind of setting?</p>
[ { "answer_id": 317321, "author": "JamesEggers", "author_id": 28540, "author_profile": "https://Stackoverflow.com/users/28540", "pm_score": 2, "selected": false, "text": "navigator.userAgent Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420.1 (KHTML, like Gecko) Version/3.0 Mobile/3B48b Safari/419.3\n" }, { "answer_id": 4844951, "author": "Gustavo Costa De Oliveira", "author_id": 595204, "author_profile": "https://Stackoverflow.com/users/595204", "pm_score": 1, "selected": false, "text": "readonly=\"true\" disabled=\"disabled\"" }, { "answer_id": 22903548, "author": "geoyws", "author_id": 1561922, "author_profile": "https://Stackoverflow.com/users/1561922", "pm_score": 2, "selected": false, "text": "<input type=\"text\" readonly>" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317295", "https://Stackoverflow.com", "https://Stackoverflow.com/users/191/" ]
317,302
<p>Which ftp client or which syntax allows easy chmod for sub-directories?</p>
[ { "answer_id": 317314, "author": "Tim", "author_id": 33914, "author_profile": "https://Stackoverflow.com/users/33914", "pm_score": 0, "selected": false, "text": "chmod -R *\n" }, { "answer_id": 317361, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 0, "selected": false, "text": "chmod" }, { "answer_id": 364899, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "chmod -R chmod ncftp /work1/jleffler/tmp > chmod -R g+x *\nchmod g+x: server said: 'SITE CHMOD -R g+x': command not understood.\nchmod *: server said: 'SITE CHMOD -R xx.pl': command not understood.\nncftp /work1/jleffler/tmp >\n" }, { "answer_id": 17193527, "author": "jfreak53", "author_id": 1585252, "author_profile": "https://Stackoverflow.com/users/1585252", "pm_score": 1, "selected": false, "text": "chmod -R 0755 /www/directory/*\n #!/bin/bash\nlftp <<EOF\nset ftp:ssl-allow no\nset ftp:passive-mode true\nset ftp:list-options -a\nopen -u [user],[password] [host]\nchmod -R 0777 /www/directory/*\nEOF\n" }, { "answer_id": 50323222, "author": "syam", "author_id": 7950519, "author_profile": "https://Stackoverflow.com/users/7950519", "pm_score": 0, "selected": false, "text": "chmod -R 755 {DIR}\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
317,310
<p>I am a bit new to Perl, but here is what I want to do: </p> <pre><code>my @array2d; while(&lt;FILE&gt;){ push(@array2d[$i], $_); } </code></pre> <p>It doesn't compile since <code>@array2d[$i]</code> is not an array but a scalar value.</p> <p>How should I declare @array2d as an array of array?</p> <p>Of course, I have no idea of how many rows I have.</p>
[ { "answer_id": 317330, "author": "gpojd", "author_id": 28071, "author_profile": "https://Stackoverflow.com/users/28071", "pm_score": 6, "selected": true, "text": "my @array = ();\nforeach my $i ( 0 .. 10 ) {\n foreach my $j ( 0 .. 10 ) {\n push @{ $array[$i] }, $j;\n }\n}\n print $array[3][2];\n" }, { "answer_id": 317349, "author": "BrianH", "author_id": 40619, "author_profile": "https://Stackoverflow.com/users/40619", "pm_score": 3, "selected": false, "text": "push(@{$array2d[$i]}, $_);\n" }, { "answer_id": 317398, "author": "Nathan Fellman", "author_id": 1084, "author_profile": "https://Stackoverflow.com/users/1084", "pm_score": 0, "selected": false, "text": "$two_dimensional_array{\"$i $j\"} = $val;\n" }, { "answer_id": 317660, "author": "Axeman", "author_id": 11289, "author_profile": "https://Stackoverflow.com/users/11289", "pm_score": 2, "selected": false, "text": "@{$array2d[$i]} = <FILE>;\n ...\npush @array2d, [ <FILE> ];\n...\n @array2d" }, { "answer_id": 6853654, "author": "slm", "author_id": 33204, "author_profile": "https://Stackoverflow.com/users/33204", "pm_score": 0, "selected": false, "text": "fopen(FILE,\"<somefile.txt\");\n@array = <FILE>;\nclose (FILE);\n" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317310", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38924/" ]
317,311
<p>I have some string s that is locale specific (eg, 0.01 or 0,01). I want to convert this string to a NSDecimalNumber. From the <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfNumberFormatting10_4.html" rel="noreferrer">examples I've seen thus far on the interwebs</a>, this is accomplished by using an NSNumberFormatter a la:</p> <pre><code>NSString *s = @"0.07"; NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; [formatter setFormatterBehavior:NSNumberFormatterBehavior10_4]; [formatter setGeneratesDecimalNumbers:YES]; NSDecimalNumber *decimalNumber = [formatter numberFromString:s]; NSLog([decimalNumber stringValue]); // prints 0.07000000000000001 </code></pre> <p>I'm using 10.4 mode (in addition to being recommended per the documentation, it is also the only mode available on the iPhone) but indicating to the formatter that I want to generate decimal numbers. Note that I've simplified my example (I'm actually dealing with currency strings). However, I'm obviously doing something wrong for it to return a value that illustrates the imprecision of floating point numbers.</p> <p>What is the correct method to convert a locale specific number string to an NSDecimalNumber?</p> <p>Edit: Note that my example is for simplicity. The question I'm asking also should relate to when you need to take a locale specific currency string and convert it to an NSDecimalNumber. Additionally, this can be expanded to a locale specific percentage string and convert it to a NSDecimalNumber.</p>
[ { "answer_id": 317953, "author": "Boaz Stuller", "author_id": 1464654, "author_profile": "https://Stackoverflow.com/users/1464654", "pm_score": 2, "selected": false, "text": "NSString *s = @\"0.07\";\n\nNSScanner* scanner = [NSScanner localizedScannerWithString:s];\nNSDecimal decimal;\n[scanner scanDecimal:&decimal];\nNSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithDecimal:decimal];\n\nNSLog([decimalNumber stringValue]); // prints 0.07\n" }, { "answer_id": 320859, "author": "shek", "author_id": 40618, "author_profile": "https://Stackoverflow.com/users/40618", "pm_score": 5, "selected": true, "text": "NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];\n[formatter setFormatterBehavior:NSNumberFormatterBehavior10_4];\n[formatter setGeneratesDecimalNumbers:TRUE];\n\nNSString *s = @\"0.07\";\n\n// Create your desired rounding behavior that is appropriate for your situation\nNSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:FALSE raiseOnOverflow:TRUE raiseOnUnderflow:TRUE raiseOnDivideByZero:TRUE]; \n\nNSDecimalNumber *decimalNumber = [formatter numberFromString:s];\nNSDecimalNumber *roundedDecimalNumber = [decimalNumber decimalNumberByRoundingAccordingToBehavior:roundingBehavior];\n\nNSLog([decimalNumber stringValue]); // prints 0.07000000000000001\nNSLog([roundedDecimalNumber stringValue]); // prints 0.07\n NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];\n[currencyFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];\n[currencyFormatter setGeneratesDecimalNumbers:TRUE];\n[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];\n\n// Here is the key: use the maximum fractional digits of the currency as the scale\nint currencyScale = [currencyFormatter maximumFractionDigits];\n\nNSDecimalNumberHandler *roundingBehavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:currencyScale raiseOnExactness:FALSE raiseOnOverflow:TRUE raiseOnUnderflow:TRUE raiseOnDivideByZero:TRUE]; \n\n// image s is some locale specific currency string (eg, $0.07 or €0.07)\nNSDecimalNumber *decimalNumber = (NSDecimalNumber*)[currencyFormatter numberFromString:s];\nNSDecimalNumber *roundedDecimalNumber = [decimalNumber decimalNumberByRoundingAccordingToBehavior:roundingBehavior];\n\nNSLog([decimalNumber stringValue]); // prints 0.07000000000000001\nNSLog([roundedDecimalNumber stringValue]); // prints 0.07\n" }, { "answer_id": 6076221, "author": "Ben Mosher", "author_id": 344143, "author_profile": "https://Stackoverflow.com/users/344143", "pm_score": 4, "selected": false, "text": "+(NSDecimalNumber *)decimalNumberWithString:(NSString *)numericString NSDecimalNumber" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317311", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40618/" ]
317,315
<p>In my applications, I often have to use relative paths. For example, when I reference JQuery, I usually do so like this:</p> <pre><code>&lt;script type="text/javascript" src="../Scripts/jquery-1.2.6.js"&gt;&lt;/script&gt; </code></pre> <p>Now that I'm making the transition to MVC, I need to account for the different paths a page might have, relative to the root. This was of course an issue with URL rewriting in the past, but I managed to work around it by using consistent paths.</p> <p>I'm aware that the standard solution is to use absolute paths such as:</p> <pre><code>&lt;script type="text/javascript" src="/Scripts/jquery-1.2.6.js"&gt;&lt;/script&gt; </code></pre> <p>but this will not work for me as during the development cycle, I have to deploy to a test machine on which the app will run in a virtual directory. Root relative paths don't work when the root changes. Also, for maintenance reasons, I cannot simply change out all the paths for the duration of deploying the test - that would be a nightmare in itself.</p> <p>So what's the best solution?</p> <p>Edit:</p> <p>Since this question is still receiving views and answers, I thought it might be prudent to update it to note that as of Razor V2, support for root-relative urls is baked in, so you can use </p> <pre><code>&lt;img src="~/Content/MyImage.jpg"&gt; </code></pre> <p>without any server-side syntax, and the view engine automatically replaces ~/ with whatever the current site root is.</p>
[ { "answer_id": 317333, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 3, "selected": false, "text": "<img src='<%= VirtualPathUtility.ToAbsolute(\"~/images/logo.gif\") %>' alt=\"Our Company Logo\"/>" }, { "answer_id": 317337, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 8, "selected": true, "text": "<script type=\"text/javascript\" src=\"<%=Url.Content(\"~/Scripts/jquery-1.2.6.js\")%>\"></script>\n <%=Html.ScriptInclude(\"~/Content/Script/jquery.1.2.6.js\")%>\n" }, { "answer_id": 317351, "author": "Jesper Palm", "author_id": 36455, "author_profile": "https://Stackoverflow.com/users/36455", "pm_score": 3, "selected": false, "text": "<script src=\"<%=ResolveUrl(\"~/Scripts/jquery-1.2.6.min.js\") %>\" type=\"text/javascript\"></script>\n" }, { "answer_id": 317539, "author": "Chris", "author_id": 34942, "author_profile": "https://Stackoverflow.com/users/34942", "pm_score": 3, "selected": false, "text": "using System;\nusing System.IO;\nusing System.Text;\nusing System.Text.RegularExpressions;\nusing System.Web;\n\nnamespace Demo\n{\n public class PathRewriter : Stream\n {\n Stream filter;\n HttpContext context;\n object writeLock = new object();\n StringBuilder sb = new StringBuilder();\n\n Regex eofTag = new Regex(\"</html>\", RegexOptions.IgnoreCase | RegexOptions.Compiled);\n Regex rootTag = new Regex(\"/_AppRoot_\", RegexOptions.IgnoreCase | RegexOptions.Compiled);\n\n public PathRewriter(Stream filter, HttpContext context)\n {\n this.filter = filter;\n this.context = context;\n }\n\n public override void Write(byte[] buffer, int offset, int count)\n {\n string temp;\n\n lock (writeLock)\n {\n temp = Encoding.UTF8.GetString(buffer, offset, count);\n sb.Append(temp);\n\n if (eofTag.IsMatch(temp))\n RewritePaths();\n }\n }\n\n public void RewritePaths()\n {\n byte[] buffer;\n string temp;\n string root;\n\n temp = sb.ToString();\n root = context.Request.ApplicationPath;\n if (root == \"/\") root = \"\";\n\n temp = rootTag.Replace(temp, root);\n buffer = Encoding.UTF8.GetBytes(temp);\n filter.Write(buffer, 0, buffer.Length);\n }\n\n public override bool CanRead\n {\n get { return true; }\n }\n\n public override bool CanSeek\n {\n get { return filter.CanSeek; }\n }\n\n public override bool CanWrite\n {\n get { return true; }\n }\n\n public override void Flush()\n {\n return;\n }\n\n public override long Length\n {\n get { return Encoding.UTF8.GetBytes(sb.ToString()).Length; }\n }\n\n public override long Position\n {\n get { return filter.Position; }\n set { filter.Position = value; }\n }\n\n public override int Read(byte[] buffer, int offset, int count)\n {\n return filter.Read(buffer, offset, count);\n }\n\n public override long Seek(long offset, SeekOrigin origin)\n {\n return filter.Seek(offset, origin);\n }\n\n public override void SetLength(long value)\n {\n throw new NotImplementedException();\n }\n }\n\n public class PathFilterModule : IHttpModule\n {\n public void Dispose()\n {\n return;\n }\n\n public void Init(HttpApplication context)\n {\n context.ReleaseRequestState += new EventHandler(context_ReleaseRequestState);\n }\n\n void context_ReleaseRequestState(object sender, EventArgs e)\n {\n HttpApplication app = sender as HttpApplication;\n if (app.Response.ContentType == \"text/html\")\n app.Response.Filter = new PathRewriter(app.Response.Filter, app.Context);\n }\n }\n}\n" }, { "answer_id": 1066721, "author": "Aaron", "author_id": 104641, "author_profile": "https://Stackoverflow.com/users/104641", "pm_score": 1, "selected": false, "text": "<script type=\"text/javascript\" src=\"/MyProject/Scripts/jquery-1.2.6.js\"></script>\n" }, { "answer_id": 7507560, "author": "JPC", "author_id": 845878, "author_profile": "https://Stackoverflow.com/users/845878", "pm_score": 2, "selected": false, "text": "<a href=\"@Url.Content(\"~/Home\")\">Application home page</a>\n" }, { "answer_id": 8361489, "author": "James Lawruk", "author_id": 88204, "author_profile": "https://Stackoverflow.com/users/88204", "pm_score": 1, "selected": false, "text": "<a href=@Helper.Root()/about\">About Us</a>\n public static string Root()\n{\n if (HttpContext.Current.Request.Url.Host == \"localhost\")\n {\n return \"\";\n }\n else\n {\n return \"/productionroot\";\n }\n}\n" }, { "answer_id": 12461981, "author": "Charles Burns", "author_id": 161816, "author_profile": "https://Stackoverflow.com/users/161816", "pm_score": 6, "selected": false, "text": "<a href=\"@Url.Content(\"~/Home\")\">Application home page</a>\n <a href=\"~/Home\">Application home page</a>\n" }, { "answer_id": 23302191, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 3, "selected": false, "text": "<A/> <SCRIPT/> <LINK/> <A href=\"~/content/\"/> Global.asax protected void Application_BeginRequest(object sender, EventArgs e)\n {\n Request.ServerVariables.Remove(\"IIS_WasUrlRewritten\");\n }\n Request.ServerVariables IIS_WasUrlRewritten src=\"~/content/...\"" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34942/" ]
317,322
<p>How would you get tree-structured data from a database with the best performance? For example, say you have a folder-hierarchy in a database. Where the folder-database-row has <strong>ID</strong>, <strong>Name</strong> and <strong>ParentID</strong> columns.</p> <p>Would you use a special algorithm to get all the data at once, minimizing the amount of database-calls and process it in code?</p> <p>Or would you use do many calls to the database and sort of get the structure done from the database directly?</p> <p>Maybe there are different answers based on x amount of database-rows, hierarchy-depth or whatever?</p> <p><strong>Edit</strong>: I use Microsoft SQL Server, but answers out of other perspectives are interesting too.</p>
[ { "answer_id": 317346, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 1, "selected": false, "text": "ID ParentID\n1 null\n2 null\n3 1\n4 2\n... ...\n" }, { "answer_id": 317375, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 4, "selected": false, "text": "SELECT * FROM treedata WHERE id LIKE '0101%';\n" }, { "answer_id": 317536, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "tblTreeNode\nTreeID = 1\nTreeNodeID = 100\nParentTreeNodeID = 99\nHierarchy = \".33.59.99.100.\"\n[...] (actual data payload for node)\n SELECT * FROM tblNode WHERE Hierarchy LIKE '%.100.%'\n --Setup the top level if there is any\nUPDATE T \nSET T.TreeNodeHierarchy = '.' + CONVERT(nvarchar(10), T.TreeNodeID) + '.'\nFROM tblTreeNode AS T\n INNER JOIN inserted i ON T.TreeNodeID = i.TreeNodeID\nWHERE (i.ParentTreeNodeID IS NULL) AND (i.TreeNodeHierarchy IS NULL)\n\nWHILE EXISTS (SELECT * FROM tblTreeNode WHERE TreeNodeHierarchy IS NULL)\n BEGIN\n --Update those items that we have enough information to update - parent has text in Hierarchy\n UPDATE CHILD \n SET CHILD.TreeNodeHierarchy = PARENT.TreeNodeHierarchy + CONVERT(nvarchar(10),CHILD.TreeNodeID) + '.'\n FROM tblTreeNode AS CHILD \n INNER JOIN tblTreeNode AS PARENT ON CHILD.ParentTreeNodeID = PARENT.TreeNodeID\n WHERE (CHILD.TreeNodeHierarchy IS NULL) AND (PARENT.TreeNodeHierarchy IS NOT NULL)\n END\n --Only want to do something if Parent IDs were changed\nIF UPDATE(ParentTreeNodeID)\n BEGIN\n --Update the changed items to reflect their new parents\n UPDATE CHILD\n SET CHILD.TreeNodeHierarchy = CASE WHEN PARENT.TreeNodeID IS NULL THEN '.' + CONVERT(nvarchar,CHILD.TreeNodeID) + '.' ELSE PARENT.TreeNodeHierarchy + CONVERT(nvarchar, CHILD.TreeNodeID) + '.' END\n FROM tblTreeNode AS CHILD \n INNER JOIN inserted AS I ON CHILD.TreeNodeID = I.TreeNodeID\n LEFT JOIN tblTreeNode AS PARENT ON CHILD.ParentTreeNodeID = PARENT.TreeNodeID\n\n --Now update any sub items of the changed rows if any exist\n IF EXISTS (\n SELECT * \n FROM tblTreeNode \n INNER JOIN deleted ON tblTreeNode.ParentTreeNodeID = deleted.TreeNodeID\n )\n UPDATE CHILD \n SET CHILD.TreeNodeHierarchy = NEWPARENT.TreeNodeHierarchy + RIGHT(CHILD.TreeNodeHierarchy, LEN(CHILD.TreeNodeHierarchy) - LEN(OLDPARENT.TreeNodeHierarchy))\n FROM tblTreeNode AS CHILD \n INNER JOIN deleted AS OLDPARENT ON CHILD.TreeNodeHierarchy LIKE (OLDPARENT.TreeNodeHierarchy + '%')\n INNER JOIN tblTreeNode AS NEWPARENT ON OLDPARENT.TreeNodeID = NEWPARENT.TreeNodeID\n\n END\n ALTER TABLE [dbo].[tblTreeNode] WITH NOCHECK ADD CONSTRAINT [CK_tblTreeNode_TreeNodeHierarchy] CHECK \n((charindex(('.' + convert(nvarchar(10),[TreeNodeID]) + '.'),[TreeNodeHierarchy],(charindex(('.' + convert(nvarchar(10),[TreeNodeID]) + '.'),[TreeNodeHierarchy]) + 1)) = 0))\n" }, { "answer_id": 36595842, "author": "Tom Gullen", "author_id": 356635, "author_profile": "https://Stackoverflow.com/users/356635", "pm_score": 0, "selected": false, "text": "ID | ParentCommentID\n TopCommentID ID | ParentCommentID | TopCommentID\n TopCommentID ParentCommentID null 0 ParentCommentID TopCommentID" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2429/" ]
317,335
<p>I understand that, if <code>S</code> is a child class of <code>T</code>, then a <code>List&lt;S&gt;</code> is <strong>not</strong> a child of <code>List&lt;T&gt;</code>. Fine. But interfaces have a different paradigm: if <code>Foo</code> implements <code>IFoo</code>, then why is a <code>List&lt;Foo&gt;</code> not (an example of) a <code>List&lt;IFoo&gt;</code>?</p> <p>As there can be no actual class <code>IFoo</code>, does this mean that I would always have to cast each element of the list when exposing a <code>List&lt;IFoo&gt;</code>? Or is this simply bad design and I have to define my own collection class <code>ListOfIFoos</code> to be able to work with them? Neither seem reasonable to me... </p> <p>What would be the best way of exposing such a list, given that I am trying to program to interfaces? I am currently tending towards actually storing my <code>List&lt;Foo&gt;</code> internally as a <code>List&lt;IFoo&gt;</code>.</p>
[ { "answer_id": 317355, "author": "kͩeͣmͮpͥ ͩ", "author_id": 26479, "author_profile": "https://Stackoverflow.com/users/26479", "pm_score": 3, "selected": false, "text": "ConvertAll public List<IFoo> IFoos()\n{\n var x = new List<Foo>(); //Foo implements IFoo\n /* .. */\n return x.ConvertAll<IFoo>(f => f); //thanks Marc\n}\n" }, { "answer_id": 317358, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 3, "selected": false, "text": "function List<IFoo> getList()\n{\n List<IFoo> r = new List<IFoo>();\n for(int i=0;i<100;i++)\n r.Add(new Foo(i+15));\n\n return r;\n}\n" }, { "answer_id": 317379, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 5, "selected": true, "text": "List<Foo> List<IFoo> MyOwnFoo IFoo List<IFoo> List<Foo>" }, { "answer_id": 317405, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 0, "selected": false, "text": "List<Foo> List<IFoo> DateTime IPAddress IFoo IFoo IFoo FooA FooB IFoo Foo IFoo" }, { "answer_id": 317414, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "// Suppose we could do this...\npublic List<IDisposable> GetDisposables()\n{\n return new List<MemoryStream>();\n}\n\n// Then we could do this\nList<IDisposable> disposables = GetDisposables();\ndisposables.Add(new Form());\n" }, { "answer_id": 11313839, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 0, "selected": false, "text": "IList<T> IReadableList<out T> IAppendable<in T> IList<T> IReadableList<T> IAppendable<T> IReadableList<T> IList<T> System.Collections.Generic.List<T> List<T> System.Collections.Generic.List<T>" } ]
2008/11/25
[ "https://Stackoverflow.com/questions/317335", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6091/" ]