qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
239,275
<p>Let's say I have the following table:</p> <pre><code>CustomerID ParentID Name ========== ======== ==== 1 null John 2 1 James 3 2 Jenna 4 3 Jennifer 5 3 Peter 6 5 Alice 7 5 Steve 8 1 Larry </code></pre> <p>I want to retrieve in one query all the descendants of James (Jenna,Jennifer,Peter, Alice, Steve). Thanks, Pablo.</p>
[ { "answer_id": 239283, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 0, "selected": false, "text": "<p>You can't do recursion in SQL without stored procedures. The way to solve this is using Nested Sets, they basically model a tree in SQL as a set.</p>\n\n<p>Notice that this will require a change to the current data model or possibly figuring out how to create a view on the original model.</p>\n\n<p>Postgresql example (using very few postgresql extensions, just SERIAL and ON COMMIT DROP, most RDBMSes will have similar functionality):</p>\n\n<p>Setup:</p>\n\n<pre><code>CREATE TABLE objects(\n id SERIAL PRIMARY KEY,\n name TEXT,\n lft INT,\n rgt INT\n);\n\nINSERT INTO objects(name, lft, rgt) VALUES('The root of the tree', 1, 2);\n</code></pre>\n\n<p>Adding a child:</p>\n\n<pre><code>START TRANSACTION;\n\n-- postgresql doesn't support variables so we create a temporary table that \n-- gets deleted after the transaction has finished.\n\nCREATE TEMP TABLE left_tmp(\n lft INT\n) ON COMMIT DROP; -- not standard sql\n\n-- store the left of the parent for later use\nINSERT INTO left_tmp (lft) VALUES((SELECT lft FROM objects WHERE name = 'The parent of the newly inserted node'));\n\n-- move all the children already in the set to the right\n-- to make room for the new child\nUPDATE objects SET rgt = rgt + 2 WHERE rgt &gt; (SELECT lft FROM left_tmp LIMIT 1);\nUPDATE objects SET lft = lft + 2 WHERE lft &gt; (SELECT lft FROM left_tmp LIMIT 1);\n\n-- insert the new child\nINSERT INTO objects(name, lft, rgt) VALUES(\n 'The name of the newly inserted node', \n (SELECT lft + 1 FROM left_tmp LIMIT 1), \n (SELECT lft + 2 FROM left_tmp LIMIT 1)\n);\n\nCOMMIT;\n</code></pre>\n\n<p>Display a trail from bottom to top:</p>\n\n<pre><code>SELECT\n parent.id, parent.lft\nFROM\n objects AS current_node\nINNER JOIN\n objects AS parent\nON\n current_node.lft BETWEEN parent.lft AND parent.rgt\nWHERE\n current_node.name = 'The name of the deepest child'\nORDER BY\n parent.lft;\n</code></pre>\n\n<p>Display the entire tree:</p>\n\n<pre><code>SELECT\n REPEAT(' ', CAST((COUNT(parent.id) - 1) AS INT)) || '- ' || current_node.name AS indented_name\nFROM\n objects current_node\nINNER JOIN\n objects parent\nON\n current_node.lft BETWEEN parent.lft AND parent.rgt\nGROUP BY\n current_node.name,\n current_node.lft\nORDER BY\n current_node.lft;\n</code></pre>\n\n<p>Select everything down from a certain element of the tree:</p>\n\n<pre><code>SELECT\n current_node.name AS node_name\nFROM\n objects current_node\nINNER JOIN\n objects parent\nON\n current_node.lft BETWEEN parent.lft AND parent.rgt\nAND\n parent.name = 'child'\nGROUP BY\n current_node.name,\n current_node.lft\nORDER BY\n current_node.lft;\n</code></pre>\n" }, { "answer_id": 239303, "author": "mathieu", "author_id": 971, "author_profile": "https://Stackoverflow.com/users/971", "pm_score": 6, "selected": true, "text": "<p>On SQL Server 2005 you can use <a href=\"https://web.archive.org/web/20210927200924/http://www.4guysfromrolla.com/webtech/071906-1.shtml\" rel=\"noreferrer\">CTEs (Common Table Expressions)</a> :</p>\n\n<pre><code>with Hierachy(CustomerID, ParentID, Name, Level)\nas\n(\nselect CustomerID, ParentID, Name, 0 as Level\n from Customers c\n where c.CustomerID = 2 -- insert parameter here\n union all\n select c.CustomerID, c.ParentID, c.Name, ch.Level + 1\n from Customers c\n inner join Hierachy ch\n on c.ParentId = ch.CustomerID\n)\nselect CustomerID, ParentID, Name\nfrom Hierachy\nwhere Level &gt; 0\n</code></pre>\n" }, { "answer_id": 240910, "author": "Kaniu", "author_id": 3236, "author_profile": "https://Stackoverflow.com/users/3236", "pm_score": -1, "selected": false, "text": "<p>Unless I'm missing something, recursion isn't necessary...</p>\n\n<pre><code>SELECT d.NAME FROM Customers As d\nINNER JOIN Customers As p ON p.CustomerID = d.ParentID\nWHERE p.Name = 'James'\n</code></pre>\n" }, { "answer_id": 3793998, "author": "zozzancs", "author_id": 373155, "author_profile": "https://Stackoverflow.com/users/373155", "pm_score": 2, "selected": false, "text": "<p>For bottom up use mathieu's answer with a little modification:</p>\n\n<pre><code>\n\nwith Hierachy(CustomerID, ParentID, Name, Level)\nas\n(\nselect CustomerID, ParentID, Name, 0 as Level\n from Customers c\n where c.CustomerID = 2 -- insert parameter here\n union all\n select c.CustomerID, c.ParentID, c.Name, ch.Level + 1\n from Customers c\n inner join Hierachy ch\n\n -- EDITED HERE --\n on ch.ParentId = c.CustomerID\n ----------------- \n\n)\nselect CustomerID, ParentID, Name\nfrom Hierachy\nwhere Level > 0\n\n\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30729/" ]
Let's say I have the following table: ``` CustomerID ParentID Name ========== ======== ==== 1 null John 2 1 James 3 2 Jenna 4 3 Jennifer 5 3 Peter 6 5 Alice 7 5 Steve 8 1 Larry ``` I want to retrieve in one query all the descendants of James (Jenna,Jennifer,Peter, Alice, Steve). Thanks, Pablo.
On SQL Server 2005 you can use [CTEs (Common Table Expressions)](https://web.archive.org/web/20210927200924/http://www.4guysfromrolla.com/webtech/071906-1.shtml) : ``` with Hierachy(CustomerID, ParentID, Name, Level) as ( select CustomerID, ParentID, Name, 0 as Level from Customers c where c.CustomerID = 2 -- insert parameter here union all select c.CustomerID, c.ParentID, c.Name, ch.Level + 1 from Customers c inner join Hierachy ch on c.ParentId = ch.CustomerID ) select CustomerID, ParentID, Name from Hierachy where Level > 0 ```
239,278
<p>I have database with many tables. In the first table, I have a field called <code>status</code>.</p> <pre><code>table 1 idno name status 111 hjghf yes 225 hjgjj no 345 hgj yes </code></pre> <p>Other tables could have same <code>idno</code> with different fields.</p> <p>I want to check the status for each id no and if it is yes then for that id number in all tables for all null and blank fields I want to update them as 111111.</p> <p>I am looking for a sample vba code for this which I can adapt.</p> <p>Thanks</p>
[ { "answer_id": 241191, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": -1, "selected": true, "text": "<p>Here is some largely untested code. Hopefully it will give you a start.</p>\n\n<pre><code>Sub UpdateNulls()\nDim strSQL As String\nDim rs As DAO.Recordset\nFor Each tdf In CurrentDb.TableDefs\n If Left(tdf.Name, 4) &lt;&gt; \"Msys\" And tdf.Name &lt;&gt; \"Table1\" Then\n strSQL = \"Select * From [\" &amp; tdf.Name &amp; \"] a Inner Join \" _\n &amp; \"Table1 On a.idno = Table1.idno Where Table1.Status = 'Yes'\"\n\n Set rs = CurrentDb.OpenRecordset(strSQL)\n\n Do While Not rs.EOF\n For i = 0 To rs.Fields.Count - 1\n If IsNull(rs.Fields(i)) Then\n rs.Edit\n rs.Fields(i) = 111111\n rs.Update\n End If\n Next\n rs.MoveNext\n Loop\n\n End If\nNext\nEnd Sub\n</code></pre>\n" }, { "answer_id": 241851, "author": "Tom Mayfield", "author_id": 2314, "author_profile": "https://Stackoverflow.com/users/2314", "pm_score": 0, "selected": false, "text": "<p>Multi-table update syntax for MS Access:</p>\n\n<pre><code>UPDATE Table2\nINNER JOIN Table1\n ON Table2.idno = Table1.idno\nSET Table2.salary = 111111\nWHERE Table1.status = 'yes'\nAND Table2.salary Is Null\n</code></pre>\n\n<p>You can go into SQL View for a query, paste this in, and then run the query, or assign it to a string and use CurrentDb.Execute or CurrentProject.Connection.Execute, depending on your DAO/ADO preference.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31132/" ]
I have database with many tables. In the first table, I have a field called `status`. ``` table 1 idno name status 111 hjghf yes 225 hjgjj no 345 hgj yes ``` Other tables could have same `idno` with different fields. I want to check the status for each id no and if it is yes then for that id number in all tables for all null and blank fields I want to update them as 111111. I am looking for a sample vba code for this which I can adapt. Thanks
Here is some largely untested code. Hopefully it will give you a start. ``` Sub UpdateNulls() Dim strSQL As String Dim rs As DAO.Recordset For Each tdf In CurrentDb.TableDefs If Left(tdf.Name, 4) <> "Msys" And tdf.Name <> "Table1" Then strSQL = "Select * From [" & tdf.Name & "] a Inner Join " _ & "Table1 On a.idno = Table1.idno Where Table1.Status = 'Yes'" Set rs = CurrentDb.OpenRecordset(strSQL) Do While Not rs.EOF For i = 0 To rs.Fields.Count - 1 If IsNull(rs.Fields(i)) Then rs.Edit rs.Fields(i) = 111111 rs.Update End If Next rs.MoveNext Loop End If Next End Sub ```
239,301
<p>Is there in Ruby some functionality/syntax to compare two floats with delta? Something similar to <em>assert_in_delta(expected_float, actual_float, delta)</em> from <em>test/unit</em> but returning Boolean?</p>
[ { "answer_id": 239314, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 6, "selected": true, "text": "<pre><code>(expected_float - actual_float).abs &lt;= delta\n</code></pre>\n" }, { "answer_id": 240708, "author": "Gene T", "author_id": 413049, "author_profile": "https://Stackoverflow.com/users/413049", "pm_score": -1, "selected": false, "text": "<p>you may also need a relative tolerance / delta calculation</p>\n\n<p><a href=\"http://realtimecollisiondetection.net/blog/?p=89\" rel=\"nofollow noreferrer\">http://realtimecollisiondetection.net/blog/?p=89</a></p>\n" }, { "answer_id": 31553495, "author": "cvkline", "author_id": 3427338, "author_profile": "https://Stackoverflow.com/users/3427338", "pm_score": 1, "selected": false, "text": "<p>Depending on your application and what your floating point values are actually representing, it might make sense to convert them to Rationals with a given precision. Then direct comparisons will always behave correctly since Rationals are just two integers.</p>\n\n<p>For instance, if you know you're dealing with US currency amounts, storing them as <code>amount.to_r.round(2)</code> allows for exact comparisons for equality.</p>\n\n<p>Just a thought... not all non-integer values need to be inexactly-represented floats</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239301", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31726/" ]
Is there in Ruby some functionality/syntax to compare two floats with delta? Something similar to *assert\_in\_delta(expected\_float, actual\_float, delta)* from *test/unit* but returning Boolean?
``` (expected_float - actual_float).abs <= delta ```
239,302
<p>I usually never see test for new in C++ and I was wondering why.</p> <p><code>Foo *f = new Foo;</code></p> <p><code>// f is assumed as allocated, why usually, nobody test the return of new?</code></p>
[ { "answer_id": 239307, "author": "David Holm", "author_id": 22247, "author_profile": "https://Stackoverflow.com/users/22247", "pm_score": 7, "selected": true, "text": "<p>As per the current standard, <em>new</em> never returns <em>NULL</em>, it throws a std::bad_alloc instead. If you don't want new to throw(as per the old standard) but rather return NULL you should call it by postfixing it with \"<em>(std::nothrow)</em>\".\ni.e.</p>\n\n<pre><code>Foo* foo = new (std::nothrow) Foo;\n</code></pre>\n\n<p>Of course, if you have a very old or possibly broken toolchain it might not follow the standard.</p>\n" }, { "answer_id": 239308, "author": "Windows programmer", "author_id": 23705, "author_profile": "https://Stackoverflow.com/users/23705", "pm_score": 0, "selected": false, "text": "<p>Usually no one tests the return of new in new code because Visual Studio now throws the way the standard says.</p>\n\n<p>In old code if a hack has been done to avoid throwing then you'd still better test.</p>\n" }, { "answer_id": 239310, "author": "Chris Becke", "author_id": 27491, "author_profile": "https://Stackoverflow.com/users/27491", "pm_score": 2, "selected": false, "text": "<p>It all depends which version of C++ the code targets.\nThe c++ specification for a long time now has stated that, by default at least, failures in new will cause a c++ exception, so any code performing a test would be entirely redundant.\nMost programming nowadays also targets virtual memory operating systems where its almost impossible to run out of memory, AND an out-of-memory condition is so fatal anyway that just letting the application crash on the next NULL access is as good a way of any of terminating.</p>\n\n<p>Its only really in embedded programming, where exception handling is deemed to be too much of an overhead, and memory is very limited, that programmers bother to check for new failures.</p>\n" }, { "answer_id": 239311, "author": "Burkhard", "author_id": 12860, "author_profile": "https://Stackoverflow.com/users/12860", "pm_score": 2, "selected": false, "text": "<p>As quoted <a href=\"http://en.wikipedia.org/wiki/Operator_new\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>\"In compilers conforming to the ISO C++ standard, if there is not enough memory for the allocation, the code throws an exception of type std::bad_alloc. All subsequent code is aborted until the error is handled in a try-catch block or the program exits abnormally. The program does not need to check the value of the pointer; if no exception was thrown, the allocation succeeded.\"</p>\n" }, { "answer_id": 239528, "author": "João Augusto", "author_id": 6909, "author_profile": "https://Stackoverflow.com/users/6909", "pm_score": 3, "selected": false, "text": "<p>It all depends on your complier VC++ up to version 6 gives NULL if the new operator fails, on a non MFC application.</p>\n\n<p>Now the problem gets bigger when you use for example STL with VC++ 6, because the STL goes with the standards it will never test for NULL when he needs to get some memory, and guess what will happen under low memory conditions....</p>\n\n<p>So for everybody that still uses VC++ 6 and STL check this article for a Fix.\n<a href=\"http://msdn.microsoft.com/pt-br/magazine/cc164087(en-us).aspx\" rel=\"noreferrer\">Don't Let Memory Allocation Failures Crash Your Legacy STL Application</a></p>\n" }, { "answer_id": 239597, "author": "n-alexander", "author_id": 23420, "author_profile": "https://Stackoverflow.com/users/23420", "pm_score": 3, "selected": false, "text": "<ol>\n<li><p><code>new</code> throws <code>std::bad_alloc</code> by default. If you use default, checking for null is obsolete, but handling exceptions is necessary. This default behavior is consistent with C++ exception safety paradigm - it usually provides that an object is either constructed or not allocated</p></li>\n<li><p>if you override default by using <code>new (std::nothrow)</code>, checking on null is necessary. \"New\" both allocates and commits pages, so it is possible to run out of memory, either because you ran out of page descriptors, or because there's no physical memory available</p></li>\n<li><p>research your OS's memory management. C/C++ reference machine does not know how your OS manages memory, so relying on language alone is not safe. For example of memory allocation gone bad, read on C <code>malloc()</code> + Linux overcommit</p></li>\n</ol>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25888/" ]
I usually never see test for new in C++ and I was wondering why. `Foo *f = new Foo;` `// f is assumed as allocated, why usually, nobody test the return of new?`
As per the current standard, *new* never returns *NULL*, it throws a std::bad\_alloc instead. If you don't want new to throw(as per the old standard) but rather return NULL you should call it by postfixing it with "*(std::nothrow)*". i.e. ``` Foo* foo = new (std::nothrow) Foo; ``` Of course, if you have a very old or possibly broken toolchain it might not follow the standard.
239,340
<p>Does anybody know a way to recursively remove all files in a working copy that are not under version control? (I need this to get more reliable results in my automatic build VMware.)</p>
[ { "answer_id": 239342, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 2, "selected": false, "text": "<p>Can you not just do an export to a new location and build from there?</p>\n" }, { "answer_id": 239351, "author": "Thomas Watnedal", "author_id": 4059, "author_profile": "https://Stackoverflow.com/users/4059", "pm_score": 6, "selected": true, "text": "<p>Edit:</p>\n\n<p>Subversion 1.9.0 introduced an option to do this:</p>\n\n<pre><code>svn cleanup --remove-unversioned\n</code></pre>\n\n<p>Before that, I use this python script to do that:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>import os\nimport re\n\ndef removeall(path):\n if not os.path.isdir(path):\n os.remove(path)\n return\n files=os.listdir(path)\n for x in files:\n fullpath=os.path.join(path, x)\n if os.path.isfile(fullpath):\n os.remove(fullpath)\n elif os.path.isdir(fullpath):\n removeall(fullpath)\n os.rmdir(path)\n\nunversionedRex = re.compile('^ ?[\\?ID] *[1-9 ]*[a-zA-Z]* +(.*)')\nfor l in os.popen('svn status --no-ignore -v').readlines():\n match = unversionedRex.match(l)\n if match: removeall(match.group(1))\n</code></pre>\n\n<p>It seems to do the job pretty well.</p>\n" }, { "answer_id": 239358, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 7, "selected": false, "text": "<p>this works for me in bash:</p>\n\n<pre><code> svn status | egrep '^\\?' | cut -c8- | xargs rm\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/users/50225/seth-reno\">Seth Reno</a>'s is better:</p>\n\n<pre><code>svn status | grep ^\\? | cut -c9- | xargs -d \\\\n rm -r \n</code></pre>\n\n<p>It handles unversioned folders and spaces in filenames</p>\n\n<p>As per comments below, this only works on files that subversion doesn't know about (status=?). Anything that subversion <em>does</em> know about (including Ignored files/folders) will not be deleted.</p>\n\n<p>If you are using subversion 1.9 or greater you can simply use the <a href=\"https://subversion.apache.org/docs/release-notes/1.9.html#svn-cleanup-options\" rel=\"noreferrer\">svn cleanup</a> command with --remove-unversioned and --remove-ignored options</p>\n" }, { "answer_id": 239371, "author": "Stefan Schultze", "author_id": 6358, "author_profile": "https://Stackoverflow.com/users/6358", "pm_score": 2, "selected": false, "text": "<p>My C# conversion of Thomas Watnedals Python script:</p>\n\n<pre><code>Console.WriteLine(\"SVN cleaning directory {0}\", directory);\n\nDirectory.SetCurrentDirectory(directory);\n\nvar psi = new ProcessStartInfo(\"svn.exe\", \"status --non-interactive\");\npsi.UseShellExecute = false;\npsi.RedirectStandardOutput = true;\npsi.WorkingDirectory = directory;\n\nusing (var process = Process.Start(psi))\n{\n string line = process.StandardOutput.ReadLine();\n while (line != null)\n {\n if (line.Length &gt; 7)\n {\n if (line[0] == '?')\n {\n string relativePath = line.Substring(7);\n Console.WriteLine(relativePath);\n\n string path = Path.Combine(directory, relativePath);\n if (Directory.Exists(path))\n {\n Directory.Delete(path, true);\n }\n else if (File.Exists(path))\n {\n File.Delete(path);\n }\n }\n }\n line = process.StandardOutput.ReadLine();\n }\n}\n</code></pre>\n" }, { "answer_id": 781456, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I couldn't get any of the above to work without additional dependencies I didn't want to have to add to my automated build system on win32. So I put together the following Ant commands - note these require the Ant-contrib JAR to be installed in (I was using version 1.0b3, the latest, with Ant 1.7.0).</p>\n\n<p><strong>Note this deletes all unversioned files without warning.</strong></p>\n\n<pre><code> &lt;taskdef resource=\"net/sf/antcontrib/antcontrib.properties\"/&gt;\n &lt;taskdef name=\"for\" classname=\"net.sf.antcontrib.logic.ForTask\" /&gt;\n\n &lt;macrodef name=\"svnExecToProperty\"&gt;\n &lt;attribute name=\"params\" /&gt;\n &lt;attribute name=\"outputProperty\" /&gt;\n &lt;sequential&gt;\n &lt;echo message=\"Executing Subversion command:\" /&gt;\n &lt;echo message=\" svn @{params}\" /&gt;\n &lt;exec executable=\"cmd.exe\" failonerror=\"true\"\n outputproperty=\"@{outputProperty}\"&gt;\n &lt;arg line=\"/c svn @{params}\" /&gt;\n &lt;/exec&gt;\n &lt;/sequential&gt;\n &lt;/macrodef&gt;\n\n &lt;!-- Deletes all unversioned files without warning from the \n basedir and all subfolders --&gt;\n &lt;target name=\"!deleteAllUnversionedFiles\"&gt;\n &lt;svnExecToProperty params=\"status &amp;quot;${basedir}&amp;quot;\" \n outputProperty=\"status\" /&gt;\n &lt;echo message=\"Deleting any unversioned files:\" /&gt;\n &lt;for list=\"${status}\" param=\"p\" delimiter=\"&amp;#x0a;\" trim=\"true\"&gt;\n &lt;sequential&gt;\n &lt;if&gt;\n &lt;matches pattern=\"\\?\\s+.*\" string=\"@{p}\" /&gt;\n &lt;then&gt;\n &lt;propertyregex property=\"f\" override=\"true\" input=\"@{p}\" \n regexp=\"\\?\\s+(.*)\" select=\"\\1\" /&gt;\n &lt;delete file=\"${f}\" failonerror=\"true\" /&gt;\n &lt;/then&gt;\n &lt;/if&gt;\n &lt;/sequential&gt;\n &lt;/for&gt;\n &lt;echo message=\"Done.\" /&gt;\n &lt;/target&gt;\n</code></pre>\n\n<p>For a different folder, change the <code>${basedir}</code> reference.</p>\n" }, { "answer_id": 1064161, "author": "g .", "author_id": 6944, "author_profile": "https://Stackoverflow.com/users/6944", "pm_score": 6, "selected": false, "text": "<p>I ran across this page while looking to do the same thing, though not for an automated build.</p>\n\n<p>After a bit more looking I discovered the '<strong>Extended Context Menu</strong>' in TortoiseSVN. Hold down the shift key and right click on the working copy. There are now additional options under the TortoiseSVN menu including '<strong>Delete unversioned items...</strong>'.</p>\n\n<p>Though perhaps not applicable for this specific question (i.e. within the context of an automated build), I thought it might be helpful for others looking to do the same thing.</p>\n" }, { "answer_id": 1212249, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>For the people that like to do this with perl instead of python, Unix shell, java, etc. Hereby a small perl script that does the jib as well.</p>\n\n<p>Note: This also removes all unversioned directories</p>\n\n<pre><code>#!perl\n\nuse strict;\n\nsub main()\n\n{\n\n my @unversioned_list = `svn status`;\n\n foreach my $line (@unversioned_list)\n\n {\n\n chomp($line);\n\n #print \"STAT: $line\\n\";\n\n if ($line =~/^\\?\\s*(.*)$/)\n\n {\n\n #print \"Must remove $1\\n\";\n\n unlink($1);\n\n rmdir($1);\n\n }\n\n }\n\n}\n\nmain();\n</code></pre>\n" }, { "answer_id": 1502365, "author": "Sukesh Nambiar", "author_id": 182315, "author_profile": "https://Stackoverflow.com/users/182315", "pm_score": 3, "selected": false, "text": "<p>If you are on windows command line, </p>\n\n<pre><code>for /f \"tokens=2*\" %i in ('svn status ^| find \"?\"') do del %i\n</code></pre>\n\n<p>Improved version:</p>\n\n<pre><code>for /f \"usebackq tokens=2*\" %i in (`svn status ^| findstr /r \"^\\?\"`) do svn delete --force \"%i %j\"\n</code></pre>\n\n<p>If you use this in a batch file you need to double the <code>%</code>:</p>\n\n<pre><code>for /f \"usebackq tokens=2*\" %%i in (`svn status ^| findstr /r \"^\\?\"`) do svn delete --force \"%%i %%j\"\n</code></pre>\n" }, { "answer_id": 1789854, "author": "Martin", "author_id": 66981, "author_profile": "https://Stackoverflow.com/users/66981", "pm_score": 4, "selected": false, "text": "<p>See: <a href=\"http://svn.apache.org/repos/asf/subversion/trunk/contrib/client-side/svn-clean\" rel=\"noreferrer\">svn-clean</a></p>\n" }, { "answer_id": 3492878, "author": "rob bentley", "author_id": 194636, "author_profile": "https://Stackoverflow.com/users/194636", "pm_score": 2, "selected": false, "text": "<p>If you are using tortoise svn there is a hidden command to do this. Hold shift whilst right clicking on a folder to launch the context menu in windows explorer. You will get a \"Delete Unversioned Items\" command.</p>\n\n<p>see the bottom of this <a href=\"http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-rename.html\" rel=\"nofollow noreferrer\">page</a> for details, or the screen shot below which highlights the extended features with the green stars, and the one of interest with the yellow rectangle...</p>\n\n<p><a href=\"https://i.stack.imgur.com/wmZJI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wmZJI.png\" alt=\"SVN Extended context menu vs standard menu\"></a></p>\n" }, { "answer_id": 4081803, "author": "dB.", "author_id": 123094, "author_profile": "https://Stackoverflow.com/users/123094", "pm_score": 0, "selected": false, "text": "<p>If you don't want to write any code, svn2.exe from <a href=\"http://svn2svn.codeplex.com/releases/view/46229\" rel=\"nofollow\">svn2svn</a> does this, also there's <a href=\"http://code.dblock.org/ShowPost.aspx?id=133\" rel=\"nofollow\">an article</a> on how it's implemented. Deleted folders and files are put in the recycle bin.</p>\n\n<p>Run \"svn2.exe sync [path]\". </p>\n" }, { "answer_id": 4572157, "author": "Aria", "author_id": 559479, "author_profile": "https://Stackoverflow.com/users/559479", "pm_score": 2, "selected": false, "text": "<pre><code>svn status --no-ignore | awk '/^[I\\?]/ {system(\"echo rm -r \" $2)}'\n</code></pre>\n\n<p>remove the echo if that's sure what you want to do.</p>\n" }, { "answer_id": 5817051, "author": "umpirsky", "author_id": 177056, "author_profile": "https://Stackoverflow.com/users/177056", "pm_score": 0, "selected": false, "text": "<p>Using TortoiseSVN: * right-click on working copy folder, while holding the shift-key down * choose \"delete unversioned items\"</p>\n\n<p><a href=\"https://stackoverflow.com/questions/2803823/how-can-i-delete-all-unversioned-ignored-files-folders-in-my-working-copy\">How can I delete all unversioned/ignored files/folders in my working copy?</a></p>\n" }, { "answer_id": 6112048, "author": "user9876", "author_id": 37386, "author_profile": "https://Stackoverflow.com/users/37386", "pm_score": 3, "selected": false, "text": "<p>Linux command line:</p>\n\n<pre><code>svn status --no-ignore | egrep '^[?I]' | cut -c9- | xargs -d \\\\n rm -r\n</code></pre>\n\n<p>Or, if some of your files are owned by root:</p>\n\n<pre><code>svn status --no-ignore | egrep '^[?I]' | cut -c9- | sudo xargs -d \\\\n rm -r\n</code></pre>\n\n<p>This is based on Ken's answer. (Ken's answer skips ignored files; my answer deletes them).</p>\n" }, { "answer_id": 7251700, "author": "Kyle", "author_id": 3335, "author_profile": "https://Stackoverflow.com/users/3335", "pm_score": 3, "selected": false, "text": "<p>I added this to my windows powershell profile</p>\n\n<pre><code>function svnclean {\n svn status | foreach { if($_.StartsWith(\"?\")) { Remove-Item $_.substring(8) -Verbose } }\n}\n</code></pre>\n" }, { "answer_id": 9916651, "author": "user1299374", "author_id": 1299374, "author_profile": "https://Stackoverflow.com/users/1299374", "pm_score": 1, "selected": false, "text": "<p>Might as well contribute another option</p>\n\n<pre><code>svn status | awk '{if($2 !~ /(config|\\.ini)/ &amp;&amp; !system(\"test -e \\\"\" $2 \"\\\"\")) {print $2; system(\"rm -Rf \\\"\" $2 \"\\\"\");}}'\n</code></pre>\n\n<p>The /(config|.ini)/ is for my own purposes.</p>\n\n<p>And might be a good idea to add --no-ignore to the svn command</p>\n" }, { "answer_id": 10199823, "author": "Eric Cope", "author_id": 256484, "author_profile": "https://Stackoverflow.com/users/256484", "pm_score": 1, "selected": false, "text": "<p>I stumbled on svn-clean on my RH5 machine. Its located at /usr/bin/svn-clean </p>\n\n<p><a href=\"http://svn.apache.org/repos/asf/subversion/trunk/contrib/client-side/svn-clean\" rel=\"nofollow\">http://svn.apache.org/repos/asf/subversion/trunk/contrib/client-side/svn-clean</a></p>\n" }, { "answer_id": 14007301, "author": "Andriy F.", "author_id": 1303422, "author_profile": "https://Stackoverflow.com/users/1303422", "pm_score": 1, "selected": false, "text": "<p>Pure windows cmd/bat solution:</p>\n\n<pre><code>@echo off\n\nsvn cleanup .\nsvn revert -R .\nFor /f \"tokens=1,2\" %%A in ('svn status --no-ignore') Do (\n If [%%A]==[?] ( Call :UniDelete %%B\n ) Else If [%%A]==[I] Call :UniDelete %%B\n )\nsvn update .\ngoto :eof\n\n:UniDelete delete file/dir\nif \"%1\"==\"%~nx0\" goto :eof\nIF EXIST \"%1\\*\" ( \n RD /S /Q \"%1\"\n) Else (\n If EXIST \"%1\" DEL /S /F /Q \"%1\"\n)\ngoto :eof\n</code></pre>\n" }, { "answer_id": 16839566, "author": "josh-cain", "author_id": 564875, "author_profile": "https://Stackoverflow.com/users/564875", "pm_score": 2, "selected": false, "text": "<p>Since everyone else is doing it...</p>\n\n<pre><code>svn status | grep ^? | awk '{print $2}' | sed 's/^/.\\//g' | xargs rm -R\n</code></pre>\n" }, { "answer_id": 17491264, "author": "Konstantin Burlachenko", "author_id": 1154447, "author_profile": "https://Stackoverflow.com/users/1154447", "pm_score": 3, "selected": false, "text": "<p>Just do it on unix-shell with:</p>\n\n<pre><code>rm -rf `svn st . | grep \"^?\" | cut -f2-9 -d' '`\n</code></pre>\n" }, { "answer_id": 17979708, "author": "J. T. Marsh", "author_id": 2076499, "author_profile": "https://Stackoverflow.com/users/2076499", "pm_score": 0, "selected": false, "text": "<p>A clean way to do this in PERL would be:</p>\n\n<pre><code>#!/usr/bin/perl\nuse IO::CaptureOutput 'capture_exec'\n\nmy $command = sprintf (\"svn status --no-ignore | grep '^?' | sed -n 's/^\\?//p'\");\n\nmy ( $stdout, $stderr, $success, $exit_code ) = capture_exec ( $command );\nmy @listOfFiles = split ( ' ', $stdout );\n\nforeach my $file ( @listOfFiles )\n{ # foreach ()\n $command = sprintf (\"rm -rf %s\", $file);\n ( $stdout, $stderr, $success, $exit_code ) = capture_exec ( $command );\n} # foreach ()\n</code></pre>\n" }, { "answer_id": 21441381, "author": "Beetroot Paul", "author_id": 1036577, "author_profile": "https://Stackoverflow.com/users/1036577", "pm_score": 1, "selected": false, "text": "<p>I've tried <a href=\"https://stackoverflow.com/users/50225/seth-reno\">Seth Reno's</a> version from <a href=\"https://stackoverflow.com/questions/239340/automatically-remove-subversion-unversioned-files/239358#239358\">this answer</a> but it didn't worked for me. I've had 8 characters before filename, not 9 used in <code>cut -c9-</code>.</p>\n\n<p>So this is my version with <code>sed</code> instead of <code>cut</code>:</p>\n\n<pre><code>svn status | grep ^\\? | sed -e 's/\\?\\s*//g' | xargs -d \\\\n rm -r\n</code></pre>\n" }, { "answer_id": 22094588, "author": "Ilya Rosman", "author_id": 3364700, "author_profile": "https://Stackoverflow.com/users/3364700", "pm_score": 0, "selected": false, "text": "<p>I used ~3 hours to generate this. It would take 5 mins to do it in Unix.\nThe mains issue were: spaces in names for Win folders, impossibility to edit %%i and problem with defining vars in Win cmd loop.</p>\n\n<pre><code>setlocal enabledelayedexpansion\n\nfor /f \"skip=1 tokens=2* delims==\" %%i in ('svn status --no-ignore --xml ^| findstr /r \"path\"') do (\n@set j=%%i\n@rd /s /q !j:~0,-1!\n)\n</code></pre>\n" }, { "answer_id": 24897622, "author": "maxschlepzig", "author_id": 427158, "author_profile": "https://Stackoverflow.com/users/427158", "pm_score": 2, "selected": false, "text": "<pre><code>svn st --no-ignore | grep '^[?I]' | sed 's/^[?I] *//' | xargs -r -d '\\n' rm -r\n</code></pre>\n\n<p>This is a unix shell command to delete all files not under subversion control.</p>\n\n<p>Notes:</p>\n\n<ul>\n<li>the <code>st</code> in <code>svn st</code> is an build-in alias for <code>status</code>, i.e. the command is equivalent to <code>svn status</code></li>\n<li><code>--no-ignore</code> also includes non-repository files in the status output, otherwise ignores via mechanisms like <code>.cvsignore</code> etc. - since the goal is to have a clean starting point for builds this switch is a must</li>\n<li>the <code>grep</code> filters the output such that only files unknown to subversion are left - the lines beginning with <code>?</code> list files unknown to subversion that would be ignored without the <code>--no-ignore</code> option</li>\n<li>the prefix up to the filename is remove via <code>sed</code></li>\n<li>the <code>xargs</code> command is instructed via <code>-r</code> to not execute <code>rm</code>, when the argument list would be empty</li>\n<li>the <code>-d '\\n'</code> option tells <code>xargs</code> to use a newline as delimiter such the command also works for filenames with spaces</li>\n<li><code>rm -r</code> is used in case complete directories (that are not part of the repository) need to be removed</li>\n</ul>\n" }, { "answer_id": 25355873, "author": "TarmoPikaro", "author_id": 2338477, "author_profile": "https://Stackoverflow.com/users/2338477", "pm_score": 0, "selected": false, "text": "<p>C# code snipet above did not work for me - I have tortoise svn client, and lines are formatted slightly differently. Here is same code snipet as above, only rewritten to function and using regex.</p>\n\n<pre><code> /// &lt;summary&gt;\n /// Cleans up svn folder by removing non committed files and folders.\n /// &lt;/summary&gt;\n void CleanSvnFolder( string folder )\n {\n Directory.SetCurrentDirectory(folder);\n\n var psi = new ProcessStartInfo(\"svn.exe\", \"status --non-interactive\");\n psi.UseShellExecute = false;\n psi.RedirectStandardOutput = true;\n psi.WorkingDirectory = folder;\n psi.CreateNoWindow = true;\n\n using (var process = Process.Start(psi))\n {\n string line = process.StandardOutput.ReadLine();\n while (line != null)\n {\n var m = Regex.Match(line, \"\\\\? +(.*)\");\n\n if( m.Groups.Count &gt;= 2 )\n {\n string relativePath = m.Groups[1].ToString();\n\n string path = Path.Combine(folder, relativePath);\n if (Directory.Exists(path))\n {\n Directory.Delete(path, true);\n }\n else if (File.Exists(path))\n {\n File.Delete(path);\n }\n }\n line = process.StandardOutput.ReadLine();\n }\n }\n } //CleanSvnFolder\n</code></pre>\n" }, { "answer_id": 28358289, "author": "Giscard Biamby", "author_id": 239185, "author_profile": "https://Stackoverflow.com/users/239185", "pm_score": 1, "selected": false, "text": "<p>If you're cool with powershell: </p>\n\n<pre><code>svn status --no-ignore | ?{$_.SubString(0,1).Equals(\"?\")} | foreach { remove-item -Path (join-Path .\\ $_.Replace(\"?\",\"\").Trim()) -WhatIf }\n</code></pre>\n\n<p>Take out the -WhatIf flag to make the command actually perform the deletes. Otherwise it will just output what it <em>would</em> do if run without the -WhatIf.</p>\n" }, { "answer_id": 31375023, "author": "zhoufei", "author_id": 599532, "author_profile": "https://Stackoverflow.com/users/599532", "pm_score": 0, "selected": false, "text": "<p>For People on windows who wants to avoid using any tool except the standart MS-Dos commands here a solution :</p>\n\n<p>FOR /F \"tokens=1* delims= \" %G IN ('svn st ^| findstr \"^?\"') DO rd /s /q \"%H\"</p>\n\n<p>FOR /F \"tokens=1* delims= \" %G IN ('svn st ^| findstr \"^?\"') DO del /s /f /q \"%H\"</p>\n\n<ul>\n<li>svn st will display the status of each files and folder in the working copy</li>\n<li>findstr will look for each line starting with '?', which mean the file/folder is unversioned</li>\n<li>FOR will use as delimiters and take the tokens after the 1st one (the 1st one is %G, the rest is %H)\nThis way we are exctracting the file/folder from the svn st command output.</li>\n<li>rd will delete folders, del will delete files.</li>\n</ul>\n" }, { "answer_id": 39499969, "author": "stevek_mcc", "author_id": 1166064, "author_profile": "https://Stackoverflow.com/users/1166064", "pm_score": 2, "selected": false, "text": "<p>If you have <a href=\"http://tortoisesvn.net/\" rel=\"nofollow\">TortoiseSVN</a> on your path and you are in the right directory:</p>\n\n<pre><code>TortoiseProc.exe /command:cleanup /path:\"%CD%\" /delunversioned /delignored /nodlg /noui\n</code></pre>\n\n<p>The options are described in the TortoiseSVN help for <code>/command:cleanup</code>:</p>\n\n<blockquote>\n <p>Use /noui to prevent the result dialog from popping up\n either telling about the cleanup being finished or showing an error\n message). /noprogressui also disables the progress dialog. /nodlg\n disables showing the cleanup dialog where the user can choose what\n exactly should be done in the cleanup. The available actions can be\n specified with the options /cleanup for status cleanup, /revert,\n /delunversioned, /delignored, /refreshshell and /externals.</p>\n</blockquote>\n" }, { "answer_id": 44199140, "author": "Michael Firth", "author_id": 4523777, "author_profile": "https://Stackoverflow.com/users/4523777", "pm_score": 1, "selected": false, "text": "<p>I would add this as a comment to <a href=\"https://stackoverflow.com/a/239351/4523777\">Thomas Watnedal's answer </a>, but can't yet.</p>\n\n<p>A minor issue with it (which won't affect Windows) is that it only checks for files or directories. For Unix like systems where symbolic links may be present, it is necessary to change the line:</p>\n\n<pre><code>if os.path.isfile(fullpath):\n</code></pre>\n\n<p>to</p>\n\n<pre><code>if os.path.isfile(fullpath) or os.path.islink(fullpath):\n</code></pre>\n\n<p>to also remove links.</p>\n\n<p>For me, changing the last line <code>if match: removeall(match.group(1))</code> into</p>\n\n<pre><code> if match:\n print \"Removing \" + match.group(1)\n removeall(match.group(1))\n</code></pre>\n\n<p>so that it displays what it is removing was useful too.</p>\n\n<p>Depending on the use case, the <code>?[\\?ID]</code> part of the regular expression may be better as <code>?[\\?I]</code>, as the <code>D</code> also removes deleted files, which were under version control. I want to use this to build in a clean, checked in folder, so there should be no files in a <code>D</code> state.</p>\n" }, { "answer_id": 48266625, "author": "chataros", "author_id": 457250, "author_profile": "https://Stackoverflow.com/users/457250", "pm_score": 0, "selected": false, "text": "<p>I also found and used the following:\nsvn status --no-ignore| awk '/^?/ {print $2}'| xargs rm</p>\n" }, { "answer_id": 51749858, "author": "Nikola", "author_id": 9835141, "author_profile": "https://Stackoverflow.com/users/9835141", "pm_score": 1, "selected": false, "text": "<p>@zhoufei I tested your answer and here is updated version:</p>\n\n<pre><code>FOR /F \"tokens=1* delims= \" %%G IN ('svn st %~1 ^| findstr \"^?\"') DO del /s /f /q \"%%H\"\nFOR /F \"tokens=1* delims= \" %%G IN ('svn st %~1 ^| findstr \"^?\"') DO rd /s /q \"%%H\"\n</code></pre>\n\n<ul>\n<li>You must use two <code>%</code> marks in front of G and H</li>\n<li>Switch the order: first remove all files, then remove all directories</li>\n<li>(optional:) In place of <code>%~1</code> can be used any directory name, I used this as a function in a bat file, so <code>%~1</code> is first input paramter</li>\n</ul>\n" }, { "answer_id": 51802658, "author": "Ivan Zhakov", "author_id": 89432, "author_profile": "https://Stackoverflow.com/users/89432", "pm_score": 3, "selected": false, "text": "<p>Subversion 1.9.0 introduced option to remove unversioned items [1]</p>\n\n<pre><code>svn cleanup --remove-unversioned\n</code></pre>\n\n<p>[1] <a href=\"https://subversion.apache.org/docs/release-notes/1.9.html#svn-cleanup-options\" rel=\"noreferrer\">https://subversion.apache.org/docs/release-notes/1.9.html#svn-cleanup-options</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6358/" ]
Does anybody know a way to recursively remove all files in a working copy that are not under version control? (I need this to get more reliable results in my automatic build VMware.)
Edit: Subversion 1.9.0 introduced an option to do this: ``` svn cleanup --remove-unversioned ``` Before that, I use this python script to do that: ```py import os import re def removeall(path): if not os.path.isdir(path): os.remove(path) return files=os.listdir(path) for x in files: fullpath=os.path.join(path, x) if os.path.isfile(fullpath): os.remove(fullpath) elif os.path.isdir(fullpath): removeall(fullpath) os.rmdir(path) unversionedRex = re.compile('^ ?[\?ID] *[1-9 ]*[a-zA-Z]* +(.*)') for l in os.popen('svn status --no-ignore -v').readlines(): match = unversionedRex.match(l) if match: removeall(match.group(1)) ``` It seems to do the job pretty well.
239,344
<p>I want your suggestion on the following pseudo-code. Please suggest how could I improve it, whether or not I could use some design patterns.</p> <pre><code> // i'm receiving a string containing : id operation arguments data = read(socket); tokens = tokenize(data," "); // tokenize the string based on spaces if(tokens[0] == "A") { if(tokens[1] == "some_operation") { // here goes code for some_operation , will use the remaining tokens as arguments for function calls } else if(tokens[1] == "some_other_operation") { // here goes code for some_other_operation , will use the remaining tokens } ... else { // unknown operation } } else if(tokens[0] == "B") { if(tokens[1] == "some_operation_for_B") { // do some operation for B } else if(tokens[1] == "yet_another_operation") { // do yet_another_operation for B } ... else { // unknown operation } } </code></pre> <p>I hope you get the point . The thing is I have a large number of <strong>id's</strong> and each has it's own <strong>operations</strong> , and I think it's kinda ugly to have 10 screens of code containing a lot of <strong>if's</strong> and <strong>else if's</strong>.</p>
[ { "answer_id": 239348, "author": "Epaga", "author_id": 6583, "author_profile": "https://Stackoverflow.com/users/6583", "pm_score": 5, "selected": true, "text": "<p>Have a class for each ID which implements a common interface. Basically the <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"noreferrer\">Strategy pattern</a> IIRC.</p>\n\n<p>So you'd call (pseudo)code like:</p>\n\n<p><code>StrategyFactory.GetStrategy(tokens[0]).parse(tokens[1..n])</code></p>\n" }, { "answer_id": 239356, "author": "Dave Van den Eynde", "author_id": 455874, "author_profile": "https://Stackoverflow.com/users/455874", "pm_score": 2, "selected": false, "text": "<p>You want to split this up into multiple functions, one for each ID, and one for each operation.</p>\n\n<p>A guideline I normally use is a screen height. If I can't have a function in full fit on my screen I start thinking about splitting things up. That way you don't need to scroll just to see where the function is going. As I said, it's a guideline, not a rule, but I find it more practical to be in control of the structure.</p>\n\n<p>If you then want to take an OO approach and turn this into a bunch of classes, you're welcome to do so if you see an advantage. Be mindful of all the plumbing that goes with it, though. You might want to keep it simple.</p>\n\n<p>Dave</p>\n" }, { "answer_id": 239360, "author": "Cheery", "author_id": 21711, "author_profile": "https://Stackoverflow.com/users/21711", "pm_score": 1, "selected": false, "text": "<p>Create a map of functions. Then you'd have code like:</p>\n\n<pre><code>consumed_count = token_mapper[tokens[0]](tokens)\nremove amount of consumed tokens according to the return value and repeat.\n</code></pre>\n\n<p>Though, I don't understand your approach anyway, You are going to write a language that's hard to handle and inflexible. Think about it: A small difference in the amount of arguments causes real havoc in that language. Therefore you are always limited to 1-3 arguments per command.</p>\n\n<p>I'd rather just use some lexer/parser generator combination, but if you want to do what you are going to do, I'd propose you at least split first with newline, then with space, and have therefore clear way to see whether it was meant to give 2 or 3 arguments.</p>\n\n<p>It's important even if your language would be machine-generated, what if your generator ends up having a bug? Fail early, fail often.</p>\n" }, { "answer_id": 239369, "author": "foraidt", "author_id": 27596, "author_profile": "https://Stackoverflow.com/users/27596", "pm_score": 2, "selected": false, "text": "<p>You could have a look into \"Table Driven Methods\" (as described in \"Code Complete\", 2nd edition, chapter 18).\nI think this is <a href=\"https://stackoverflow.com/questions/239344/how-could-i-improve-this-code-c#239360\">what Cheery describes.</a>\nA benefit of that is easy extensibility. You just have to add some entries to the table. This table could be hard coded or even loaded at run-time.</p>\n\n<p>Similar to <a href=\"https://stackoverflow.com/questions/239344/how-could-i-improve-this-code-c#239348\">Epaga's suggestion</a> you coul also try to solve this via polymorphism, having specialized classes perform actions for the different cases. The drawback here is that you have to write new classes in case of changes.</p>\n" }, { "answer_id": 239376, "author": "Keith Nicholas", "author_id": 10431, "author_profile": "https://Stackoverflow.com/users/10431", "pm_score": 1, "selected": false, "text": "<p>you could use the command pattern...... each of your actions would know its id and operation and add itself to to a list at run time...then you'd simply look up the right command, pass it whatever context it needs and it will execute the operation.</p>\n" }, { "answer_id": 239378, "author": "c0m4", "author_id": 2079, "author_profile": "https://Stackoverflow.com/users/2079", "pm_score": 1, "selected": false, "text": "<p>The table driven aproach seems to fit this, like mxp said. If you have diffrent number of parameters for your functions you could have a column in the table that specifies the number of parameters for the function on the same row.</p>\n" }, { "answer_id": 239574, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 3, "selected": false, "text": "<p>First write down the syntax of what you support, then write the code to support it.</p>\n\n<p>Using BNF notation is great for that. And using the Spirit library for the code-part is quite straightforward.</p>\n\n<pre><code>Command := ACommand | BCommand\n\nACommand := 'A' AOperation\nAOperation := 'some_operation' | 'some_other_operation'\n\nBCommand := 'B' BOperation\nBOperation := 'some_operation_for_B' | 'some_other_operation_for_B'\n</code></pre>\n\n<p>This easily translates into a Spirit parser. Every production rule would become a one-liner, every end-symbol would be translated into a function.</p>\n\n<pre><code>#include \"stdafx.h\"\n#include &lt;boost/spirit/core.hpp&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n\nusing namespace std;\nusing namespace boost::spirit;\n\nnamespace {\n void AOperation(char const*, char const*) { cout &lt;&lt; \"AOperation\\n\"; }\n void AOtherOperation(char const*, char const*) { cout &lt;&lt; \"AOtherOperation\\n\"; }\n\n void BOperation(char const*, char const*) { cout &lt;&lt; \"BOperation\\n\"; }\n void BOtherOperation(char const*, char const*) { cout &lt;&lt; \"BOtherOperation\\n\"; }\n}\n\nstruct arguments : public grammar&lt;arguments&gt;\n{\n template &lt;typename ScannerT&gt;\n struct definition\n {\n definition(arguments const&amp; /*self*/)\n {\n command\n = acommand | bcommand;\n\n acommand = chlit&lt;char&gt;('A') \n &gt;&gt; ( a_someoperation | a_someotheroperation );\n\n a_someoperation = str_p( \"some_operation\" ) [ &amp;AOperation ];\n a_someotheroperation = str_p( \"some_other_operation\" )[ &amp;AOtherOperation ];\n\n bcommand = chlit&lt;char&gt;('B') \n &gt;&gt; ( b_someoperation | b_someotheroperation );\n\n b_someoperation = str_p( \"some_operation_for_B\" ) [ &amp;BOperation ];\n b_someotheroperation = str_p( \"some_other_operation_for_B\" )[ &amp;BOtherOperation ];\n\n }\n\n rule&lt;ScannerT&gt; command;\n rule&lt;ScannerT&gt; acommand, bcommand;\n rule&lt;ScannerT&gt; a_someoperation, a_someotheroperation;\n rule&lt;ScannerT&gt; b_someoperation, b_someotheroperation;\n\n rule&lt;ScannerT&gt; const&amp;\n start() const { return command; }\n };\n};\n\ntemplate&lt;typename parse_info &gt;\nbool test( parse_info pi ) {\n if( pi.full ) { \n cout &lt;&lt; \"success\" &lt;&lt; endl; \n return true;\n } else { \n cout &lt;&lt; \"fail\" &lt;&lt; endl; \n return false;\n }\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n\n arguments args;\n test( parse( \"A some_operation\", args, space_p ) );\n test( parse( \"A some_other_operation\", args, space_p ) );\n test( parse( \"B some_operation_for_B\", args, space_p ) );\n test( parse( \"B some_other_operation_for_B\", args, space_p ) );\n test( parse( \"A some_other_operation_for_B\", args, space_p ) );\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 240474, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 2, "selected": false, "text": "<p>I've seen a solution to this problem that worked well: a hash table of functions. </p>\n\n<p>At compile time a <a href=\"http://www.google.com/search?q=gperf&amp;ie=utf-8&amp;oe=utf-8&amp;aq=t&amp;rls=org.mozilla:en-US:official&amp;client=firefox-a\" rel=\"nofollow noreferrer\">Perfect Hash Function</a> is created for each supported operation and the operation is associated with a function to call (the function pointer is the value in the hash, the command string is the key). </p>\n\n<p>During runtime, the command functionality is called by using the command string to find the function in the hash table. Then the function is called passing the \"data\" string by reference. Each command function then parses out the remaining string according to its rules... the strategy pattern also applies at this point. </p>\n\n<p>Makes the code work like a state machine, which is (IMHO) the easiest way to approach networking code. </p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31610/" ]
I want your suggestion on the following pseudo-code. Please suggest how could I improve it, whether or not I could use some design patterns. ``` // i'm receiving a string containing : id operation arguments data = read(socket); tokens = tokenize(data," "); // tokenize the string based on spaces if(tokens[0] == "A") { if(tokens[1] == "some_operation") { // here goes code for some_operation , will use the remaining tokens as arguments for function calls } else if(tokens[1] == "some_other_operation") { // here goes code for some_other_operation , will use the remaining tokens } ... else { // unknown operation } } else if(tokens[0] == "B") { if(tokens[1] == "some_operation_for_B") { // do some operation for B } else if(tokens[1] == "yet_another_operation") { // do yet_another_operation for B } ... else { // unknown operation } } ``` I hope you get the point . The thing is I have a large number of **id's** and each has it's own **operations** , and I think it's kinda ugly to have 10 screens of code containing a lot of **if's** and **else if's**.
Have a class for each ID which implements a common interface. Basically the [Strategy pattern](http://en.wikipedia.org/wiki/Strategy_pattern) IIRC. So you'd call (pseudo)code like: `StrategyFactory.GetStrategy(tokens[0]).parse(tokens[1..n])`
239,350
<p>For some odd reason the Elapsed event is firing twice, where it should definitely be firing once. And immediately after, the timer ceases to work... The code structure is somewhat like this: A certain object is defined to fire a certain event when a value it contains, which is constantly updated in 500-1500ms intervals, increases in over X sum compared to the previous value.</p> <p>For example, if I define my X as 2, and the values I'm receiving are 1,2,1,2,3,4,8 for example, the event will fire when 8 is entered. The event handler for that event starts the aforementioned timer, which runs for Y time before it elapses and fires the problematic event. If the value returns to normal before the timer elapses, the timer is reset.</p> <p>So, the overall result should be an application that measures a certain dynamic value, and monitors it for large X size exceptions that occur for over Y seconds time.</p> <p>The overall result in code looks something like</p> <pre><code>vMonitor.Range=X; vMonitor.Over+= new EventHandler(StartTimer); vMonitor.Normal+= new EventHandler(StopTimer); vTimer.Elapsed+= new EventHandler(RaiseAlert); source.BeginUpdate(vMonitor.Value); </code></pre> <p>The actual problem is that the RaiseAlert is fired twice upon the timers elapsing, and then its as if the Timer stops working completely, not firing at all anymore. I think its worth mentioning that the full application contains a lot of thread activity, with atleast 2 threads running at a time, updating the vMonitor values.</p> <p>Any Thoughts?</p> <h3>Update:</h3> <p>About the thread matter, its fairly complex to explain the exact structure, but I can say that the vMonitor object is contained in another object, that contains the updating value, which is constantly changed by the various threads, in a monitored manner, of course. Whenever the parent object's value is updated, its compared to vMonitor, and the proper event is fired. The value in vMonitor is subsequently replaced by the parent objects value.</p> <p>EDIT: I've just verified it again, the vTimer.Elapsed delegate holds only one, correct, event handler.</p>
[ { "answer_id": 239354, "author": "Calanus", "author_id": 445, "author_profile": "https://Stackoverflow.com/users/445", "pm_score": 0, "selected": false, "text": "<p>Well my most basic instinct would be that somehow you actually have two event wireups to the Elapsed event - resulting in two events firing. I've been caught out through this, sometimes because I've added the event wireup manually when it has already been added in the designer, or there is some inheritance aspect here where the wireup is already in a base class and you are repeating it in a derived class.</p>\n\n<p>Of course if there are multiple threads then that is a whole different ball game!</p>\n" }, { "answer_id": 241990, "author": "Switters", "author_id": 1860358, "author_profile": "https://Stackoverflow.com/users/1860358", "pm_score": 0, "selected": false, "text": "<p>Edit to take into account what Mitch had said because I completely forgot that's the easiest answer. In the method that handles the Elapsed event make sure you are first stopping your timer so that the event will not fire again while it is being handled.</p>\n" }, { "answer_id": 242003, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 2, "selected": false, "text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.80).aspx\" rel=\"nofollow noreferrer\">MSDN</a>:</p>\n\n<blockquote>\n <p>The Elapsed event is raised on a\n ThreadPool thread. If processing of\n the Elapsed event lasts longer than\n Interval, the event might be raised\n again on another ThreadPool thread.\n Thus, the event handler should be\n reentrant.</p>\n</blockquote>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
For some odd reason the Elapsed event is firing twice, where it should definitely be firing once. And immediately after, the timer ceases to work... The code structure is somewhat like this: A certain object is defined to fire a certain event when a value it contains, which is constantly updated in 500-1500ms intervals, increases in over X sum compared to the previous value. For example, if I define my X as 2, and the values I'm receiving are 1,2,1,2,3,4,8 for example, the event will fire when 8 is entered. The event handler for that event starts the aforementioned timer, which runs for Y time before it elapses and fires the problematic event. If the value returns to normal before the timer elapses, the timer is reset. So, the overall result should be an application that measures a certain dynamic value, and monitors it for large X size exceptions that occur for over Y seconds time. The overall result in code looks something like ``` vMonitor.Range=X; vMonitor.Over+= new EventHandler(StartTimer); vMonitor.Normal+= new EventHandler(StopTimer); vTimer.Elapsed+= new EventHandler(RaiseAlert); source.BeginUpdate(vMonitor.Value); ``` The actual problem is that the RaiseAlert is fired twice upon the timers elapsing, and then its as if the Timer stops working completely, not firing at all anymore. I think its worth mentioning that the full application contains a lot of thread activity, with atleast 2 threads running at a time, updating the vMonitor values. Any Thoughts? ### Update: About the thread matter, its fairly complex to explain the exact structure, but I can say that the vMonitor object is contained in another object, that contains the updating value, which is constantly changed by the various threads, in a monitored manner, of course. Whenever the parent object's value is updated, its compared to vMonitor, and the proper event is fired. The value in vMonitor is subsequently replaced by the parent objects value. EDIT: I've just verified it again, the vTimer.Elapsed delegate holds only one, correct, event handler.
From [MSDN](http://msdn.microsoft.com/en-us/library/system.timers.timer(VS.80).aspx): > > The Elapsed event is raised on a > ThreadPool thread. If processing of > the Elapsed event lasts longer than > Interval, the event might be raised > again on another ThreadPool thread. > Thus, the event handler should be > reentrant. > > >
239,408
<p>I have a class with some abstract methods, but I want to be able to edit a subclass of that class in the designer. However, the designer can't edit the subclass unless it can create an instance of the parent class. So my plan is to replace the abstract methods with stubs and mark them as virtual - but then if I make another subclass, I won't get a compile-time error if I forget to implement them.</p> <p>Is there a way to mark the methods so that they have to be implemented by subclasses, without marking them as abstract?</p>
[ { "answer_id": 239423, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "<p>Well you could do some really messy code involving <code>#if</code> - i.e. in <code>DEBUG</code> it is virtual (for the designer), but in <code>RELEASE</code> it is abstract. A real pain to maintain, though.</p>\n\n<p>But other than that: basically, no. If you want designer support it can't be abstract, so you are left with \"virtual\" (presumably with the base method throwing a <code>NotImplementedException</code>).</p>\n\n<p>Of course, your unit tests will check that the methods have been implemented, yes? ;-p</p>\n\n<p>Actually, it would probably be quite easy to test via generics - i.e. have a generic test method of the form:</p>\n\n<pre><code>[Test]\npublic void TestFoo() {\n ActualTest&lt;Foo&gt;();\n}\n[Test]\npublic void TestBar() {\n ActualTest&lt;Bar&gt;();\n}\n\nstatic void ActualTest&lt;T&gt;() where T : SomeBaseClass, new() {\n T obj = new T();\n Assert.blah something involving obj\n}\n</code></pre>\n" }, { "answer_id": 239490, "author": "Simon Keep", "author_id": 1127460, "author_profile": "https://Stackoverflow.com/users/1127460", "pm_score": 0, "selected": false, "text": "<p>I know its not quite what you are after but you could make all of your stubs in the base class throw the NotImplementedException. Then if any of your subclasses have not overridden them you would get a runtime exception when the method in the base class gets called.</p>\n" }, { "answer_id": 240277, "author": "Brent Rockwood", "author_id": 31253, "author_profile": "https://Stackoverflow.com/users/31253", "pm_score": 0, "selected": false, "text": "<p>The Component class contains a boolean property called \"DesignMode\" which is very handy when you want your code to behave differently in the designer than at runtime. May be of some use in this case.</p>\n" }, { "answer_id": 240421, "author": "Curro", "author_id": 10688, "author_profile": "https://Stackoverflow.com/users/10688", "pm_score": 3, "selected": false, "text": "<p>You could use the reference to implementation idiom in your class.</p>\n\n<pre><code>public class DesignerHappy\n{\n private ADesignerHappyImp imp_;\n\n public int MyMethod()\n {\n return imp_.MyMethod() \n }\n\n public int MyProperty\n {\n get { return imp_.MyProperty; }\n set { imp_.MyProperty = value; }\n }\n}\n\npublic abstract class ADesignerHappyImp\n{\n public abstract int MyMethod();\n public int MyProperty {get; set;}\n}\n</code></pre>\n\n<p>DesignerHappy just exposes the interface you want but forwards all the calls to the implementation object. You extend the behavior by sub-classing ADesignerHappyImp, which forces you to implement all the abstract members.</p>\n\n<p>You can provide a default implementation of ADesignerHappyImp, which is used to initialize DesignerHappy by default and expose a property that allows you to change the implementation.</p>\n" }, { "answer_id": 240667, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 0, "selected": false, "text": "<p>As a general rule, if there's no way in a language to do something that generally means that there's a good conceptual reason not to do it.</p>\n\n<p>Sometimes this will be the fault of the language designers - but not often. Usually I find they know more about language design than I do ;-)</p>\n\n<p>In this case you want a un-overridden virtual method to throw a compile time exception (rather and a run time one). Basically an abstract method then.</p>\n\n<p>Making virtual methods behave like abstract ones is just going to create a world of confusion for you further down the line.</p>\n\n<p>On the other hand, VS plug in design is often not quite at the same level (that's a little unfair, but certainly less rigour is applied than is at the language design stage - and rightly so). Some VS tools, like the class designer and current WPF editors, are nice ideas but not really complete - yet. </p>\n\n<p>In the case that you're describing I think you have an argument not to use the class designer, not an argument to hack your code.</p>\n\n<p>At some point (maybe in the next VS) they'll tidy up how the class designer deals with abstract classes, and then you'll have a hack with no idea why it was coded that way.</p>\n\n<p>It should always be the last resort to hack your code to fit the designer, and when you do try to keep hacks minimal. I find that it's usually better to have concise, readable code that makes sense quickly over Byzantine code that works in the current broken tools.</p>\n" }, { "answer_id": 305952, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Note that \"DesignMode\" is not set in the constructor. It's set after VS parses the InitializeComponents() method.</p>\n" }, { "answer_id": 7815906, "author": "Roger", "author_id": 1002305, "author_profile": "https://Stackoverflow.com/users/1002305", "pm_score": 0, "selected": false, "text": "<p>To use ms as an example...</p>\n\n<p>Microsoft does this with the user control templates in silverlight. #if is perfectly acceptable and it is doubtful the the tooling will work around it anytime soon. IMHO </p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239408", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
I have a class with some abstract methods, but I want to be able to edit a subclass of that class in the designer. However, the designer can't edit the subclass unless it can create an instance of the parent class. So my plan is to replace the abstract methods with stubs and mark them as virtual - but then if I make another subclass, I won't get a compile-time error if I forget to implement them. Is there a way to mark the methods so that they have to be implemented by subclasses, without marking them as abstract?
Well you could do some really messy code involving `#if` - i.e. in `DEBUG` it is virtual (for the designer), but in `RELEASE` it is abstract. A real pain to maintain, though. But other than that: basically, no. If you want designer support it can't be abstract, so you are left with "virtual" (presumably with the base method throwing a `NotImplementedException`). Of course, your unit tests will check that the methods have been implemented, yes? ;-p Actually, it would probably be quite easy to test via generics - i.e. have a generic test method of the form: ``` [Test] public void TestFoo() { ActualTest<Foo>(); } [Test] public void TestBar() { ActualTest<Bar>(); } static void ActualTest<T>() where T : SomeBaseClass, new() { T obj = new T(); Assert.blah something involving obj } ```
239,414
<p>How do I insert a current_timestamp into an SQL Server 2005 database datable with a timestamp column?</p> <p>It should be simple but I cannot get it to work. Examples would be much appreciated.</p>
[ { "answer_id": 239426, "author": "robsoft", "author_id": 3897, "author_profile": "https://Stackoverflow.com/users/3897", "pm_score": 3, "selected": false, "text": "<p>if you can execute a query from PHP then it should just be a matter of using 'getdate()' ;</p>\n\n<pre><code>update MyTable set MyColumn=getdate();\n</code></pre>\n\n<p>or</p>\n\n<pre><code>insert into MyTable (MyColumn) values (getdate());\n</code></pre>\n" }, { "answer_id": 239427, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>You just use the normal mechanism to execute your queries into SQL Server, and use what follows.</p>\n\n<p>The current_timestamp function returns it</p>\n\n<pre><code> insert into table (creation_date) VALUES (current_timestamp)\n</code></pre>\n\n<p>Complete example</p>\n\n<pre><code>CREATE table timestamp_test (creation_timestamp datetime)\nINSERT INTO timestamp_test (creation_timestamp) VALUES (current_timestamp)\nSELECT * FROM timestamp_test\nDROP TABLE timestamp_test\n</code></pre>\n" }, { "answer_id": 239433, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 3, "selected": false, "text": "<p>The column datatype should be datetime</p>\n\n<p>You can either get the database to work out the date:</p>\n\n<pre><code>$sql = 'INSERT INTO tablename (fieldname) VALUES (getdate())';\n</code></pre>\n\n<p>or get PHP to work out the date</p>\n\n<pre><code>$sql = 'INSERT INTO tablename (fieldname) VALUES (\\'' . date('Y-m-d H:i:s') . '\\')';\n</code></pre>\n\n<p>then something like <code>mssql_execute($sql);</code> but this depends on how you are connecting to your database</p>\n" }, { "answer_id": 240195, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 0, "selected": false, "text": "<p>If you explain the error you are receiving (and post your insert or update code), it might make it easier to see what your problem is. One possible issue is that you must be inserting into a datetime field (or in 2008 you could use a date field as well). Occasionally people think that they can insert the current date into a timestamp field but even though the name of this data type seems as if it should be date related, this data type actaully has nothing to do with dates and times and cannot accept date data.</p>\n" }, { "answer_id": 8236130, "author": "davibq", "author_id": 1060923, "author_profile": "https://Stackoverflow.com/users/1060923", "pm_score": 2, "selected": false, "text": "<p>To insert data into a timeStamp field, I think you have to use <code>DEFAULT</code>.\nFor example: </p>\n\n<pre><code>INSERT INTO User(username, EnterTS) VALUES ('user123', DEFAULT)\n</code></pre>\n\n<p>where <code>EnterTS</code> is a TimeStamp field</p>\n" }, { "answer_id": 11037161, "author": "HPWD", "author_id": 483140, "author_profile": "https://Stackoverflow.com/users/483140", "pm_score": 0, "selected": false, "text": "<p>I realize this is an old post but I ran across this and figured others might too.</p>\n\n<p>What I do is to create a field in the table using the datatype of datetime and then for the column properties for the default Value or binding, I enter <code>getdate()</code>. Every record that gets entered into the table now has a date and time stamp.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do I insert a current\_timestamp into an SQL Server 2005 database datable with a timestamp column? It should be simple but I cannot get it to work. Examples would be much appreciated.
if you can execute a query from PHP then it should just be a matter of using 'getdate()' ; ``` update MyTable set MyColumn=getdate(); ``` or ``` insert into MyTable (MyColumn) values (getdate()); ```
239,425
<p>I have a WinForms C# application using a MS SQL Server Express database. The application is deployed on the PCs of our customers and they don't have computer related knowledge. </p> <p>The application updates the database regularly and I see a lot of fragmentation on the index files. How do I keep the database healthy/responsive over time? </p> <p>I was thinking about programming a stored procedure which reorganizes every index, but I lack t-sql skills; can someone lead me in the right direction? </p> <p>Bas</p>
[ { "answer_id": 239479, "author": "baldy", "author_id": 2012, "author_profile": "https://Stackoverflow.com/users/2012", "pm_score": 1, "selected": false, "text": "<p>Use the DBCC REINDEX option if you can afford to take the table offline for a short while, alternatively DBCC INDEXDEFRAG. The IndexDefrag option has been depracted though. You can also use the ALTER INDEX statement in SQL 2005/2008.</p>\n" }, { "answer_id": 239632, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 0, "selected": false, "text": "<p>Also make sure that your database FILE is less prone to fragmentation. This is admittedly very tough to do, since you don't know what the layout of your customers' drives are, but I suggest starting your .MDB file off at a reasonably large initial size to prevent online rebuilds, which suck time and resources, and often lead to file level fragmentation as well. </p>\n\n<p>Your index design also impacts how fragmented your indexes are. You need to make sure indexes you're inserting to a lot have an appropriately low <a href=\"http://msdn.microsoft.com/en-us/library/aa933139(SQL.80).aspx\" rel=\"nofollow noreferrer\">FILLFACTOR</a> to prevent page splitting. Also get rid of any indexes which are not being used.</p>\n\n<p>To defrag your indexes, use the <a href=\"http://msdn.microsoft.com/en-us/library/ms181671.aspx\" rel=\"nofollow noreferrer\">DBCC DBREINDEX</a> command.</p>\n" }, { "answer_id": 239764, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Would be nice to have a reusable stored procedure written that can do everything that I should do on a database programmatically using best DBA maintenance practices.</p>\n\n<p>Like updating statistics, check for page errors, defrag, reindex, shrink?, .....</p>\n\n<p>Like a \"Make my DB healthy\" stored proc</p>\n\n<p>anyone who have a script like that available?</p>\n" }, { "answer_id": 1889097, "author": "Bas Jansen", "author_id": 1997188, "author_profile": "https://Stackoverflow.com/users/1997188", "pm_score": 1, "selected": true, "text": "<p>I now use 2 sql scripts. </p>\n\n<pre><code>SELECT \n st.object_id AS objectid,\n st.index_id AS indexid,\n partition_number AS partitionnum,\n avg_fragmentation_in_percent AS frag,\n o.name,\n i.name\nFROM \n sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL , NULL, 'LIMITED') st\njoin\n sys.objects o on o.object_id = st.object_id\njoin \n sys.indexes i on st.object_id = i.object_id and i.index_id=st.index_id\n</code></pre>\n\n<p>I run this when starting my program and check if my main tables has an avg_fragmentation_in_percent of more then 70. If so I run the following script.</p>\n\n<pre><code>SET NOCOUNT ON;\nDECLARE @objectid int;\nDECLARE @indexid int;\nDECLARE @partitioncount bigint;\nDECLARE @schemaname nvarchar(130); \nDECLARE @objectname nvarchar(130); \nDECLARE @indexname nvarchar(130); \nDECLARE @partitionnum bigint;\nDECLARE @partitions bigint;\nDECLARE @frag float;\nDECLARE @command nvarchar(4000); \n-- Conditionally select tables and indexes from the sys.dm_db_index_physical_stats function \n-- and convert object and index IDs to names.\n\nif ( object_id( 'tempdb..#work_to_do' ) is not null )\n DROP TABLE #work_to_do;\n\n-- Alleen indexen die meer dan x% gefragemteerd zijn\nSELECT\n object_id AS objectid,\n index_id AS indexid,\n partition_number AS partitionnum,\n avg_fragmentation_in_percent AS frag\nINTO #work_to_do\nFROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL , NULL, 'LIMITED')\nWHERE avg_fragmentation_in_percent &gt; 5.0 AND index_id &gt; 0;\n\n-- Declare the cursor for the list of partitions to be processed.\nDECLARE partitions CURSOR FOR SELECT * FROM #work_to_do;\n\n-- Open the cursor.\nOPEN partitions;\n\n-- Loop through the partitions.\nWHILE (1=1)\n BEGIN;\n FETCH NEXT\n FROM partitions\n INTO @objectid, @indexid, @partitionnum, @frag;\n IF @@FETCH_STATUS &lt; 0 BREAK;\n SELECT @objectname = QUOTENAME(o.name), @schemaname = QUOTENAME(s.name)\n FROM sys.objects AS o\n JOIN sys.schemas as s ON s.schema_id = o.schema_id\n WHERE o.object_id = @objectid;\n SELECT @indexname = QUOTENAME(name)\n FROM sys.indexes\n WHERE object_id = @objectid AND index_id = @indexid;\n SELECT @partitioncount = count (*)\n FROM sys.partitions\n WHERE object_id = @objectid AND index_id = @indexid;\n\n SET @command = N'ALTER INDEX ' + @indexname + N' ON ' + @schemaname + N'.' + @objectname + N' REBUILD WITH (FILLFACTOR = 90)';\n IF @partitioncount &gt; 1\n SET @command = @command + N' PARTITION=' + CAST(@partitionnum AS nvarchar(10));\n EXEC (@command);\n PRINT N'Executed: ' + @command;\n END;\n\n-- Close and deallocate the cursor.\nCLOSE partitions;\nDEALLOCATE partitions;\n\n-- Drop the temporary table.\nDROP TABLE #work_to_do;\n</code></pre>\n\n<p>This script defrags all tables with a fragmantation of more then 5%</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1997188/" ]
I have a WinForms C# application using a MS SQL Server Express database. The application is deployed on the PCs of our customers and they don't have computer related knowledge. The application updates the database regularly and I see a lot of fragmentation on the index files. How do I keep the database healthy/responsive over time? I was thinking about programming a stored procedure which reorganizes every index, but I lack t-sql skills; can someone lead me in the right direction? Bas
I now use 2 sql scripts. ``` SELECT st.object_id AS objectid, st.index_id AS indexid, partition_number AS partitionnum, avg_fragmentation_in_percent AS frag, o.name, i.name FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL , NULL, 'LIMITED') st join sys.objects o on o.object_id = st.object_id join sys.indexes i on st.object_id = i.object_id and i.index_id=st.index_id ``` I run this when starting my program and check if my main tables has an avg\_fragmentation\_in\_percent of more then 70. If so I run the following script. ``` SET NOCOUNT ON; DECLARE @objectid int; DECLARE @indexid int; DECLARE @partitioncount bigint; DECLARE @schemaname nvarchar(130); DECLARE @objectname nvarchar(130); DECLARE @indexname nvarchar(130); DECLARE @partitionnum bigint; DECLARE @partitions bigint; DECLARE @frag float; DECLARE @command nvarchar(4000); -- Conditionally select tables and indexes from the sys.dm_db_index_physical_stats function -- and convert object and index IDs to names. if ( object_id( 'tempdb..#work_to_do' ) is not null ) DROP TABLE #work_to_do; -- Alleen indexen die meer dan x% gefragemteerd zijn SELECT object_id AS objectid, index_id AS indexid, partition_number AS partitionnum, avg_fragmentation_in_percent AS frag INTO #work_to_do FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL , NULL, 'LIMITED') WHERE avg_fragmentation_in_percent > 5.0 AND index_id > 0; -- Declare the cursor for the list of partitions to be processed. DECLARE partitions CURSOR FOR SELECT * FROM #work_to_do; -- Open the cursor. OPEN partitions; -- Loop through the partitions. WHILE (1=1) BEGIN; FETCH NEXT FROM partitions INTO @objectid, @indexid, @partitionnum, @frag; IF @@FETCH_STATUS < 0 BREAK; SELECT @objectname = QUOTENAME(o.name), @schemaname = QUOTENAME(s.name) FROM sys.objects AS o JOIN sys.schemas as s ON s.schema_id = o.schema_id WHERE o.object_id = @objectid; SELECT @indexname = QUOTENAME(name) FROM sys.indexes WHERE object_id = @objectid AND index_id = @indexid; SELECT @partitioncount = count (*) FROM sys.partitions WHERE object_id = @objectid AND index_id = @indexid; SET @command = N'ALTER INDEX ' + @indexname + N' ON ' + @schemaname + N'.' + @objectname + N' REBUILD WITH (FILLFACTOR = 90)'; IF @partitioncount > 1 SET @command = @command + N' PARTITION=' + CAST(@partitionnum AS nvarchar(10)); EXEC (@command); PRINT N'Executed: ' + @command; END; -- Close and deallocate the cursor. CLOSE partitions; DEALLOCATE partitions; -- Drop the temporary table. DROP TABLE #work_to_do; ``` This script defrags all tables with a fragmantation of more then 5%
239,435
<p>I'm kinda stuck with this one so I hoped someone could help me.</p> <p>I am doing a Winforms application and I need to show a Modal Dialog (form.ShowDialog) that returns a value (prompts the User some values and wraps them in a Object). </p> <p>I just can't see how to do this rather than give a reference into the object or depending on some form of public Property to read the data afterwards. </p> <p>I'd just like to have ShowDialog return something different, but that doesn't work. Is thare some "good" way to do this? </p> <p>I'm sure the problem isn't new, but since almost nobody seems to do Winforms any more I can't find any guidance on the web.</p>
[ { "answer_id": 239449, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 5, "selected": true, "text": "<p>Add a static method to your form, like this:</p>\n\n<pre><code>public class MyDialog : Form\n{\n // todo: think of a better method name :)\n public static MyObject ShowAndReturnObject() \n {\n var dlg = new MyDialog();\n if (new dlg.ShowDialog() == DialogResult.OK) \n {\n var obj = // construct an instance of MyObject from dlg\n return obj;\n }\n else\n {\n return null; \n }\n }\n}\n</code></pre>\n\n<p>Now you can call this from your program thusly:</p>\n\n<pre><code>var myObject = MyDialog.ShowAndReturnObject();\n</code></pre>\n\n<p>... and if they cancel the dialog, myObject will be null.</p>\n\n<p>Now, having said all that, I do believe that adding a property to your form's class which you then read from after calling ShowDialog() is the better approach.</p>\n" }, { "answer_id": 239460, "author": "Kieron", "author_id": 5791, "author_profile": "https://Stackoverflow.com/users/5791", "pm_score": 0, "selected": false, "text": "<p>Or you could create a new ShowDialog method inside your form class that does basically what Matt Hamilton's does. Maybe even an extension method if it's something you do to lots of forms in your problem.</p>\n" }, { "answer_id": 12764709, "author": "Armando Peña", "author_id": 1684287, "author_profile": "https://Stackoverflow.com/users/1684287", "pm_score": 2, "selected": false, "text": "<p>You can create a public property inside the Dialog that represents the returning value:</p>\n\n<pre><code>/* Caller Code */ \nvar dlg = new MyDialog();\nif(dlg.ShowDialog() == DialogResult.OK)\n MessageBox.Show(dlg.MyResult);\n\n/* Dialog Code */\npublic string MyResult { get { return textBox1.Text; } }\n\nprivate void btnOk_Click(object sender, EventArgs e)\n{\n DialogResult = System.Windows.Forms.DialogResult.OK;\n this.Close();\n}\n</code></pre>\n" }, { "answer_id": 17282944, "author": "mjhillman", "author_id": 2093531, "author_profile": "https://Stackoverflow.com/users/2093531", "pm_score": 0, "selected": false, "text": "<p>The public property in the dialog form makes sense. However, do not close the dialog in the Ok button click event handler. When you assign the DialogResult property the dialog form will be hidden. Then in the calling form you can determine if Ok or Cancel was clicked by examining the DialogResult. Then you can access the public property if the Ok button was clicked and then dispose the dialog form. This should be done using a try-catch-finally block in the calling form or through a using statement. You must dispose of the modal dialog in order to prevent a memory leak.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21699/" ]
I'm kinda stuck with this one so I hoped someone could help me. I am doing a Winforms application and I need to show a Modal Dialog (form.ShowDialog) that returns a value (prompts the User some values and wraps them in a Object). I just can't see how to do this rather than give a reference into the object or depending on some form of public Property to read the data afterwards. I'd just like to have ShowDialog return something different, but that doesn't work. Is thare some "good" way to do this? I'm sure the problem isn't new, but since almost nobody seems to do Winforms any more I can't find any guidance on the web.
Add a static method to your form, like this: ``` public class MyDialog : Form { // todo: think of a better method name :) public static MyObject ShowAndReturnObject() { var dlg = new MyDialog(); if (new dlg.ShowDialog() == DialogResult.OK) { var obj = // construct an instance of MyObject from dlg return obj; } else { return null; } } } ``` Now you can call this from your program thusly: ``` var myObject = MyDialog.ShowAndReturnObject(); ``` ... and if they cancel the dialog, myObject will be null. Now, having said all that, I do believe that adding a property to your form's class which you then read from after calling ShowDialog() is the better approach.
239,443
<p>I have these two <code>CREATE TABLE</code> statements: </p> <pre><code>CREATE TABLE GUEST ( id int(15) not null auto_increment PRIMARY KEY, GuestName char(25) not null ); CREATE TABLE PAYMENT ( id int(15) not null auto_increment Foreign Key(id) references GUEST(id), BillNr int(15) not null ); </code></pre> <p>What is the problem in the second statement? It did not create a new table.</p>
[ { "answer_id": 239582, "author": "mattoc", "author_id": 10901, "author_profile": "https://Stackoverflow.com/users/10901", "pm_score": 0, "selected": false, "text": "<p>Make sure you're using the InnoDB engine for either the database, or for both tables. From the MySQL Reference:</p>\n\n<blockquote>\n <p>For storage engines other than InnoDB,\n MySQL Server parses the FOREIGN KEY\n syntax in CREATE TABLE statements, but\n does not use or store it.</p>\n</blockquote>\n" }, { "answer_id": 239620, "author": "Hapkido", "author_id": 27646, "author_profile": "https://Stackoverflow.com/users/27646", "pm_score": 3, "selected": false, "text": "<p>I will suggest having a unique key for the payment table. On it's side, the foreign key should not be auto_increment as it refer to an already existing key.</p>\n\n<pre><code>CREATE TABLE GUEST(\n id int(15) not null auto_increment PRIMARY KEY, \n GuestName char(25) not null\n) ENGINE=INNODB;\n\nCREATE TABLE PAYMENT(\n id int(15)not null auto_increment, \n Guest_id int(15) not null, \n INDEX G_id (Guest_id), \n Foreign Key(Guest_id) references GUEST(id),\n BillNr int(15) not null\n) ENGINE=INNODB;\n</code></pre>\n" }, { "answer_id": 239633, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 4, "selected": false, "text": "<p>The answer to your question is almost the same as the answer to <a href=\"https://stackoverflow.com/questions/236668/foreign-keys-in-mysql#236677\">this one</a> . </p>\n\n<p>You need to specify in the table containing the foreign key the name of the table containing the primary key, and the name of the primary key field (using \"references\").</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html\" rel=\"noreferrer\">This</a> has some code showing how to create foreign keys by themselves, and in CREATE TABLE.</p>\n\n<p>Here's one of the simpler examples from that:</p>\n\n<pre><code>CREATE TABLE parent (id INT NOT NULL,\n PRIMARY KEY (id)\n) ENGINE=INNODB;\nCREATE TABLE child (id INT, parent_id INT,\n INDEX par_ind (parent_id),\n FOREIGN KEY (parent_id) REFERENCES parent(id)\n ON DELETE CASCADE\n) ENGINE=INNODB;\n</code></pre>\n" }, { "answer_id": 5360218, "author": "Piyush Sharma", "author_id": 667009, "author_profile": "https://Stackoverflow.com/users/667009", "pm_score": -1, "selected": false, "text": "<p>There should be space between <code>int(15)</code> and <code>not null</code></p>\n" }, { "answer_id": 55868477, "author": "Thirumurugan K", "author_id": 9984163, "author_profile": "https://Stackoverflow.com/users/9984163", "pm_score": 0, "selected": false, "text": "<pre><code>create table course(ccode int(2) primary key,course varchar(10));\n\ncreate table student1(rollno int(5) primary key,name varchar(10),coursecode int(2) not \nnull,mark1 int(3),mark2 int(3),foreign key(coursecode) references course(ccode));\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17451/" ]
I have these two `CREATE TABLE` statements: ``` CREATE TABLE GUEST ( id int(15) not null auto_increment PRIMARY KEY, GuestName char(25) not null ); CREATE TABLE PAYMENT ( id int(15) not null auto_increment Foreign Key(id) references GUEST(id), BillNr int(15) not null ); ``` What is the problem in the second statement? It did not create a new table.
The answer to your question is almost the same as the answer to [this one](https://stackoverflow.com/questions/236668/foreign-keys-in-mysql#236677) . You need to specify in the table containing the foreign key the name of the table containing the primary key, and the name of the primary key field (using "references"). [This](http://dev.mysql.com/doc/refman/5.0/en/innodb-foreign-key-constraints.html) has some code showing how to create foreign keys by themselves, and in CREATE TABLE. Here's one of the simpler examples from that: ``` CREATE TABLE parent (id INT NOT NULL, PRIMARY KEY (id) ) ENGINE=INNODB; CREATE TABLE child (id INT, parent_id INT, INDEX par_ind (parent_id), FOREIGN KEY (parent_id) REFERENCES parent(id) ON DELETE CASCADE ) ENGINE=INNODB; ```
239,450
<p>I want to compare two ms-access .mdb files to check that the data they contain is same in both.</p> <p>How can I do this?</p>
[ { "answer_id": 239484, "author": "rwired", "author_id": 17492, "author_profile": "https://Stackoverflow.com/users/17492", "pm_score": -1, "selected": false, "text": "<p>If you want to know if the files are identical then</p>\n\n<pre><code>fc file1.mdb file2.mdb \n</code></pre>\n\n<p>on a DOS command line.</p>\n\n<p>If the files aren't identical but you suspect they contain the same tables and records then the easiest way would be quickly write a small utility that opens both databases and cycles through the tables of both performing a heterogeneous query to extract the Diff between the two files. </p>\n\n<p>There are some tools out there which will do this for you, but they all appear to be shareware. </p>\n" }, { "answer_id": 239529, "author": "Ather", "author_id": 1065163, "author_profile": "https://Stackoverflow.com/users/1065163", "pm_score": 2, "selected": false, "text": "<p>Take text dumps of database tables and simply compare the dumped text files using BeyondCompare (or any other text comparison tool). Crude but can work!</p>\n" }, { "answer_id": 239540, "author": "Marcin K", "author_id": 28722, "author_profile": "https://Stackoverflow.com/users/28722", "pm_score": 2, "selected": false, "text": "<p>I have very good experience with <a href=\"http://www.dbbalance.com/\" rel=\"nofollow noreferrer\">Cross-Database Comparator</a>. It is able to compare structure and/or data.</p>\n" }, { "answer_id": 241429, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 4, "selected": true, "text": "<p>I've done this kind of thing in code many, many times, mostly in cases where a local MDB needed to have updates applied to it drawn from data entered on a website. In one case the website was driven by an MDB, in others, it was a MySQL database. For the MDB, we just downloaded it, for MySQL, we ran scripts on the website to export and FTP text files.</p>\n\n<p>Now, the main point is that we wanted to compare data in the local MDB to the data downloaded from the website and update the local MDB to reflect changes made on the website (no, it wasn't possible to use a single data source -- it was the first thing I suggested, but it wasn't feasible).</p>\n\n<p>Let's call MDB A your local database, and MDB B the one you're downloading for comparison. What you have to check for is:</p>\n\n<ol>\n<li><p>records that exist in MDB A but not in MDB B. These may or may not be candidates for deletion (this will depend on your particular data).</p></li>\n<li><p>records that exist in MDB B but not in MDB A. These you will append from MDB B to MDB A.</p></li>\n<li><p>records that exist in both, which will need to be compared field by field.</p></li>\n</ol>\n\n<p>Steps #1 and #2 are fairly easily accomplished with queries that use an outer join to find the missing records. Step 3 requires some code.</p>\n\n<p>The principle behind the code is that the structure of all the tables in both MDBs are identical. So, you use DAO to walk the TableDefs collection, open a recordset, and walk the fields collection to run a SQL statement on each column of each table that either updates the data or outputs a list of the differences. </p>\n\n<p>The basic structure behind the code is:</p>\n\n<pre><code> Set rs = db.OpenRecordset(\"[SQL statement with the fields you want compared]\")\n For Each fld In rs.Fields\n ' Write a SQL string to update all the records in this column\n ' where the data doesn't match\n strSQL = \"[constructed SQL here]\"\n db.Execute strSQL, dbFailOnError\n Next fld\n</code></pre>\n\n<p>Now, the major complexity here is that your WHERE clause for each field has to be different -- text fields need to be treated differently from numeric and data fields. So you'll probably want a SELECT CASE that writes your WHERE clause based on the field type:</p>\n\n<pre><code> Select Case fld.Type\n Case dbText, dbMemo\n Case Else\n End Select\n</code></pre>\n\n<p>You'll want to use Nz() to compare the text fields, but you'd use Nz(TextField,'') for that, while using Nz(NumericField,0) for numeric fields or date fields. </p>\n\n<p>My example code doesn't actually use the structure above to define the WHERE clause because it's limited to fields that work very well comparing concatenated with a ZLS (text fields). What's below is pretty complicated to read through, but it's basically an expansion on the above structure.</p>\n\n<p>It was written for efficiency of updates, since it executes a SQL UPDATE for each field of the table, which is much more efficient than executing a SQL UPDATE for each row. If, on the other hand, you don't want to do an update, but want a list of the differences, you might treat the whole thing differently. But that gets pretty complicated depending on the output, </p>\n\n<p>If all you want to know is if two MDBs are identical, you would first check the number of records in each table first, and if you have one non-match, you quit and tell the user that the MDBs aren't the same. If the recordcounts are the same, then you have to check field by field, which I believe is best accomplished with column-by-column SQL written dynamically -- as soon as one of the resulting SQL SELECTS returns 1 or more records, you abort and tell your user that the MDBs are not identical.</p>\n\n<p>The complicated part is if you want to record the differences and inform the user, but going into that would make this already-interminable post even longer!</p>\n\n<p>What follows is just a portion of code from a larger subroutine which updates the saved query qdfOldMembers (from MDB A) with data from qdfNewMembers (from MDB B). The first argument, strSQL, is a SELECT statement that is limited to the fields you want to compare, while strTmpDB is the path/filename of the other MDB (MDB B in our example). The code assumes that strTmpDB has qdfNewMembers and qdfOldMembers already created (the original code writes the saved QueryDef on the fly). It could just as easily be direct table names (the only reason I use a saved query is because the fieldnames don't match exactly between the two MDBs it was written for).</p>\n\n<pre><code>Public Sub ImportMembers(strSQL As String, strTmpDB As String)\n Const STR_QUOTE = \"\"\"\"\n Dim db As Database\n Dim rsSource As Recordset '\n Dim fld As Field\n Dim strUpdateField As String\n Dim strZLS As String\n Dim strSet As String\n Dim strWhere As String\n\n ' EXTENSIVE CODE LEFT OUT HERE\n\n Set db = Application.DBEngine(0).OpenDatabase(strTmpDB)\n\n ' UPDATE EXISTING RECORDS\n Set rsSource = db.OpenRecordset(strSQL)\n strSQL = \"UPDATE qdfNewMembers INNER JOIN qdfOldMembers ON \"\n strSQL = strSQL &amp; \"qdfNewMembers.EntityID = qdfOldMembers.EntityID IN '\" _\n &amp; strTmpDB &amp; \"'\"\n If rsSource.RecordCount &lt;&gt; 0 Then\n For Each fld In rsSource.Fields\n strUpdateField = fld.Name\n 'Debug.Print strUpdateField\n If InStr(strUpdateField, \"ID\") = 0 Then\n If fld.Type = dbText Then\n strZLS = \" &amp; ''\"\n Else\n strZLS = vbNullString\n End If\n strSet = \" SET qdfOldMembers.\" &amp; strUpdateField _\n &amp; \" = varZLStoNull(qdfNewMembers.\" &amp; strUpdateField &amp; \")\"\n strWhere = \" WHERE \" &amp; \"qdfOldMembers.\" &amp; strUpdateField &amp; strZLS _\n &amp; \"&lt;&gt;\" &amp; \"qdfNewMembers.\" &amp; strUpdateField &amp; strZLS _\n &amp; \" OR (IsNull(qdfOldMembers.\" &amp; strUpdateField _\n &amp; \")&lt;&gt;IsNull(varZLStoNull(qdfNewMembers.\" _\n &amp; strUpdateField &amp; \")));\"\n db.Execute strSQL &amp; strSet &amp; strWhere, dbFailOnError\n 'Debug.Print strSQL &amp; strSet &amp; strWhere\n End If\n Next fld\n End If\nEnd Sub\n</code></pre>\n\n<p>Code for function varZLSToNull():</p>\n\n<pre><code>Public Function varZLStoNull(varInput As Variant) As Variant\n If Len(varInput) = 0 Then\n varZLStoNull = Null\n Else\n varZLStoNull = varInput\n End If\nEnd Function\n</code></pre>\n\n<p>I don't know if that's too complex to make sense, but maybe it will help somebody.</p>\n" }, { "answer_id": 1822588, "author": "Tony Toews", "author_id": 93528, "author_profile": "https://Stackoverflow.com/users/93528", "pm_score": 1, "selected": false, "text": "<p>See the Compare Access databases section at the <a href=\"http://www.granite.ab.ca/access/thirdparty.htm\" rel=\"nofollow noreferrer\">Microsoft Access third party utilities, products, tools, modules, etc.</a> page at my website.</p>\n" }, { "answer_id": 7311948, "author": "Greg Finzer", "author_id": 52962, "author_profile": "https://Stackoverflow.com/users/52962", "pm_score": 3, "selected": false, "text": "<p>You can try <a href=\"http://www.kellermansoftware.com/p-33-accessdiff.aspx\" rel=\"nofollow\">AccessDiff</a> (paid product). It has the ability to compare the schema, the data, and also access objects. It has a GUI and also a command line interface. </p>\n\n<p>Disclosure: I am the creator of this tool.</p>\n" }, { "answer_id": 9558613, "author": "sarh", "author_id": 282694, "author_profile": "https://Stackoverflow.com/users/282694", "pm_score": 0, "selected": false, "text": "<p>I've added \"table diff\" feature to my <a href=\"https://www.db-merge-tools.net/microsoft-access-diff-merge-overview.html\" rel=\"nofollow noreferrer\">accdbmerge</a> utility not so long time ago.\nI beleive that this answer will not help to solve original question, but it may be helpful for someone faced with the same problem in the future.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6613/" ]
I want to compare two ms-access .mdb files to check that the data they contain is same in both. How can I do this?
I've done this kind of thing in code many, many times, mostly in cases where a local MDB needed to have updates applied to it drawn from data entered on a website. In one case the website was driven by an MDB, in others, it was a MySQL database. For the MDB, we just downloaded it, for MySQL, we ran scripts on the website to export and FTP text files. Now, the main point is that we wanted to compare data in the local MDB to the data downloaded from the website and update the local MDB to reflect changes made on the website (no, it wasn't possible to use a single data source -- it was the first thing I suggested, but it wasn't feasible). Let's call MDB A your local database, and MDB B the one you're downloading for comparison. What you have to check for is: 1. records that exist in MDB A but not in MDB B. These may or may not be candidates for deletion (this will depend on your particular data). 2. records that exist in MDB B but not in MDB A. These you will append from MDB B to MDB A. 3. records that exist in both, which will need to be compared field by field. Steps #1 and #2 are fairly easily accomplished with queries that use an outer join to find the missing records. Step 3 requires some code. The principle behind the code is that the structure of all the tables in both MDBs are identical. So, you use DAO to walk the TableDefs collection, open a recordset, and walk the fields collection to run a SQL statement on each column of each table that either updates the data or outputs a list of the differences. The basic structure behind the code is: ``` Set rs = db.OpenRecordset("[SQL statement with the fields you want compared]") For Each fld In rs.Fields ' Write a SQL string to update all the records in this column ' where the data doesn't match strSQL = "[constructed SQL here]" db.Execute strSQL, dbFailOnError Next fld ``` Now, the major complexity here is that your WHERE clause for each field has to be different -- text fields need to be treated differently from numeric and data fields. So you'll probably want a SELECT CASE that writes your WHERE clause based on the field type: ``` Select Case fld.Type Case dbText, dbMemo Case Else End Select ``` You'll want to use Nz() to compare the text fields, but you'd use Nz(TextField,'') for that, while using Nz(NumericField,0) for numeric fields or date fields. My example code doesn't actually use the structure above to define the WHERE clause because it's limited to fields that work very well comparing concatenated with a ZLS (text fields). What's below is pretty complicated to read through, but it's basically an expansion on the above structure. It was written for efficiency of updates, since it executes a SQL UPDATE for each field of the table, which is much more efficient than executing a SQL UPDATE for each row. If, on the other hand, you don't want to do an update, but want a list of the differences, you might treat the whole thing differently. But that gets pretty complicated depending on the output, If all you want to know is if two MDBs are identical, you would first check the number of records in each table first, and if you have one non-match, you quit and tell the user that the MDBs aren't the same. If the recordcounts are the same, then you have to check field by field, which I believe is best accomplished with column-by-column SQL written dynamically -- as soon as one of the resulting SQL SELECTS returns 1 or more records, you abort and tell your user that the MDBs are not identical. The complicated part is if you want to record the differences and inform the user, but going into that would make this already-interminable post even longer! What follows is just a portion of code from a larger subroutine which updates the saved query qdfOldMembers (from MDB A) with data from qdfNewMembers (from MDB B). The first argument, strSQL, is a SELECT statement that is limited to the fields you want to compare, while strTmpDB is the path/filename of the other MDB (MDB B in our example). The code assumes that strTmpDB has qdfNewMembers and qdfOldMembers already created (the original code writes the saved QueryDef on the fly). It could just as easily be direct table names (the only reason I use a saved query is because the fieldnames don't match exactly between the two MDBs it was written for). ``` Public Sub ImportMembers(strSQL As String, strTmpDB As String) Const STR_QUOTE = """" Dim db As Database Dim rsSource As Recordset ' Dim fld As Field Dim strUpdateField As String Dim strZLS As String Dim strSet As String Dim strWhere As String ' EXTENSIVE CODE LEFT OUT HERE Set db = Application.DBEngine(0).OpenDatabase(strTmpDB) ' UPDATE EXISTING RECORDS Set rsSource = db.OpenRecordset(strSQL) strSQL = "UPDATE qdfNewMembers INNER JOIN qdfOldMembers ON " strSQL = strSQL & "qdfNewMembers.EntityID = qdfOldMembers.EntityID IN '" _ & strTmpDB & "'" If rsSource.RecordCount <> 0 Then For Each fld In rsSource.Fields strUpdateField = fld.Name 'Debug.Print strUpdateField If InStr(strUpdateField, "ID") = 0 Then If fld.Type = dbText Then strZLS = " & ''" Else strZLS = vbNullString End If strSet = " SET qdfOldMembers." & strUpdateField _ & " = varZLStoNull(qdfNewMembers." & strUpdateField & ")" strWhere = " WHERE " & "qdfOldMembers." & strUpdateField & strZLS _ & "<>" & "qdfNewMembers." & strUpdateField & strZLS _ & " OR (IsNull(qdfOldMembers." & strUpdateField _ & ")<>IsNull(varZLStoNull(qdfNewMembers." _ & strUpdateField & ")));" db.Execute strSQL & strSet & strWhere, dbFailOnError 'Debug.Print strSQL & strSet & strWhere End If Next fld End If End Sub ``` Code for function varZLSToNull(): ``` Public Function varZLStoNull(varInput As Variant) As Variant If Len(varInput) = 0 Then varZLStoNull = Null Else varZLStoNull = varInput End If End Function ``` I don't know if that's too complex to make sense, but maybe it will help somebody.
239,453
<p>I have a bunch of questions to post regarding the issue of separating the view from logic when creating a GUI.<br> The following is a minimal example of what I would do for a simple dialog that has a label and a button using the "Humble Dialog" approach. Pressing the button should show some text on the label. I have used C++ an Qt that I am comfortable with but I guess it is readable by all other audiences.<br> In any case I am interested in possible side effects because of the choice of language (I am using C++ in the project I am interested in introducing this).</p> <pre><code>class IView { public: IView(){} virtual ~IView(){} virtual void showResult(const QString &amp;text)=0; }; class Presenter { public: Presenter(IView *view){ m_View = view; } ~Presenter(){} void buttonPressed(){ QString text; // Evaluate text m_View-&gt;showResult(text); } private: IView *m_View; } // Multiple inheritance. Is this OK? class MyView : public QDialog, public IView { public: MyView(){ m_Presenter = new Presenter(this); m_Button = new QPushbutton(this); m_Label = new QLabel(this); // Ui event handled inside view but then directly // propagated to the Presenter connect(m_Button,SIGNAL(clicked()),this,SLOT(buttonPressed())); } ~MyView(){ delete m_Presenter; // Qt will automatically delete m_Button and m_Label; } void showResult(const QString &amp;text){ m_Label-&gt;setText(text); } protected slots: void buttonPressed(){ m_Presenter-&gt;buttonPressed(); } private: Presenter *m_Presenter; QPushbutton *m_Button; QLabel *m_Label; } class TestView : public IView { public: TestView(){} ~TestView(){} void showResult(const QString &amp;text){ m_LabelText = text; } QString getResult(){ return m_LabelText; } private: QString m_LabelText; } // Test code TestView view; Presenter presenter(&amp;view); presenter.buttonPressed(); EXPECT_EQ(view.getResult(),"Expected Result"); // Procuction code MyView view; view.show(); </code></pre> <p>Now this is what I got by following the <a href="http://www.objectmentor.com/resources/articles/TheHumbleDialogBox.pdf" rel="nofollow noreferrer">initial work on the Humble dialog by Feathers</a>. The approach that I would get from <a href="http://codebetter.com/blogs/jeremy.miller/pages/129546.aspx" rel="nofollow noreferrer">Fowler's implentation</a> would be to avoid creating the instance of the Presenter class in the constructor of MyView but pass it as a parameter instead so the production code would look like the test code. I personally like the approach I present here.</p> <p>So,</p> <ul> <li>Is it meant to be used with multiple inheritance (see my comment in MyView class)?</li> <li>Should the events be propagated directly to the Presenter or should they be handled in the view that will call the respective presenter action (as I have done here to avoid having to make the Presenter a QObject so it can handle UI events)?</li> <li>Are there any other remarks?</li> </ul>
[ { "answer_id": 239541, "author": "Mendelt", "author_id": 3320, "author_profile": "https://Stackoverflow.com/users/3320", "pm_score": 1, "selected": false, "text": "<p>I usually use the same pattern for my UI in C# Winforms stuff.</p>\n\n<p>You're actually not really doing multiple inheritance here. One of the classes you're inheriting from is just an empty interface. The only problem here is that C++ doesn't know the difference between a class and an interface.</p>\n\n<p>I don't think there's a problem with creating the presenter inside the view like this either. It's not the most testable design but you're probably not going test the view anyway because there's nothing to test there if you're using humble dialog. Or you could do \"poor man's DI\" by adding a second constructor that injects a presenter instead of creating it for testing purposes.</p>\n\n<p>In C# I usually have views that don't know about the presenter at all and just throw events instead of calling the presenter. This adds some decoupling but might be overkill in most situations.</p>\n\n<p>Overall this is a good implementation. If I'll ever have to write a C++ app with a UI i'm going to check this post</p>\n" }, { "answer_id": 239625, "author": "EricSchaefer", "author_id": 8976, "author_profile": "https://Stackoverflow.com/users/8976", "pm_score": 1, "selected": false, "text": "<p>Looks OK to me. But I would not use QString in the IView-Interface. Use some presentation independend type, if possible. That way, you can change the GUI-toolkit, without affecting the program logic and tests. Keep QString only if it is really painful to convert between QString and std::string or char* (I have no idea...).</p>\n" }, { "answer_id": 1656500, "author": "Dave", "author_id": 200388, "author_profile": "https://Stackoverflow.com/users/200388", "pm_score": 2, "selected": false, "text": "<p>When you do multiple inheritance with QObjects, the first class in the inheritance list needs to be the QObject-derived class. This is only strictly required if you plan to add signals and slots to your class, but is good practice anyway. So your class declaration:</p>\n\n<p>class MyView : public IView , public QDialog {</p>\n\n<p>needs to become this instead:</p>\n\n<p>class MyView : public QDialog , public IView {</p>\n\n<p>Again, this will only bite you if you ever add a slot or signal to \"MyView\".</p>\n\n<p>Other than that, I think this is a fine implementation, albeit huge amounts of overkill for a dialog. :)</p>\n\n<p>I'm using Fowler's MVP with Qt, and it's working okay. Things are more testable (nUnit style), but it is a bit more complex IMO.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6403/" ]
I have a bunch of questions to post regarding the issue of separating the view from logic when creating a GUI. The following is a minimal example of what I would do for a simple dialog that has a label and a button using the "Humble Dialog" approach. Pressing the button should show some text on the label. I have used C++ an Qt that I am comfortable with but I guess it is readable by all other audiences. In any case I am interested in possible side effects because of the choice of language (I am using C++ in the project I am interested in introducing this). ``` class IView { public: IView(){} virtual ~IView(){} virtual void showResult(const QString &text)=0; }; class Presenter { public: Presenter(IView *view){ m_View = view; } ~Presenter(){} void buttonPressed(){ QString text; // Evaluate text m_View->showResult(text); } private: IView *m_View; } // Multiple inheritance. Is this OK? class MyView : public QDialog, public IView { public: MyView(){ m_Presenter = new Presenter(this); m_Button = new QPushbutton(this); m_Label = new QLabel(this); // Ui event handled inside view but then directly // propagated to the Presenter connect(m_Button,SIGNAL(clicked()),this,SLOT(buttonPressed())); } ~MyView(){ delete m_Presenter; // Qt will automatically delete m_Button and m_Label; } void showResult(const QString &text){ m_Label->setText(text); } protected slots: void buttonPressed(){ m_Presenter->buttonPressed(); } private: Presenter *m_Presenter; QPushbutton *m_Button; QLabel *m_Label; } class TestView : public IView { public: TestView(){} ~TestView(){} void showResult(const QString &text){ m_LabelText = text; } QString getResult(){ return m_LabelText; } private: QString m_LabelText; } // Test code TestView view; Presenter presenter(&view); presenter.buttonPressed(); EXPECT_EQ(view.getResult(),"Expected Result"); // Procuction code MyView view; view.show(); ``` Now this is what I got by following the [initial work on the Humble dialog by Feathers](http://www.objectmentor.com/resources/articles/TheHumbleDialogBox.pdf). The approach that I would get from [Fowler's implentation](http://codebetter.com/blogs/jeremy.miller/pages/129546.aspx) would be to avoid creating the instance of the Presenter class in the constructor of MyView but pass it as a parameter instead so the production code would look like the test code. I personally like the approach I present here. So, * Is it meant to be used with multiple inheritance (see my comment in MyView class)? * Should the events be propagated directly to the Presenter or should they be handled in the view that will call the respective presenter action (as I have done here to avoid having to make the Presenter a QObject so it can handle UI events)? * Are there any other remarks?
When you do multiple inheritance with QObjects, the first class in the inheritance list needs to be the QObject-derived class. This is only strictly required if you plan to add signals and slots to your class, but is good practice anyway. So your class declaration: class MyView : public IView , public QDialog { needs to become this instead: class MyView : public QDialog , public IView { Again, this will only bite you if you ever add a slot or signal to "MyView". Other than that, I think this is a fine implementation, albeit huge amounts of overkill for a dialog. :) I'm using Fowler's MVP with Qt, and it's working okay. Things are more testable (nUnit style), but it is a bit more complex IMO.
239,463
<p>I have an application that behaves oddly, and just to verify, I'd like to see which security zone it is currently running under.</p> <p>I've found the System.Security.SecurityZone enum, but can't seem to find anything that will return which of these I'm running under.</p> <p>Does anyone have any tips?</p> <p>Basically I want to find out if my application is running in MyComputer, Intranet, Internet, Untrusted, Trusted, etc.</p> <hr> <p><strong>Edit:</strong> Here's the minor test-app I wrote to find this code, thanks to <a href="https://stackoverflow.com/users/2525/blowdart">@blowdart</a>.</p> <pre><code>using System; using System.Reflection; namespace zone_check { class Program { static void Main(string[] args) { Console.WriteLine(".NET version: " + Environment.Version); foreach (Object ev in Assembly.GetExecutingAssembly().Evidence) { if (ev is System.Security.Policy.Zone) { System.Security.Policy.Zone zone = (System.Security.Policy.Zone)ev; Console.WriteLine("Security zone: " + zone.SecurityZone); break; } } } } } </code></pre>
[ { "answer_id": 239471, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 4, "selected": true, "text": "<p>You need to look at the CAS evidence for the current assembly;</p>\n\n<p>this.GetType().Assembly.Evidence</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.assembly.evidence.aspx\" rel=\"noreferrer\">Assembly.Evidence</a> is a property <a href=\"http://msdn.microsoft.com/en-us/library/system.security.policy.evidence.aspx\" rel=\"noreferrer\">Evidence</a> object. From this you can <a href=\"http://www.improve.dk/blog/2008/06/11/analyzing-assembly-evidence\" rel=\"noreferrer\">enumerate the evidence</a> and look for the zone which appears as a &lt;System.Security.Policy.Zone&gt; element.</p>\n" }, { "answer_id": 13532405, "author": "thejaeck.net", "author_id": 1427893, "author_profile": "https://Stackoverflow.com/users/1427893", "pm_score": -1, "selected": false, "text": "<p>You can also use </p>\n\n<pre><code>Evidence e = Thread.CurrentThread.GetType().Assembly.Evidence;\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code>this.GetType().Assembly.Evidence\n</code></pre>\n" }, { "answer_id": 19205682, "author": "György Balássy", "author_id": 421501, "author_profile": "https://Stackoverflow.com/users/421501", "pm_score": 2, "selected": false, "text": "<p>In .NET 3.5 you can simplify the code with LINQ:</p>\n\n<pre><code>Zone z = a.Evidence.OfType&lt;Zone&gt;().First();\n</code></pre>\n\n<p>From .NET 4.0 you have a convenient <code>GetHostEvidence</code> method:</p>\n\n<pre><code>Zone z = Assembly.GetExecutingAssembly().Evidence.GetHostEvidence&lt;Zone&gt;();\n</code></pre>\n\n<p>Note that from .NET 4.0 evidence classes derive from the <code>EvidenceBase</code> base class.</p>\n\n<p>HTH,\nGyörgy</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
I have an application that behaves oddly, and just to verify, I'd like to see which security zone it is currently running under. I've found the System.Security.SecurityZone enum, but can't seem to find anything that will return which of these I'm running under. Does anyone have any tips? Basically I want to find out if my application is running in MyComputer, Intranet, Internet, Untrusted, Trusted, etc. --- **Edit:** Here's the minor test-app I wrote to find this code, thanks to [@blowdart](https://stackoverflow.com/users/2525/blowdart). ``` using System; using System.Reflection; namespace zone_check { class Program { static void Main(string[] args) { Console.WriteLine(".NET version: " + Environment.Version); foreach (Object ev in Assembly.GetExecutingAssembly().Evidence) { if (ev is System.Security.Policy.Zone) { System.Security.Policy.Zone zone = (System.Security.Policy.Zone)ev; Console.WriteLine("Security zone: " + zone.SecurityZone); break; } } } } } ```
You need to look at the CAS evidence for the current assembly; this.GetType().Assembly.Evidence [Assembly.Evidence](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.evidence.aspx) is a property [Evidence](http://msdn.microsoft.com/en-us/library/system.security.policy.evidence.aspx) object. From this you can [enumerate the evidence](http://www.improve.dk/blog/2008/06/11/analyzing-assembly-evidence) and look for the zone which appears as a <System.Security.Policy.Zone> element.
239,465
<p>I have a setup project for a .NET Service Application which uses a .NET component which exposes a COM interface (COM callable wrapper / CCW). To get the component working on a target machine, it has to be registered with</p> <blockquote> <p>regasm.exe /tlb /codebase component.dll</p> </blockquote> <p>The /tlb switch to generate the typelib is mandatory in this case, otherwise I can't create objects from that assembly.</p> <p>The question is, how can I configure my Visual Studio 2008 Setup-Project to register this assembly with a call to regasm /tlb ?</p>
[ { "answer_id": 239641, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Your service should have an Installer class.\nRegister to the OnAfterInstall event and call RegAsm: the path should be computed from the Windows directory and tied to a specific .Net version.</p>\n" }, { "answer_id": 446509, "author": "Wolfwyrd", "author_id": 15570, "author_profile": "https://Stackoverflow.com/users/15570", "pm_score": 2, "selected": false, "text": "<ol>\n<li>In your main project (the one containing the class you want to register), right click the project file and select Add / New Item and select Installer Class. Call it something like clsRegisterDll.cs</li>\n<li>In the designer that appears, click 'Click here to switch to code view' or right click the clsRegisterDll.cs file in solution explorer and select View Code</li>\n<li><p>Override the Install, Commit and Uninstall methods adding:</p>\n\n<p>// Get the location of regasm\nstring regasmPath = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory() + @\"regasm.exe\";\n// Get the location of our DLL\nstring componentPath = typeof(RegisterAssembly).Assembly.Location;\n// Execute regasm<br>\nSystem.Diagnostics.Process.Start(regasmPath, \"/codebase /tlb \\\"\" + componentPath + \"\\\"\");</p>\n\n<p>Swap /codebase /tlb for /u in the uninstall action.</p></li>\n<li>Compile your project</li>\n<li>In your installer, make sure you have added your dll to the Application Folder, and then right-click the installer project and select View / Custom Actions</li>\n<li>Right-click Install, and then click Add Custom Action</li>\n<li>Double click on Application Folder, and then on your dll</li>\n<li>Do the same for the Commit action</li>\n<li>Build and test your installer</li>\n</ol>\n\n<p>A walkthrough with an actual class for you to try can be found at: <a href=\"http://leon.mvps.org/DotNet/RegasmInstaller.html\" rel=\"nofollow noreferrer\">http://leon.mvps.org/DotNet/RegasmInstaller.html</a></p>\n" }, { "answer_id": 1883517, "author": "Sean Gough", "author_id": 12842, "author_profile": "https://Stackoverflow.com/users/12842", "pm_score": 5, "selected": true, "text": "<p>You can lose the manual call to regasm.exe by using System.Runtime.InteropServices.RegistrationServices instead:</p>\n\n<pre><code>[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]\npublic override void Install(IDictionary stateSaver)\n{\nbase.Install(stateSaver);\n\nRegistrationServices regsrv = new RegistrationServices();\nif (!regsrv.RegisterAssembly(GetType().Assembly, AssemblyRegistrationFlags.SetCodeBase))\n{\n throw new InstallException(\"Failed to register for COM Interop.\");\n}\n\n}\n\n[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)]\npublic override void Uninstall(IDictionary savedState)\n{\nbase.Uninstall(savedState);\n\nRegistrationServices regsrv = new RegistrationServices();\nif (!regsrv.UnregisterAssembly(GetType().Assembly))\n{\n throw new InstallException(\"Failed to unregister for COM Interop.\");\n}\n}\n</code></pre>\n\n<p>This also unregisters the library upon uninstall.</p>\n" }, { "answer_id": 7189966, "author": "user911989", "author_id": 911989, "author_profile": "https://Stackoverflow.com/users/911989", "pm_score": 1, "selected": false, "text": "<p>I initially tried running regasm from the installer process (before I saw this posting). Trying to run regasm , and handling all the errors was problematic - even without trying to handle elevated privileges for Windows 7.</p>\n\n<p>Using <code>Runtime.InteropServices.RegistrationServices.RegisterAssembly</code> was much cleaner and provided a much better error trapping.</p>\n" }, { "answer_id": 56818730, "author": "klasyc", "author_id": 907675, "author_profile": "https://Stackoverflow.com/users/907675", "pm_score": 0, "selected": false, "text": "<p>Visual Studio installer makes only COM class registration, but does not make the type library generation and registration (this is what <code>/tlb</code> switch at <code>regasm.exe does</code>) by default. At least in Visual Studio 2017 it is enough to generate the type library in the post-build steps of DLL to be registered using <code>Tlbexp.exe</code> utility. </p>\n\n<p>If the installer project discovers a file with extension <code>.tlb</code> in the same directory and with the same name as the library you are installing, it automatically includes it to the setup project and makes the registration steps during the installation. Of course it is also possible to generate the <code>.tlb</code> file by hand and include it in the setup project (and set its Register property to <code>vsdrfCOM</code>).</p>\n\n<p>Here is a <a href=\"https://www.red-gate.com/simple-talk/dotnet/visual-studio/build-and-deploy-a-.net-com-assembly/\" rel=\"nofollow noreferrer\">great article</a> about C# and COM interface and the information above come from its section called Deployment.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25727/" ]
I have a setup project for a .NET Service Application which uses a .NET component which exposes a COM interface (COM callable wrapper / CCW). To get the component working on a target machine, it has to be registered with > > regasm.exe /tlb /codebase component.dll > > > The /tlb switch to generate the typelib is mandatory in this case, otherwise I can't create objects from that assembly. The question is, how can I configure my Visual Studio 2008 Setup-Project to register this assembly with a call to regasm /tlb ?
You can lose the manual call to regasm.exe by using System.Runtime.InteropServices.RegistrationServices instead: ``` [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)] public override void Install(IDictionary stateSaver) { base.Install(stateSaver); RegistrationServices regsrv = new RegistrationServices(); if (!regsrv.RegisterAssembly(GetType().Assembly, AssemblyRegistrationFlags.SetCodeBase)) { throw new InstallException("Failed to register for COM Interop."); } } [System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand)] public override void Uninstall(IDictionary savedState) { base.Uninstall(savedState); RegistrationServices regsrv = new RegistrationServices(); if (!regsrv.UnregisterAssembly(GetType().Assembly)) { throw new InstallException("Failed to unregister for COM Interop."); } } ``` This also unregisters the library upon uninstall.
239,486
<p>I want to convert an XML document containing many elements within a node (around 150) into another XML document with a slightly different schema but mostly with the same element names. Now do I have to manually map each element/node between the 2 documents. For that I will have to hardcode 150 lines of mapping and element names. Something like this: </p> <pre><code>XElement newOrder = new XElement("Order"); newOrder.Add(new XElement("OrderId", (string)oldOrder.Element("OrderId")), newOrder.Add(new XElement("OrderName", (string)oldOrder.Element("OrderName")), ............... ............... ...............and so on </code></pre> <p>The newOrder document may contain additional nodes which will be set to null if nothing is found for them in the oldOrder. So do I have any other choice than to hardcode 150 element names like orderId, orderName and so on... Or is there some better more maintainable way?</p>
[ { "answer_id": 239515, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 5, "selected": true, "text": "<p>Use an <a href=\"http://www.w3schools.com/xsl/xsl_transformation.asp\" rel=\"noreferrer\">XSLT transform</a> instead. You can use the built-in .NET <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xsl.xslcompiledtransform.aspx\" rel=\"noreferrer\">XslCompiledTransform</a> to do the transformation. Saves you from having to type out stacks of code. If you don't already know XSL/XSLT, then learning it is something that'll bank you CV :)</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 239519, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 1, "selected": false, "text": "<p>Use an XSLT transformation to translate your old xml document into the new format. </p>\n" }, { "answer_id": 239997, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>XElement.Add has an <a href=\"http://msdn.microsoft.com/en-us/library/bb345077.aspx\" rel=\"nofollow noreferrer\">overload</a> that takes object[].</p>\n\n<pre><code>List&lt;string&gt; elementNames = GetElementNames();\n\nnewOrder.Add(\n elementNames\n .Select(name =&gt; GetElement(name, oldOrder))\n .Where(element =&gt; element != null)\n .ToArray()\n );\n</code></pre>\n\n<p>//</p>\n\n<pre><code>public XElement GetElement(string name, XElement source)\n{\n XElement result = null;\n XElement original = source.Elements(name).FirstOrDefault();\n if (original != null)\n {\n result = new XElement(name, (string)original)\n }\n return result;\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239486", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688440/" ]
I want to convert an XML document containing many elements within a node (around 150) into another XML document with a slightly different schema but mostly with the same element names. Now do I have to manually map each element/node between the 2 documents. For that I will have to hardcode 150 lines of mapping and element names. Something like this: ``` XElement newOrder = new XElement("Order"); newOrder.Add(new XElement("OrderId", (string)oldOrder.Element("OrderId")), newOrder.Add(new XElement("OrderName", (string)oldOrder.Element("OrderName")), ............... ............... ...............and so on ``` The newOrder document may contain additional nodes which will be set to null if nothing is found for them in the oldOrder. So do I have any other choice than to hardcode 150 element names like orderId, orderName and so on... Or is there some better more maintainable way?
Use an [XSLT transform](http://www.w3schools.com/xsl/xsl_transformation.asp) instead. You can use the built-in .NET [XslCompiledTransform](http://msdn.microsoft.com/en-us/library/system.xml.xsl.xslcompiledtransform.aspx) to do the transformation. Saves you from having to type out stacks of code. If you don't already know XSL/XSLT, then learning it is something that'll bank you CV :) Good luck!
239,526
<p>How do I truncate output in BASH? </p> <p>For example, if I "du file.name" how do I just get the numeric value and nothing more?</p> <p>later addition:<br> all solutions work perfectly. I chose to accept the most enlightning "cut" answer because I prefer the simplest approach in bash files others are supposed to be able to read.</p>
[ { "answer_id": 239530, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": false, "text": "<pre><code>du | cut -f 1\n</code></pre>\n" }, { "answer_id": 239532, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 5, "selected": true, "text": "<p>If you know what the delimiters are then cut is your friend</p>\n\n<pre><code>du | cut -f1\n</code></pre>\n\n<p>Cut defaults to tab delimiters so in this case you are selecting the first field. </p>\n\n<p>You can change delimiters: cut -d ' ' would use a space as a delimiter. (from <a href=\"https://stackoverflow.com/users/18771/tomalak\">Tomalak</a>)</p>\n\n<p>You can also select individual character positions or ranges: </p>\n\n<pre><code>ls | cut -c1-2\n</code></pre>\n" }, { "answer_id": 239535, "author": "Mark Baker", "author_id": 11815, "author_profile": "https://Stackoverflow.com/users/11815", "pm_score": 3, "selected": false, "text": "<p>I'd recommend cut, as others have said. But another alternative that is sometimes useful because it allows any whitespace as separators, is to use awk:</p>\n\n<pre><code>du file.name | awk '{print $1}'\n</code></pre>\n" }, { "answer_id": 239803, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 1, "selected": false, "text": "<p>If you just want the number of bytes of a single file, use the <code>-s</code> operator.</p>\n\n<pre><code>SIZE=-s file.name\n</code></pre>\n\n<p>That gives you a different number than <code>du</code>, but I'm not sure how exactly you're using this.</p>\n\n<p>This has the advantage of not having to run <code>du</code>, and having <code>bash</code> get the size of the file directly.</p>\n\n<p>It's hard to answer questions like this in a vacuum, because we don't know how you're going to use the data. Knowing that might suggest an entirely different answer.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11813/" ]
How do I truncate output in BASH? For example, if I "du file.name" how do I just get the numeric value and nothing more? later addition: all solutions work perfectly. I chose to accept the most enlightning "cut" answer because I prefer the simplest approach in bash files others are supposed to be able to read.
If you know what the delimiters are then cut is your friend ``` du | cut -f1 ``` Cut defaults to tab delimiters so in this case you are selecting the first field. You can change delimiters: cut -d ' ' would use a space as a delimiter. (from [Tomalak](https://stackoverflow.com/users/18771/tomalak)) You can also select individual character positions or ranges: ``` ls | cut -c1-2 ```
239,537
<p>My Program overrides <code>public void paint(Graphics g, int x, int y);</code> in order to draw some stings using <code>g.drawString(someString, x+10, y+30);</code></p> <p>Now someString can be quite long and thus, it may not fit on one line.<br></p> <p>What is the best way to write the text on multiple line.<br> For instance, in a rectangle (x1, y1, x2, y2)?</p>
[ { "answer_id": 239539, "author": "Epaga", "author_id": 6583, "author_profile": "https://Stackoverflow.com/users/6583", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/awt/font/TextLayout.html\" rel=\"nofollow noreferrer\">java.awt.font.TextLayout</a> might be helpful. Here's a snippet of their example code:</p>\n\n<pre><code> Graphics2D g = ...;\n Point2D loc = ...;\n Font font = Font.getFont(\"Helvetica-bold-italic\");\n FontRenderContext frc = g.getFontRenderContext();\n TextLayout layout = new TextLayout(\"This is a string\", font, frc);\n layout.draw(g, (float)loc.getX(), (float)loc.getY());\n\n Rectangle2D bounds = layout.getBounds();\n bounds.setRect(bounds.getX()+loc.getX(),\n bounds.getY()+loc.getY(),\n bounds.getWidth(),\n bounds.getHeight());\n g.draw(bounds);\n</code></pre>\n\n<p>Otherwise you could always use a Swing text element to do the job for you, just pass in the Graphics you want it to paint into.</p>\n" }, { "answer_id": 239605, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 2, "selected": false, "text": "<p>Incrementally build your string, one word at a time, using Epaga's method to find the length of your string. Once the length is longer than your rectangle, remove the last word and print. Repeat until you run out of words.</p>\n\n<p>It sounds like a bad algorithm, but for each line, it's really O(screenWidth/averageCharacterWidth) => O(1).</p>\n\n<p>Still, use a StringBuffer to build your string!</p>\n" }, { "answer_id": 239750, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 4, "selected": true, "text": "<p>Thanks to Epaga's hint and a couple of examples on the Net (not so obvious to find! I used mainly <a href=\"http://www.roseindia.net/java/example/java/swing/graphics2D/line-break-text-layout.shtml\" rel=\"noreferrer\" title=\"Break a Line for text layout\">Break a Line for text layout</a>), I could make a component to display wrapped text. It is incomplete, but at least it shows the intended effect.</p>\n\n<pre><code>class TextContainer extends JPanel\n{\n private int m_width;\n private int m_height;\n private String m_text;\n private AttributedCharacterIterator m_iterator;\n private int m_start;\n private int m_end;\n\n public TextContainer(String text, int width, int height)\n {\n m_text = text;\n m_width = width;\n m_height = height;\n\n AttributedString styledText = new AttributedString(text);\n m_iterator = styledText.getIterator();\n m_start = m_iterator.getBeginIndex();\n m_end = m_iterator.getEndIndex();\n }\n\n public String getText()\n {\n return m_text;\n }\n\n public Dimension getPreferredSize()\n {\n return new Dimension(m_width, m_height);\n }\n\n public void paint(Graphics g)\n {\n super.paintComponent(g);\n\n Graphics2D g2 = (Graphics2D) g;\n FontRenderContext frc = g2.getFontRenderContext();\n\n LineBreakMeasurer measurer = new LineBreakMeasurer(m_iterator, frc);\n measurer.setPosition(m_start);\n\n float x = 0, y = 0;\n while (measurer.getPosition() &lt; m_end)\n {\n TextLayout layout = measurer.nextLayout(m_width);\n\n y += layout.getAscent();\n float dx = layout.isLeftToRight() ?\n 0 : m_width - layout.getAdvance();\n\n layout.draw(g2, x + dx, y);\n y += layout.getDescent() + layout.getLeading();\n }\n }\n}\n</code></pre>\n\n<p>Just for fun, I made it fitting a circle (alas, no justification, it seems):</p>\n\n<pre><code>public void paint(Graphics g)\n{\n super.paintComponent(g);\n\n Graphics2D g2 = (Graphics2D) g;\n FontRenderContext frc = g2.getFontRenderContext();\n\n LineBreakMeasurer measurer = new LineBreakMeasurer(m_iterator, frc);\n measurer.setPosition(m_start);\n\n float y = 0;\n while (measurer.getPosition() &lt; m_end)\n {\n double ix = Math.sqrt((m_width / 2 - y) * y);\n float x = m_width / 2.0F - (float) ix;\n int width = (int) ix * 2;\n\n TextLayout layout = measurer.nextLayout(width);\n\n y += layout.getAscent();\n float dx = layout.isLeftToRight() ?\n 0 : width - layout.getAdvance();\n\n layout.draw(g2, x + dx, y);\n y += layout.getDescent() + layout.getLeading();\n }\n}\n</code></pre>\n\n<p>I am not too sure about dx computation, though.</p>\n" }, { "answer_id": 239770, "author": "michelemarcon", "author_id": 15173, "author_profile": "https://Stackoverflow.com/users/15173", "pm_score": 0, "selected": false, "text": "<p>You can use a JLabel and embed the text with html.</p>\n\n<pre><code>JLabel.setText(\"&lt;html&gt;\"+line1+\"&lt;br&gt;\"+line2);\n</code></pre>\n" }, { "answer_id": 10825957, "author": "msj121", "author_id": 318938, "author_profile": "https://Stackoverflow.com/users/318938", "pm_score": 1, "selected": false, "text": "<p>Had some trouble myself this is my solution:</p>\n\n<pre><code>Graphics2D g=....\nFontRenderContext frc = g.getFontRenderContext();\nTextLayout layout = new TextLayout(text, font, frc);\nString[] outputs = text.split(\"\\n\");\nfor(int i=0; i&lt;outputs.length; i++){\n g.drawString(outputs[i], 15,(int) (15+i*layout.getBounds().getHeight()+0.5));\n</code></pre>\n\n<p>Hope that helps.... simple but it works.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12860/" ]
My Program overrides `public void paint(Graphics g, int x, int y);` in order to draw some stings using `g.drawString(someString, x+10, y+30);` Now someString can be quite long and thus, it may not fit on one line. What is the best way to write the text on multiple line. For instance, in a rectangle (x1, y1, x2, y2)?
Thanks to Epaga's hint and a couple of examples on the Net (not so obvious to find! I used mainly [Break a Line for text layout](http://www.roseindia.net/java/example/java/swing/graphics2D/line-break-text-layout.shtml "Break a Line for text layout")), I could make a component to display wrapped text. It is incomplete, but at least it shows the intended effect. ``` class TextContainer extends JPanel { private int m_width; private int m_height; private String m_text; private AttributedCharacterIterator m_iterator; private int m_start; private int m_end; public TextContainer(String text, int width, int height) { m_text = text; m_width = width; m_height = height; AttributedString styledText = new AttributedString(text); m_iterator = styledText.getIterator(); m_start = m_iterator.getBeginIndex(); m_end = m_iterator.getEndIndex(); } public String getText() { return m_text; } public Dimension getPreferredSize() { return new Dimension(m_width, m_height); } public void paint(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; FontRenderContext frc = g2.getFontRenderContext(); LineBreakMeasurer measurer = new LineBreakMeasurer(m_iterator, frc); measurer.setPosition(m_start); float x = 0, y = 0; while (measurer.getPosition() < m_end) { TextLayout layout = measurer.nextLayout(m_width); y += layout.getAscent(); float dx = layout.isLeftToRight() ? 0 : m_width - layout.getAdvance(); layout.draw(g2, x + dx, y); y += layout.getDescent() + layout.getLeading(); } } } ``` Just for fun, I made it fitting a circle (alas, no justification, it seems): ``` public void paint(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; FontRenderContext frc = g2.getFontRenderContext(); LineBreakMeasurer measurer = new LineBreakMeasurer(m_iterator, frc); measurer.setPosition(m_start); float y = 0; while (measurer.getPosition() < m_end) { double ix = Math.sqrt((m_width / 2 - y) * y); float x = m_width / 2.0F - (float) ix; int width = (int) ix * 2; TextLayout layout = measurer.nextLayout(width); y += layout.getAscent(); float dx = layout.isLeftToRight() ? 0 : width - layout.getAdvance(); layout.draw(g2, x + dx, y); y += layout.getDescent() + layout.getLeading(); } } ``` I am not too sure about dx computation, though.
239,545
<p>I have a table that has a <code>processed_timestamp</code> column -- if a record has been processed then that field contains the datetime it was processed, otherwise it is null.</p> <p>I want to write a query that returns two rows:</p> <pre><code>NULL xx -- count of records with null timestamps NOT NULL yy -- count of records with non-null timestamps </code></pre> <p>Is that possible?</p> <p><strong>Update:</strong> The table is quite large, so efficiency is important. I could just run two queries to calculate each total separately, but I want to avoid hitting the table twice if I can avoid it.</p>
[ { "answer_id": 239548, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 6, "selected": false, "text": "<p>In MySQL you could do something like</p>\n\n<pre><code>SELECT \n IF(ISNULL(processed_timestamp), 'NULL', 'NOT NULL') as myfield, \n COUNT(*) \nFROM mytable \nGROUP BY myfield\n</code></pre>\n" }, { "answer_id": 239551, "author": "ADEpt", "author_id": 10105, "author_profile": "https://Stackoverflow.com/users/10105", "pm_score": 3, "selected": false, "text": "<p>If it's oracle then you can do:</p>\n\n<pre><code>select decode(field,NULL,'NULL','NOT NULL'), count(*)\nfrom table\ngroup by decode(field,NULL,'NULL','NOT NULL');\n</code></pre>\n\n<p>I'm sure that other DBs allow for similar trick.</p>\n" }, { "answer_id": 239553, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 5, "selected": false, "text": "<p>Try the following, it's vendor-neutral:</p>\n\n<pre><code>select\n 'null ' as type,\n count(*) as quant\n from tbl\n where tmstmp is null\nunion all\nselect\n 'not null' as type,\n count(*) as quant\n from tbl\n where tmstmp is not null\n</code></pre>\n\n<p>After having our local DB2 guru look at this, he concurs: none of the solutions presented to date (including this one) can avoid a full table scan (of the table if timestamp is not indexed, or of the indexotherwise). They all scan every record in the table exactly once. </p>\n\n<p>All the CASE/IF/NVL2() solutions do a null-to-string conversion for each row, introducing unnecessary load on the DBMS. This solution does not have that problem.</p>\n" }, { "answer_id": 239555, "author": "trunkc", "author_id": 1961117, "author_profile": "https://Stackoverflow.com/users/1961117", "pm_score": 6, "selected": true, "text": "<p>Oracle:</p>\n\n<p>group by nvl2(field, 'NOT NULL', 'NULL')</p>\n" }, { "answer_id": 239557, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 6, "selected": false, "text": "<p>In T-SQL (MS SQL Server), this works:</p>\n\n<pre><code>SELECT\n CASE WHEN Field IS NULL THEN 'NULL' ELSE 'NOT NULL' END FieldContent,\n COUNT(*) FieldCount\nFROM\n TheTable\nGROUP BY\n CASE WHEN Field IS NULL THEN 'NULL' ELSE 'NOT NULL' END\n</code></pre>\n" }, { "answer_id": 239564, "author": "Tom", "author_id": 3715, "author_profile": "https://Stackoverflow.com/users/3715", "pm_score": 2, "selected": false, "text": "<p>Another MySQL method is to use the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#operator_case\" rel=\"nofollow noreferrer\"><code>CASE</code> operator</a>, which can be generalised to more alternatives than <code>IF()</code>:</p>\n\n<pre><code>SELECT CASE WHEN processed_timestamp IS NULL THEN 'NULL' \n ELSE 'NOT NULL' END AS a,\n COUNT(*) AS n \n FROM logs \n GROUP BY a\n</code></pre>\n" }, { "answer_id": 239568, "author": "James Green", "author_id": 31736, "author_profile": "https://Stackoverflow.com/users/31736", "pm_score": 0, "selected": false, "text": "<p>I personally like Pax's solution, but if you absolutely require only one row returned (as I had recently), In MS SQL Server 2005/2008 you can \"stack\" the two queries using a CTE</p>\n\n<pre><code>with NullRows (countOf)\nAS\n(\n SELECT count(*) \n FORM table \n WHERE [processed_timestamp] IS NOT NULL\n)\nSELECT count(*) AS nulls, countOf\nFROM table, NullRows\nWHERE [processed_timestamp] IS NULL\nGROUP BY countOf\n</code></pre>\n\n<p>Hope this helps</p>\n" }, { "answer_id": 239733, "author": "Unsliced", "author_id": 2902, "author_profile": "https://Stackoverflow.com/users/2902", "pm_score": 0, "selected": false, "text": "<p>[T-SQL]: </p>\n\n<pre><code>select [case], count(*) tally\nfrom (\n select \n case when [processed_timestamp] is null then 'null'\n else 'not null'\n end [case]\n from myTable\n) a \n</code></pre>\n\n<p>And you can add into the case statement whatever other values you'd like to form a partition, e.g. today, yesterday, between noon and 2pm, after 6pm on a Thursday. </p>\n" }, { "answer_id": 239849, "author": "James Green", "author_id": 31736, "author_profile": "https://Stackoverflow.com/users/31736", "pm_score": 3, "selected": false, "text": "<p>Stewart,</p>\n\n<p>Maybe consider this solution. It is (also!) vendor non-specific.</p>\n\n<pre><code>SELECT count([processed_timestamp]) AS notnullrows, \n count(*) - count([processed_timestamp]) AS nullrows \nFROM table\n</code></pre>\n\n<p>As for efficiency, this avoids 2x index seeks/table scans/whatever by including the results on one row. If you absolutely require 2 rows in the result, two passes over the set may be unavoidable because of unioning aggregates.</p>\n\n<p>Hope this helps</p>\n" }, { "answer_id": 239957, "author": "Aleksey Otrubennikov", "author_id": 16209, "author_profile": "https://Stackoverflow.com/users/16209", "pm_score": 0, "selected": false, "text": "<pre><code>Select Sum(Case When processed_timestamp IS NULL\n Then 1\n Else 0\n End) not_processed_count,\n Sum(Case When processed_timestamp Is Not NULL\n Then 1\n Else 0\n End) processed_count,\n Count(1) total\nFrom table\n</code></pre>\n\n<p>Edit: didn't read carefully, this one returns a single row.</p>\n" }, { "answer_id": 242090, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 1, "selected": false, "text": "<p>In Oracle</p>\n\n<pre><code>SELECT COUNT(*), COUNT(TIME_STAMP_COLUMN)\nFROM TABLE;\n</code></pre>\n\n<p>count(*) returns the count of all rows</p>\n\n<p>count(column_name) returns the number of rows which are not NULL, so</p>\n\n<pre><code>SELECT COUNT(*) - COUNT(TIME_STAMP_COLUMN) NUL_COUNT,\n COUNT(TIME_STAMP_COLUMN) NON_NUL_COUNT\nFROM TABLE\n</code></pre>\n\n<p>ought to do the job.</p>\n\n<p>If the column is indexed, you might end up with some sort of range scan and avoid actually reading the table.</p>\n" }, { "answer_id": 242092, "author": "dkretz", "author_id": 31641, "author_profile": "https://Stackoverflow.com/users/31641", "pm_score": 1, "selected": false, "text": "<p>If your database has an efficient COUNT(*) function for a table, you could COUNT whichever is the smaller number, and subtract.</p>\n" }, { "answer_id": 35577336, "author": "Jatin Sanghvi", "author_id": 470119, "author_profile": "https://Stackoverflow.com/users/470119", "pm_score": 2, "selected": false, "text": "<p>SQL Server (starting with 2012):</p>\n\n<pre><code>SELECT IIF(ISDATE(processed_timestamp) = 0, 'NULL', 'NON NULL'), COUNT(*)\nFROM MyTable\nGROUP BY ISDATE(processed_timestamp);\n</code></pre>\n" }, { "answer_id": 35764161, "author": "Refael", "author_id": 1916002, "author_profile": "https://Stackoverflow.com/users/1916002", "pm_score": 2, "selected": false, "text": "<p>Another way in T-sql (sql-server)</p>\n\n<pre><code>select count(case when t.timestamps is null \n then 1 \n else null end) NULLROWS,\n count(case when t.timestamps is not null \n then 1 \n else null end) NOTNULLROWS\nfrom myTable t \n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6408/" ]
I have a table that has a `processed_timestamp` column -- if a record has been processed then that field contains the datetime it was processed, otherwise it is null. I want to write a query that returns two rows: ``` NULL xx -- count of records with null timestamps NOT NULL yy -- count of records with non-null timestamps ``` Is that possible? **Update:** The table is quite large, so efficiency is important. I could just run two queries to calculate each total separately, but I want to avoid hitting the table twice if I can avoid it.
Oracle: group by nvl2(field, 'NOT NULL', 'NULL')
239,546
<pre><code>$sql = "INSERT INTO images (path, useremail, approved, flagged,caption,date) VALUES ('$target','$email',0,0, '$caption','$b')"; $sql1 = "INSERT INTO users (name, email, phone) VALUES ('$peoplename','$email','$phone')" $conn-&gt;execute($sql, $sql1); </code></pre> <p>Above is the code Ι am using to try and write to 2 tables. Before Ι introduced connection through the COM object Ι could do this not a problem but now Ι cannot do it for some reason. Any help would be appreciated.</p>
[ { "answer_id": 239554, "author": "Sani Singh Huttunen", "author_id": 26742, "author_profile": "https://Stackoverflow.com/users/26742", "pm_score": 0, "selected": false, "text": "<p>You have a missing semicolon on the second line.</p>\n" }, { "answer_id": 239563, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 3, "selected": false, "text": "<p>I thought that the second parameter was for passing parameters to be bound to the query.</p>\n\n<p>If the server lets you execute two sql statements in one go maybe this would work. (added a terminating semi-colon at the end of each query and concatenated both queries together as one string.)</p>\n\n<pre><code>$sql = \"INSERT INTO images (path, useremail, approved, flagged,caption,date) VALUES ('$target','$email',0,0, '$caption','$b');\";\n$sql1 = \"INSERT INTO users (name, email, phone) VALUES ('$peoplename','$email','$phone');\";\n$conn-&gt;execute($sql . $sql1); \n</code></pre>\n\n<p>otherwise the obvious</p>\n\n<pre><code> $conn-&gt;execute($sql); \n $conn-&gt;execute($sql1); \n</code></pre>\n" }, { "answer_id": 239565, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 0, "selected": false, "text": "<p>Why not put it as one SQL statement?</p>\n\n<pre><code>$sql = \"INSERT INTO images (path, useremail, approved, flagged,caption,date) VALUES ('$target','$email',0,0, '$caption','$b'); INSERT INTO users (name, email, phone) VALUES ('$peoplename','$email','$phone')\";\n$conn-&gt;execute($sql);\n</code></pre>\n" }, { "answer_id": 239594, "author": "James Green", "author_id": 31736, "author_profile": "https://Stackoverflow.com/users/31736", "pm_score": 0, "selected": false, "text": "<p>Drew, I'm not a PHP guru, but one thing I see missing in the other answers is transactional integrity. Even stacking the two INSERTs in the same string seperated with a semicolon does ensure atomicity of the action (if that is important to you :-)</p>\n\n<p>Hope this helps</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` $sql = "INSERT INTO images (path, useremail, approved, flagged,caption,date) VALUES ('$target','$email',0,0, '$caption','$b')"; $sql1 = "INSERT INTO users (name, email, phone) VALUES ('$peoplename','$email','$phone')" $conn->execute($sql, $sql1); ``` Above is the code Ι am using to try and write to 2 tables. Before Ι introduced connection through the COM object Ι could do this not a problem but now Ι cannot do it for some reason. Any help would be appreciated.
I thought that the second parameter was for passing parameters to be bound to the query. If the server lets you execute two sql statements in one go maybe this would work. (added a terminating semi-colon at the end of each query and concatenated both queries together as one string.) ``` $sql = "INSERT INTO images (path, useremail, approved, flagged,caption,date) VALUES ('$target','$email',0,0, '$caption','$b');"; $sql1 = "INSERT INTO users (name, email, phone) VALUES ('$peoplename','$email','$phone');"; $conn->execute($sql . $sql1); ``` otherwise the obvious ``` $conn->execute($sql); $conn->execute($sql1); ```
239,556
<p>We are replacing the exception handling system in our app in order to conform to Vista certification, but the problem is how to force certain exceptions to be thrown, so that we can check the response.</p> <p>Unfortunately the whole app was written without taking into consideration proper layering, abstraction or isolation principles, and within the timeframe introducing mocking and unit testing is out of the question :(</p> <p>My idea is to introduce code which will throw a particular exception, either through a compiler directive or by respecting a value in the config file. We can then just run the app as normal and manually check how the exception is handled.</p> <p>Just thought I'd put it out there and see if the SO community can think of anything better!</p> <p>Cheers</p>
[ { "answer_id": 239559, "author": "Ben Collins", "author_id": 3279, "author_profile": "https://Stackoverflow.com/users/3279", "pm_score": 1, "selected": false, "text": "<p>Introduce this code:</p>\n\n<pre><code>throw new Exception(\"test\");\n</code></pre>\n\n<p>If you need the exception to always be there (i.e., not just test code), then hide it behind a command-line parameter.</p>\n\n<pre><code>C:\\Users\\Dude&gt; myapp.exe /x\n</code></pre>\n" }, { "answer_id": 239607, "author": "Morten Christiansen", "author_id": 4055, "author_profile": "https://Stackoverflow.com/users/4055", "pm_score": 0, "selected": false, "text": "<p>I might not have a clue about this but my first thought was to use aspect oriented programming to throw exceptions when certain code is run. spring.net has <a href=\"http://www.springframework.net/docs/1.2.0-RC1/reference/html/aop.html\" rel=\"nofollow noreferrer\">support</a> for this, though I don't know how well it works for your purpose. I wouldn't take my word on this but it's something to look into.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7140/" ]
We are replacing the exception handling system in our app in order to conform to Vista certification, but the problem is how to force certain exceptions to be thrown, so that we can check the response. Unfortunately the whole app was written without taking into consideration proper layering, abstraction or isolation principles, and within the timeframe introducing mocking and unit testing is out of the question :( My idea is to introduce code which will throw a particular exception, either through a compiler directive or by respecting a value in the config file. We can then just run the app as normal and manually check how the exception is handled. Just thought I'd put it out there and see if the SO community can think of anything better! Cheers
Introduce this code: ``` throw new Exception("test"); ``` If you need the exception to always be there (i.e., not just test code), then hide it behind a command-line parameter. ``` C:\Users\Dude> myapp.exe /x ```
239,601
<p>How would you model booked hotel room to guests relationship (in PostgreSQL, if it matters)? A room can have several guests, but at least one.</p> <p>Sure, one can relate guests to bookings with a foreign key <code>booking_id</code>. But how do you enforce on the DBMS level that a room must have at least one guest?</p> <p>May be it's just impossible?</p>
[ { "answer_id": 239616, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 0, "selected": false, "text": "<p>What about a room which has not been rented out? What you're looking for are reservations and a reservation presumably needs at least one guest on it.</p>\n\n<p>I think what you're asking is whether you can guarantee that a reservation record is not added unless you have at least one guest for and you can't add a guest without a reservation. It's a bit of a Catch-22 for most DBMSs systems.</p>\n" }, { "answer_id": 239617, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 1, "selected": false, "text": "<p>You could designate one of the guests as the \"primary\" guest and have it map to a column on the Rooms table. Of course, this is a ridiculous rule for a hotel, where it's perfectly valid to have a room with 0 guests (I very well could pay for a room and not stay there)...</p>\n" }, { "answer_id": 239618, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 2, "selected": false, "text": "<p>In this context I suggest that the entity you are modeling is in fact a <strong>BOOKING</strong> - a single entity - rather than two entities of room and guest.</p>\n\n<p>So the table would be something like</p>\n\n<pre><code>BOOKING\n-------\nbooking id\nroom id\nguest id (FK to table of guests for booking)\nfirst date of occupancy\nlast date of occupancy\n</code></pre>\n\n<p>Where guest id is not nullable,\nand you have another table to hold guests per booking...</p>\n\n<pre><code>GUESTS\n------\nguest id\ncustomer id (FK to customer table)\n</code></pre>\n" }, { "answer_id": 239635, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 4, "selected": true, "text": "<p>Actually, if you read the question, it states booked hotel rooms. This is quite easy to do as follows:</p>\n\n<pre><code>Rooms:\n room_id primary key not null\n blah\n blah\n\nGuests:\n guest_id primary key not null\n yada\n yada\n\nBookedRooms:\n room_id primary key foreign key (Rooms:room_id)\n primary_guest_id foreign key (Guests:guest_id)\n\nOtherGuestsInRooms:\n room_id foreign key (BookedRooms:room_id)\n guest_id foreign key (Guests:guest_id)\n</code></pre>\n\n<p>That way, you can enforce a booked room having at least one guest while the OtherGuests is a 0-or-more relationship. You can't create a booked room without a guest and you can't add other guests without the booked room.</p>\n\n<p>It's the same sort of logic you follow if you want an n-to-n relationship, which should be normalized to a separate table containing a 1-to-n and an n-to-1 with the two tables.</p>\n" }, { "answer_id": 239636, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 1, "selected": false, "text": "<p>I think what you mean is that a room BOOKING is for at least one guest. ANSI standard SQL would allow you to express the constraint as an ASSERTION something like:</p>\n\n<pre><code>create assertion x as check\n (not exists (select * from booking b\n where not exists\n (select * from booking_guest bg\n where bg.booking_id = b.booking_id)));\n</code></pre>\n\n<p>However, I don't suppose Postgres supports that (I'm not sure any current DBMS does).</p>\n\n<p>There is a way using materialized views and check constraints, but I've never seen this done in practice:</p>\n\n<p>1) Create a materialised view as</p>\n\n<pre><code>select booking_id from booking b\nwhere not exists \n (select * from booking_guest bg \n where bg.booking_id = b.booking_id);\n</code></pre>\n\n<p>2) Add a check constraint to the materialized view:</p>\n\n<pre><code>check (boooking_id is null)\n</code></pre>\n\n<p>This constraint will fail if ever the materialized view is not empty, i.e. if there is a booking with no associated guest. However, you would need to be careful about the performance of this approach.</p>\n" }, { "answer_id": 3716252, "author": "edgerunner", "author_id": 311941, "author_profile": "https://Stackoverflow.com/users/311941", "pm_score": 0, "selected": false, "text": "<p>I'd say you should create a <code>bookings</code> table with three primary keys. But instead of referring to bookings rooms, you can refer to a <code>beds</code> table.</p>\n\n<pre><code>bookings:\n bed_id: foreign_key primary\n guest_id: foreign_key primary\n day: date primary\n bill_id: foreign_key not null\n\nbeds:\n room_id: foreign_key primary\n</code></pre>\n\n<p>Since being the <code>primary</code> implies being required, and since this is the only way a guest and a room can be related, it makes sure that there cannot be a booking without a guest.</p>\n\n<p>Notice that there is only one <code>day</code> field. This requires that you create a booking for every day a guest will stay in a room, but also ensures that nothing will be accidentally booked twice. A bed can be booked by only one customer on any given day(which is not true for rooms)</p>\n\n<p>The <code>bill_id</code> is there so that you can refer a booking to a specific record for a bill, which can also be referenced by other things such as minibar expenses.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6430/" ]
How would you model booked hotel room to guests relationship (in PostgreSQL, if it matters)? A room can have several guests, but at least one. Sure, one can relate guests to bookings with a foreign key `booking_id`. But how do you enforce on the DBMS level that a room must have at least one guest? May be it's just impossible?
Actually, if you read the question, it states booked hotel rooms. This is quite easy to do as follows: ``` Rooms: room_id primary key not null blah blah Guests: guest_id primary key not null yada yada BookedRooms: room_id primary key foreign key (Rooms:room_id) primary_guest_id foreign key (Guests:guest_id) OtherGuestsInRooms: room_id foreign key (BookedRooms:room_id) guest_id foreign key (Guests:guest_id) ``` That way, you can enforce a booked room having at least one guest while the OtherGuests is a 0-or-more relationship. You can't create a booked room without a guest and you can't add other guests without the booked room. It's the same sort of logic you follow if you want an n-to-n relationship, which should be normalized to a separate table containing a 1-to-n and an n-to-1 with the two tables.
239,622
<p>We have an x-files problem with our .NET application. Or, rather, hybrid Win32 and .NET application.</p> <p>When it attempts to communicate with Oracle, it just dies. Vanishes. Goes to the big black void in the sky. No event log message, no exception, no nothing.</p> <p>If we simply ask the application to talk to a MS SQL Server instead, which has the effect of replacing the usage of OracleConnection and related classes with SqlConnection and related classes, it works as expected.</p> <p>Today we had a breakthrough.</p> <p>For some reason, a customer had figured out that by placing all the application files in a directory on his desktop, it worked as expected with Oracle as well. Moving the directory down to the root of the drive, or in C:\Temp or, well, around a bit, made the crash reappear.</p> <p>Basically it was 100% reproducable that the application worked if run from directory on desktop, and failed if run from directory in root.</p> <p>Today we figured out that the difference that counted was wether there was a space in the directory name or not.</p> <p>So, these directories would work:</p> <pre><code>C:\Program Files\AppDir\Executable.exe C:\Temp Lemp\AppDir\Executable.exe C:\Documents and Settings\someuser\Desktop\AppDir\Executable.exe </code></pre> <p>whereas these would not:</p> <pre><code>C:\CompanyName\AppDir\Executable.exe C:\Programfiler\AppDir\Executable.exe &lt;-- Program Files in norwegian C:\Temp\AppDir\Executable.exe </code></pre> <p>I'm hoping someone reading this has seen similar behavior and have a "aha, you need to twiddle the frob on the oracle glitz driver configuration" or similar.</p> <p>Anyone?</p> <hr> <p><strong>Followup #1:</strong> Ok, I've processed the procmon output now, both files from when I hit the button that attempts to open the window that triggers the cascade failure, and I've noticed that they keep track mostly, there's some smallish differences near the top of both files, and they they keep track a long way down.</p> <p>However, when one run fails, the other keeps going and the next few lines of the log output are these:</p> <pre><code>ReadFile C:\oracle\product\10.2.0\db_1\BIN\orageneric10.dll SUCCESS Offset: 274 432, Length: 32 768, I/O Flags: Non-cached, Paging I/O, Synchronous Paging I/O ReadFile C:\oracle\product\10.2.0\db_1\BIN\orageneric10.dll SUCCESS Offset: 233 472, Length: 32 768, I/O Flags: Non-cached, Paging I/O, Synchronous Paging I/O </code></pre> <p>After this, the working run continues to execute, and the other touches the mscorwks.dll files a few times before threads close down and the app closes. Thus, the failed run does not touch the above files.</p> <hr> <p><strong>Followup #2:</strong> Figured I'd try to upgrade the oracle client drivers, but 10.2.0.1 is apparently the highest version available for Windows 2003 server and XP clients.</p> <hr> <p><strong>Followup #3:</strong> Well, we've ended up with a black-box solution. Basically we found that the problem is somewhere related to <a href="http://www.devexpress.com/Products/NET/ORM/" rel="nofollow noreferrer">XPO</a> and Oracle. XPO has a system-table it manages, called XPObjectType, with three columns: Oid, TypeName and AssemblyName. Due to how Oracle is configured in the databases we talk to, the column names were OID, TYPENAME and ASSEMBLYNAME. This would ordinarily not be a problem, except that XPO talks to the schema information directly and checks if the table is there with the right column names, and XPO doesn't handle case differences so it sees a XPObjectType table with three unknown columns and none of those it expects.</p> <p>Exactly what XPO does now I don't really know, but if I dropped this table, and recreated it with the right case, using double quotes around all the column names to get the case right, the problem doesn't crop up.</p> <p>Exactly where the space in the folder name comes into this, I still have no idea, but this problem had two tiers:</p> <ol> <li>Stop the application from crashing at our customers, short-term solution</li> <li>Fix the bug, long-term solution</li> </ol> <p>Right now tier 1 is solved, tier 2 will be put back into the queue for now and prioritized. We're facing some bigger changes to our data tier anyway so this might not be a problem we need to solve, at least if all our Oracle-customers verify that the table-fix actually gets rid of the problem.</p> <p>I'll accept the answer by <a href="https://stackoverflow.com/users/24995/dave-markle">Dave Markle</a> since though Process Monitor (the big brother of File Monitor) didn't actually pinpoint the problem, I was able to use it to determine that after my breakpoint in user-code where XPO had built up the query for this table, no I/O happened until all the entries for the application closing down was logged, which led me to believe it was this table that was the culprit, or at least influenced the problem somehow.</p> <p>If I manage to get to the real cause of this, I'll update the post.</p>
[ { "answer_id": 239659, "author": "Dave Markle", "author_id": 24995, "author_profile": "https://Stackoverflow.com/users/24995", "pm_score": 3, "selected": true, "text": "<p>Here's what I would do. First, TRIPLE-check that you're seeing the behavior you think you're seeing. I can see this happening the other way around by not using System.IO.Path to concatenate paths, but not like you're seeing it. Triple-check that the file permissions make sense.</p>\n\n<p>Next, download <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx\" rel=\"nofollow noreferrer\">Filemon</a> from MS and watch what's happening on the filesystem as your program hits these troubled spots. You can filter out specific file activity (removing your anti-virus file activity, for example) to make everything look a bit cleaner while you do this. Look for file access errors using FileMon for both the success case and the error case for your program. That should point you to what file's being accessed and causing the problem. For example, if you see a <code>FILE_NOT_FOUND</code> error accessing a nonsense filename, you can be assured that you or the vendor are doing something wrong, possibly leading to your problem...</p>\n" }, { "answer_id": 239996, "author": "Rasmus Faber", "author_id": 5542, "author_profile": "https://Stackoverflow.com/users/5542", "pm_score": 1, "selected": false, "text": "<p>You should probably see if you can reproduce the problem it with a simple application that only tries to open a connection to Oracle. That way you can be 100% sure that the problem is with OracleConnection or the Oracle driver and not with your own code.</p>\n" }, { "answer_id": 1442070, "author": "Gary Myers", "author_id": 25714, "author_profile": "https://Stackoverflow.com/users/25714", "pm_score": 0, "selected": false, "text": "<p>You should get a medal for perseverance for that !.</p>\n\n<blockquote>\n <p>\"Exactly what XPO does now I don't\n really know, but if I dropped this\n table, and recreated it with the right\n case, using double quotes around all\n the column names to get the case\n right, the problem doesn't crop up.</p>\n \n <p>Exactly where the space in the folder\n name comes into this, I still have no\n idea\"</p>\n</blockquote>\n\n<p>The issues I get with spaces in names is that they generally interpret the bit before the space as the name and the rest as a parameter. If that is the case, then with the plain name it can see \"C\\Temp\" and it is a directory. With the spaced name, it gets \"C:\\Program Files\", looks for \"C:\\Program\" and that doesn't exist. It would fail, for example, to overwrite \"C:\\Temp\" but would succeed in writing \"C:\\Program\".\nWonder whether it would still fail with \"C:\\Program Files\" if there is a file or directory called \"C:\\Program\"</p>\n" }, { "answer_id": 2768642, "author": "Crocked", "author_id": 54344, "author_profile": "https://Stackoverflow.com/users/54344", "pm_score": 0, "selected": false, "text": "<p>I´d suspect the oracle client to be honest. Had a problem which was similar in it´s frustrating nature. </p>\n\n<p>If we installed on 64 bit machines the client would stop at start when connecting to oracle even though the app is 32 bit. We eventually tracked it down to the fact that a certain oracle client (Ora 10 had a problem with brackets in the path so a program running under program files would work under program files (x86) caused the crash. Updating the machine to use the 11G client fixed the problem but there were also some patches available from metalink which are not directly available. Whats strange in your case is that you get no exception but the behaviour of moving the application to a new folder fixes the issue in a similar way so it may be related.</p>\n\n<p>ORA-12154: TNS:could not resolve the connect identifier specified\nor\nORA-6413: Connection not open. </p>\n\n<p>Useful links <a href=\"http://blogs.msdn.com/debarchan/archive/2009/02/04/good-old-connectivity-issue.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/debarchan/archive/2009/02/04/good-old-connectivity-issue.aspx</a></p>\n\n<p>Details from Metalink below.</p>\n\n<p>Metalink Bug 3807408 Cannot externally authenticate user with quote in username</p>\n\n<p>Description\nIf an externally authenticated username contains a '(',')' or '='\nthen the user cannot be authenticated.\nAdditionally if a program name / path contains these characters it\nmay not be possible to connect .\neg: \n Windows clients installed in a directory \"C:\\Program Files (x86)\"\n fail to connect with \n ORA-12154: TNS:could not resolve the connect identifier specified</p>\n\n<p>The hallmark of this problem is that the Net trace (level 16) shows\nthe problem character/s replaced by a \"?\" in the trace.</p>\n\n<p>Workaround\n For the authentication problem:\n change username, \n or \n do not use remote OS authentication for those users</p>\n\n<p>For the program / directory issue:\n change the program/directory name</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
We have an x-files problem with our .NET application. Or, rather, hybrid Win32 and .NET application. When it attempts to communicate with Oracle, it just dies. Vanishes. Goes to the big black void in the sky. No event log message, no exception, no nothing. If we simply ask the application to talk to a MS SQL Server instead, which has the effect of replacing the usage of OracleConnection and related classes with SqlConnection and related classes, it works as expected. Today we had a breakthrough. For some reason, a customer had figured out that by placing all the application files in a directory on his desktop, it worked as expected with Oracle as well. Moving the directory down to the root of the drive, or in C:\Temp or, well, around a bit, made the crash reappear. Basically it was 100% reproducable that the application worked if run from directory on desktop, and failed if run from directory in root. Today we figured out that the difference that counted was wether there was a space in the directory name or not. So, these directories would work: ``` C:\Program Files\AppDir\Executable.exe C:\Temp Lemp\AppDir\Executable.exe C:\Documents and Settings\someuser\Desktop\AppDir\Executable.exe ``` whereas these would not: ``` C:\CompanyName\AppDir\Executable.exe C:\Programfiler\AppDir\Executable.exe <-- Program Files in norwegian C:\Temp\AppDir\Executable.exe ``` I'm hoping someone reading this has seen similar behavior and have a "aha, you need to twiddle the frob on the oracle glitz driver configuration" or similar. Anyone? --- **Followup #1:** Ok, I've processed the procmon output now, both files from when I hit the button that attempts to open the window that triggers the cascade failure, and I've noticed that they keep track mostly, there's some smallish differences near the top of both files, and they they keep track a long way down. However, when one run fails, the other keeps going and the next few lines of the log output are these: ``` ReadFile C:\oracle\product\10.2.0\db_1\BIN\orageneric10.dll SUCCESS Offset: 274 432, Length: 32 768, I/O Flags: Non-cached, Paging I/O, Synchronous Paging I/O ReadFile C:\oracle\product\10.2.0\db_1\BIN\orageneric10.dll SUCCESS Offset: 233 472, Length: 32 768, I/O Flags: Non-cached, Paging I/O, Synchronous Paging I/O ``` After this, the working run continues to execute, and the other touches the mscorwks.dll files a few times before threads close down and the app closes. Thus, the failed run does not touch the above files. --- **Followup #2:** Figured I'd try to upgrade the oracle client drivers, but 10.2.0.1 is apparently the highest version available for Windows 2003 server and XP clients. --- **Followup #3:** Well, we've ended up with a black-box solution. Basically we found that the problem is somewhere related to [XPO](http://www.devexpress.com/Products/NET/ORM/) and Oracle. XPO has a system-table it manages, called XPObjectType, with three columns: Oid, TypeName and AssemblyName. Due to how Oracle is configured in the databases we talk to, the column names were OID, TYPENAME and ASSEMBLYNAME. This would ordinarily not be a problem, except that XPO talks to the schema information directly and checks if the table is there with the right column names, and XPO doesn't handle case differences so it sees a XPObjectType table with three unknown columns and none of those it expects. Exactly what XPO does now I don't really know, but if I dropped this table, and recreated it with the right case, using double quotes around all the column names to get the case right, the problem doesn't crop up. Exactly where the space in the folder name comes into this, I still have no idea, but this problem had two tiers: 1. Stop the application from crashing at our customers, short-term solution 2. Fix the bug, long-term solution Right now tier 1 is solved, tier 2 will be put back into the queue for now and prioritized. We're facing some bigger changes to our data tier anyway so this might not be a problem we need to solve, at least if all our Oracle-customers verify that the table-fix actually gets rid of the problem. I'll accept the answer by [Dave Markle](https://stackoverflow.com/users/24995/dave-markle) since though Process Monitor (the big brother of File Monitor) didn't actually pinpoint the problem, I was able to use it to determine that after my breakpoint in user-code where XPO had built up the query for this table, no I/O happened until all the entries for the application closing down was logged, which led me to believe it was this table that was the culprit, or at least influenced the problem somehow. If I manage to get to the real cause of this, I'll update the post.
Here's what I would do. First, TRIPLE-check that you're seeing the behavior you think you're seeing. I can see this happening the other way around by not using System.IO.Path to concatenate paths, but not like you're seeing it. Triple-check that the file permissions make sense. Next, download [Filemon](http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx) from MS and watch what's happening on the filesystem as your program hits these troubled spots. You can filter out specific file activity (removing your anti-virus file activity, for example) to make everything look a bit cleaner while you do this. Look for file access errors using FileMon for both the success case and the error case for your program. That should point you to what file's being accessed and causing the problem. For example, if you see a `FILE_NOT_FOUND` error accessing a nonsense filename, you can be assured that you or the vendor are doing something wrong, possibly leading to your problem...
239,628
<p>HI,</p> <p>I am trying to write a query in vba and to save its result in a report. I am a beginner. this is what i have tried can somebody correct me</p> <pre><code>Dim cn As New ADODB.Connection, rs As New ADODB.Recordset Dim sql As String Set cn = CurrentProject.Connection sql = "Select * from table1 where empno is 0" rs.Open sql, cn While Not rs.EOF ' here i think i should save the result in a report but i am not sure how rs.MoveNext Wend rs.Close cn.Close Set rs = Nothing Set cn = Nothing </code></pre> <p>Also how do i change this query to run this on all tables in a database</p>
[ { "answer_id": 239699, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 0, "selected": false, "text": "<p>Normally you would design the report based on a data source. Then after your report is done and working properly you use VBA to display or save the report.</p>\n" }, { "answer_id": 239717, "author": "James Green", "author_id": 31736, "author_profile": "https://Stackoverflow.com/users/31736", "pm_score": 0, "selected": false, "text": "<p>To run this for each table in the database, I'd suggest writing a function that looped through CurrentData.AllTables(i) and then called your function above in each iteration</p>\n\n<p>Hope this helps</p>\n" }, { "answer_id": 240103, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 1, "selected": false, "text": "<p><strong>IF you are wanting to create a report using MS Access's report generator</strong>, you will have to use a Query Object (there might be a way to trick MS Access into running it off of your record set, but it's probably not worth your effort). </p>\n\n<p>You can create the Query Object on the \"Database\" window. Click the Query button in the objects list, and then click on New. In the resulting editor you can create the query graphically or if you prefer with SQL. Save the query and give it a meaning full name.</p>\n\n<p>Similarly the report can be created on the \"Database\" window. Click on the Report button and then on New. In the resulting wizard, you'll link the report to the query you just created.<br>\n<strong><em>Update:</strong> As D.W. Fenton said, you can embed the query right within the Report Object without creating a separate Query Object. My preference is to create one anyway.</em></p>\n\n<p>The problem with this method is you would have to create a separate query and report for each table.</p>\n\n<p><strong>IF you just want to dump the result out to a text file (to read/print later)</strong>, then you can do it using recordsets like you are in your VBA code. It will look something like this</p>\n\n<pre><code>'...\ndim strFoo as string\ndim strBar as string\n'...\nif not rs.bof then\n rd.MoveFirst\nend if\nWhile Not rs.EOF\n strFoo = rs(\"foo\") 'copy the value in the field \n 'named \"foo\" into strFoo.\n strBar = rs(\"bar\")\n '... etc. for all fields you want\n '\n 'write out the values to a text file \n '(I'll leave this an exercise for the reader)\n '\n rs.MoveNext\nWend\n'...\n</code></pre>\n\n<p>Parsing all of the tables can be done in a loop something like this:</p>\n\n<pre><code>dim strTableName as string\ndim db As Database\n'...\nSet db = CurrentDb\ndb.TableDefs.Refresh\nFor Each myTable In db.TableDefs\n If Len(myTable.Connect) &gt; 0 Then\n strTableName = myTable.Name\n '...\n 'Do something with the table\n '...\n End If\nNext\nset db = nothing\n</code></pre>\n\n<p><strong>=======================UPDATE=======================</strong><br>\n<strong>It is possible to run an MS-Access Report from a record set.</strong> To repease what I said to <a href=\"https://stackoverflow.com/questions/242504/accesshow-can-i-generate-a-report-of-a-recordset\">tksy's question</a>\nFrom <a href=\"http://www.mvps.org/access/reports/rpt0014.htm\" rel=\"nofollow noreferrer\">Access Web</a> you can use the \"name\" property of a recordset. You resulting code would look something like this:</p>\n\n<p><em>In the report</em> </p>\n\n<pre><code>Private Sub Report_Open(Cancel As Integer)\n Me.RecordSource = gMyRecordSet.Name\nEnd Sub\n</code></pre>\n\n<p><em>In the calling object (module, form, etc.)</em> </p>\n\n<pre><code>Public gMyRecordSet As Recordset\n'...\nPublic Sub callMyReport()\n '...\n Set gMyRecordSet = CurrentDb.OpenRecordset(\"Select * \" &amp; _\n \"from foo \" &amp; _\n \"where bar='yaddah'\")\n DoCmd.OpenReport \"myReport\", acViewPreview \n '...\n gMyRecordSet.Close \n Set gMyRecordSet = Nothing\n '...\nEnd Sub\n</code></pre>\n\n<p><strong>Q.E.D.</strong></p>\n" }, { "answer_id": 241017, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 0, "selected": false, "text": "<p>If you want to simply view the results, you can create a query. For example, here is some rough, mostly untested VBA:</p>\n\n<pre><code>Sub ViewMySQL\nDim strSQL as String\nDim strName As String\n\n'Note that this is not sensible in that you\n'will end up with as many queries open as there are tables\n\n For Each tdf In CurrentDB.TableDefs\n If Left(tdf.Name,4)&lt;&gt;\"Msys\" Then\n strName = \"tmp\" &amp; tdf.Name\n\n strSQL = \"Select * from [\" &amp; tdf.Name &amp; \"] where empno = 0\"\n UpdateQuery strName, strSQL\n DoCmd.OpenQuery strName, acViewNormal\n End If\n Next\nEnd Sub\n\nFunction UpdateQuery(QueryName, SQL)\n\n If IsNull(DLookup(\"Name\", \"MsysObjects\", \"Name='\" &amp; QueryName &amp; \"'\")) Then\n CurrentDb.CreateQueryDef QueryName, SQL\n Else\n CurrentDb.QueryDefs(QueryName).SQL = SQL\n End If\n\n UpdateQuery = True\n\nEnd Function\n</code></pre>\n\n<p>You may also be interested in MDB Doc, an add-in for Microsoft Access 97-2003 that allows you to document objects/properties within an Access database to an HTML file.</p>\n\n<p>-- <a href=\"http://mdbdoc.sourceforge.net/\" rel=\"nofollow noreferrer\">http://mdbdoc.sourceforge.net/</a></p>\n" }, { "answer_id": 241224, "author": "David-W-Fenton", "author_id": 9787, "author_profile": "https://Stackoverflow.com/users/9787", "pm_score": 0, "selected": false, "text": "<p>It's not entirely clear to me what you want to do. If you want to view the results of SQL statement, you'd create a form and set its recordsource to \"Select * from table1 where empno is 0\". Then you could view the results one record at a time.</p>\n\n<p>If that's not what you want, then I'm afraid I just don't have enough information to answer your question.</p>\n\n<p>From what you <em>have</em> said so far, I don't see any reason why you need VBA or a report, since you just want to view the data. A report is for printing, a form is for viewing and editing. A report is page-oriented and not that easy to navigate, while a form is record-oriented, and allows you to edit the data (if you want to).</p>\n\n<p>More information about what you want to accomplish will help us give you better answers.</p>\n" }, { "answer_id": 57439564, "author": "sean", "author_id": 11910113, "author_profile": "https://Stackoverflow.com/users/11910113", "pm_score": 0, "selected": false, "text": "<p>Had the same question. just use the clipboard! </p>\n\n<ol>\n<li>select the query results by click/dragging over all field names shown</li>\n<li>press ctrl-c to copy to windows clipboard</li>\n<li>open a blank document in word and click inside it</li>\n<li>press ctrl-v to paste from clipboard.</li>\n</ol>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
HI, I am trying to write a query in vba and to save its result in a report. I am a beginner. this is what i have tried can somebody correct me ``` Dim cn As New ADODB.Connection, rs As New ADODB.Recordset Dim sql As String Set cn = CurrentProject.Connection sql = "Select * from table1 where empno is 0" rs.Open sql, cn While Not rs.EOF ' here i think i should save the result in a report but i am not sure how rs.MoveNext Wend rs.Close cn.Close Set rs = Nothing Set cn = Nothing ``` Also how do i change this query to run this on all tables in a database
**IF you are wanting to create a report using MS Access's report generator**, you will have to use a Query Object (there might be a way to trick MS Access into running it off of your record set, but it's probably not worth your effort). You can create the Query Object on the "Database" window. Click the Query button in the objects list, and then click on New. In the resulting editor you can create the query graphically or if you prefer with SQL. Save the query and give it a meaning full name. Similarly the report can be created on the "Database" window. Click on the Report button and then on New. In the resulting wizard, you'll link the report to the query you just created. ***Update:*** As D.W. Fenton said, you can embed the query right within the Report Object without creating a separate Query Object. My preference is to create one anyway. The problem with this method is you would have to create a separate query and report for each table. **IF you just want to dump the result out to a text file (to read/print later)**, then you can do it using recordsets like you are in your VBA code. It will look something like this ``` '... dim strFoo as string dim strBar as string '... if not rs.bof then rd.MoveFirst end if While Not rs.EOF strFoo = rs("foo") 'copy the value in the field 'named "foo" into strFoo. strBar = rs("bar") '... etc. for all fields you want ' 'write out the values to a text file '(I'll leave this an exercise for the reader) ' rs.MoveNext Wend '... ``` Parsing all of the tables can be done in a loop something like this: ``` dim strTableName as string dim db As Database '... Set db = CurrentDb db.TableDefs.Refresh For Each myTable In db.TableDefs If Len(myTable.Connect) > 0 Then strTableName = myTable.Name '... 'Do something with the table '... End If Next set db = nothing ``` **=======================UPDATE=======================** **It is possible to run an MS-Access Report from a record set.** To repease what I said to [tksy's question](https://stackoverflow.com/questions/242504/accesshow-can-i-generate-a-report-of-a-recordset) From [Access Web](http://www.mvps.org/access/reports/rpt0014.htm) you can use the "name" property of a recordset. You resulting code would look something like this: *In the report* ``` Private Sub Report_Open(Cancel As Integer) Me.RecordSource = gMyRecordSet.Name End Sub ``` *In the calling object (module, form, etc.)* ``` Public gMyRecordSet As Recordset '... Public Sub callMyReport() '... Set gMyRecordSet = CurrentDb.OpenRecordset("Select * " & _ "from foo " & _ "where bar='yaddah'") DoCmd.OpenReport "myReport", acViewPreview '... gMyRecordSet.Close Set gMyRecordSet = Nothing '... End Sub ``` **Q.E.D.**
239,645
<p>I have an abstract Class <strong>Monitor.java</strong> which is subclassed by a Class <strong>EmailMonitor.java</strong>. </p> <p>The method:</p> <pre><code>public abstract List&lt;? extends MonitorAccount&gt; performMonitor(List&lt;? extends MonitorAccount&gt; accounts) </code></pre> <p>is defined in <strong>Monitor.java</strong> and must be overridden in <strong>EmailMonitor.java</strong>.</p> <p>I currently have the method overridden in <strong>EmailMonitor.java</strong> as follows:</p> <pre><code>@Override public List&lt;EmailAccount&gt; performMonitor(List&lt;EmailAccount&gt; emailAccounts) { //...unrelated logic return emailAccounts; } </code></pre> <p>However, this produces the compile time error: </p> <p><code>Name clash: The method performMonitor(List&lt;EmailAccount&gt;) of type EmailMonitor has the same erasure as performMonitor(Lis&lt;? extends MonitorAccount&gt; emailAccounts) of type Monitor but does not override it</code></p> <p><code>EmailAccount</code> is a subclass of <code>MonitorAccount</code>, so (in my mind at least) overriding it in this way makes perfect sense. Seeing as the compiler is not happy with my logic though, How should I go about this correctly while still keeping my compile time checks to make sure that all calls to <code>EmailMonitor.performMonitor()</code> receive Lists of <code>EmailAccount</code> rather than some other type of <code>MonitorAccount</code>? </p></p>
[ { "answer_id": 239663, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 6, "selected": true, "text": "<p>No, it's not overriding it properly. Overriding means you should be able to cope with any valid input to the base class. Consider what would happen if a client did this:</p>\n\n<pre><code>Monitor x = new EmailMonitor();\nList&lt;NonEmailAccount&gt; nonEmailAccounts = ...;\nx.performMonitor(nonEmailAccounts);\n</code></pre>\n\n<p>There's nothing in there which should give a compile-time error given your description - but it's clearly wrong.</p>\n\n<p>It sounds to me like <code>Monitor</code> should be generic in the type of account it can monitor, so your <code>EmailMonitor</code> should extend <code>Monitor&lt;EmailAccount&gt;</code>. So:</p>\n\n<pre><code>public abtract class Monitor&lt;T extends MonitorAccount&gt;\n{\n ...\n public abstract List&lt;? extends T&gt; performMonitor(\n List&lt;? extends T&gt; accounts);\n}\n\npublic class EmailMonitor extends Monitor&lt;EmailAccount&gt;\n{\n @Override\n public abstract List&lt;? extends EmailAccount&gt; performMonitor(\n List&lt;? extends EmailAccount&gt; accounts)\n {\n // Code goes here\n }\n}\n</code></pre>\n\n<p>You might want to think carefully about the generics in the <code>performMonitor</code> call though - what's the return value meant to signify?</p>\n" }, { "answer_id": 240192, "author": "Robert Ngetich", "author_id": 31749, "author_profile": "https://Stackoverflow.com/users/31749", "pm_score": 3, "selected": false, "text": "<p>Here is my own solution. I suspect this is the same thing Jon Skeet was trying to get at... without the typo (see my comment in reply to his answer). </p>\n\n<p>the <b>Monitor.java</b> class:</p>\n\n<pre><code>public abstract class Monitor &lt;T extends MonitorAccount&gt; {\n ...\n public abstract List&lt;T&gt; performMonitor(List&lt;T&gt; accounts);\n ..\n}\n</code></pre>\n\n<p><b>EmailMonitor.java</b></p>\n\n<pre><code>public class EmailMonitor extends Monitor&lt;EmailAccount&gt; {\n ...\n public List&lt;EmailAccount&gt; performMonitor(List&lt;EmailAccount&gt; emailAccounts) {\n ..//logic...logic...logic\n return emailAccounts;\n }\n ...\n}\n</code></pre>\n\n<p>In this configuration, <i>EmailMonitor.performMonitor()</i> will always check at compile time that it receives a list of <b>EmailAccount</b> rather than any of my other types <b>FTPAccount, DBAccount,</b> etc... It's much cleaner than the alternative, which would have been receiving/sending a raw list and then having to coerce it the required type resulting in potential runtime type casting exceptions. </p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31749/" ]
I have an abstract Class **Monitor.java** which is subclassed by a Class **EmailMonitor.java**. The method: ``` public abstract List<? extends MonitorAccount> performMonitor(List<? extends MonitorAccount> accounts) ``` is defined in **Monitor.java** and must be overridden in **EmailMonitor.java**. I currently have the method overridden in **EmailMonitor.java** as follows: ``` @Override public List<EmailAccount> performMonitor(List<EmailAccount> emailAccounts) { //...unrelated logic return emailAccounts; } ``` However, this produces the compile time error: `Name clash: The method performMonitor(List<EmailAccount>) of type EmailMonitor has the same erasure as performMonitor(Lis<? extends MonitorAccount> emailAccounts) of type Monitor but does not override it` `EmailAccount` is a subclass of `MonitorAccount`, so (in my mind at least) overriding it in this way makes perfect sense. Seeing as the compiler is not happy with my logic though, How should I go about this correctly while still keeping my compile time checks to make sure that all calls to `EmailMonitor.performMonitor()` receive Lists of `EmailAccount` rather than some other type of `MonitorAccount`?
No, it's not overriding it properly. Overriding means you should be able to cope with any valid input to the base class. Consider what would happen if a client did this: ``` Monitor x = new EmailMonitor(); List<NonEmailAccount> nonEmailAccounts = ...; x.performMonitor(nonEmailAccounts); ``` There's nothing in there which should give a compile-time error given your description - but it's clearly wrong. It sounds to me like `Monitor` should be generic in the type of account it can monitor, so your `EmailMonitor` should extend `Monitor<EmailAccount>`. So: ``` public abtract class Monitor<T extends MonitorAccount> { ... public abstract List<? extends T> performMonitor( List<? extends T> accounts); } public class EmailMonitor extends Monitor<EmailAccount> { @Override public abstract List<? extends EmailAccount> performMonitor( List<? extends EmailAccount> accounts) { // Code goes here } } ``` You might want to think carefully about the generics in the `performMonitor` call though - what's the return value meant to signify?
239,669
<p>I'm occasionaly getting the following popup from an AJAX.NET application</p> <pre>Sys.WebForms.PageRequestManagerServerErrorException: An Unknown error occurred while processing the request on the server. The status code returned from the server was: 12031</pre> <p>From the <a href="http://support.microsoft.com/kb/193625" rel="noreferrer">Microsoft kb</a> that status code indicates a ERROR_INTERNET_CONNECTION_RESET, but it doesn't state what was the underlying issue the triggered the error in the first place.</p> <p>How can I log/trace/etc the underlying error that generated the popup?</p>
[ { "answer_id": 239674, "author": "Zachary Yates", "author_id": 8360, "author_profile": "https://Stackoverflow.com/users/8360", "pm_score": 4, "selected": false, "text": "<p>If you're getting that from an updatePanel, set EnablePartialRendering to false in the ScriptManager for the page, and then it should give you the actual error.</p>\n\n<p>Also, if it only happens occasionally, I've found that it could be a viewstate problem, especially when the page goes a long time (20mins or so) between refreshes.</p>\n\n<p>Otherwise, try some try/catch blocks. Those are some easy methods.</p>\n\n<p>Hope that helps!</p>\n" }, { "answer_id": 545656, "author": "penyaskito", "author_id": 3008, "author_profile": "https://Stackoverflow.com/users/3008", "pm_score": 5, "selected": true, "text": "<p>It's a viewstate problem, but not related with time but with size. Try playing with maxRequestLength in your web.config.</p>\n" }, { "answer_id": 2140625, "author": "alice7", "author_id": 21918, "author_profile": "https://Stackoverflow.com/users/21918", "pm_score": 0, "selected": false, "text": "<p>sometimes the error occurs if you have added a server SSL certificate(https).If the certificate is not valid it will give this error.</p>\n" }, { "answer_id": 6535792, "author": "Sergii.PSP", "author_id": 802837, "author_profile": "https://Stackoverflow.com/users/802837", "pm_score": 1, "selected": false, "text": "<p>I've got this error in UpdatePanel with autopostback Dropdown after big delay (>20 min) between change dropdown selection.</p>\n\n<p>Try increase session timeout in web.cofig. For example:</p>\n\n<pre><code>&lt;sessionState mode=\"InProc\" cookieless=\"true\" timeout=\"720\"/&gt;;\n</code></pre>\n" }, { "answer_id": 9526511, "author": "Neha", "author_id": 1244039, "author_profile": "https://Stackoverflow.com/users/1244039", "pm_score": 0, "selected": false, "text": "<p>I had the following error happening on postback:</p>\n\n<blockquote>\n <p>Error: Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server.</p>\n</blockquote>\n\n<p>But for me, the issue was that I am converting my project from ASP.NET 2.0 to ASP.NET 4.0 and I had <code>&lt;asp:UpdatePanel runat=\"server\"&gt;</code> used on the page.</p>\n\n<p>I took off the <code>&lt;asp:UpdatePanel runat=\"server\"&gt;</code> (for the time being), then ran the page to get the exact error. Which was \"A potentially dangerous Request.Form value was detected\"</p>\n\n<p>I found that even though I have <code>ValidateRequest=\"false\"</code> on the page, ASP.NET 4.0 requires you to add <code>requestValidationMode=\"2.0\"</code> in the HttpRuntime tag of web.config.</p>\n\n<pre><code>&lt;httpRuntime maxRequestLength=\"102400\" requestValidationMode=\"2.0\"/&gt;\n</code></pre>\n\n<p><a href=\"http://www.codeproject.com/Tips/297679/A-potentially-dangerous-Request-Form-value-was-det\" rel=\"nofollow\">Reference</a></p>\n" }, { "answer_id": 10176400, "author": "hari", "author_id": 1336584, "author_profile": "https://Stackoverflow.com/users/1336584", "pm_score": 2, "selected": false, "text": "<p><strong>add</strong> <code>&lt;httpRuntime requestValidationMode=\"2.0\"/&gt;</code><br>\n in <strong>web.config</strong>\nand in <strong>YourPage.aspx</strong> set (ClientIDMode=\"Static\" ValidateRequest=\"false\") </p>\n\n<p>::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::</p>\n\n<p>EXAMPLE: web.config</p>\n\n<pre><code> &lt;?xml version=\"1.0\"?&gt;\n&lt;!--\n For more information on how to configure your ASP.NET application, please visit\n http://go.microsoft.com/fwlink/?LinkId=169433\n --&gt;\n&lt;configuration&gt;\n &lt;system.web&gt;\n &lt;httpRuntime requestValidationMode=\"2.0\"/&gt;\n &lt;compilation debug=\"true\" targetFramework=\"4.0\"&gt;\n &lt;assemblies&gt;\n &lt;add assembly=\"System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/&gt;\n &lt;/assemblies&gt;\n &lt;/compilation&gt;\n\n &lt;/system.web&gt;\n\n\n &lt;connectionStrings&gt;\n &lt;add name=\"WT_ZadnjiEntities\" connectionString=\"metadata=res://*/DAL.Model.csdl|res://*/DAL.Model.ssdl|res://*/DAL.Model.msl;provider=System.Data.SqlClient;provider connection string=&amp;quot;data source=SATELLITE-PC;initial catalog=WT_Zadnji;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&amp;quot;\" providerName=\"System.Data.EntityClient\" /&gt;\n &lt;/connectionStrings&gt;\n&lt;/configuration&gt;\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12772/" ]
I'm occasionaly getting the following popup from an AJAX.NET application ``` Sys.WebForms.PageRequestManagerServerErrorException: An Unknown error occurred while processing the request on the server. The status code returned from the server was: 12031 ``` From the [Microsoft kb](http://support.microsoft.com/kb/193625) that status code indicates a ERROR\_INTERNET\_CONNECTION\_RESET, but it doesn't state what was the underlying issue the triggered the error in the first place. How can I log/trace/etc the underlying error that generated the popup?
It's a viewstate problem, but not related with time but with size. Try playing with maxRequestLength in your web.config.
239,682
<p>When reading the registry for file names I get 3 entries loading into my combo box for every 1 registry entry. If I have 1 file listed in the registry I would see :</p> <p>Combo box values:</p> <p>c:\file1.txt</p> <p>&lt;-----Blank here</p> <p>c:\file1.txt</p> <p>I have found the problem lies in this code, it hits 'if (previousFiles != null)' 3 times. How should I correct this?</p> <pre><code>for (int i = 0; i &lt;= 5; i++) { Object previousFiles = OurKey.GetValue("Files" + i); if (previousFiles != null) { comboBox1.Items.Add(previousFiles.ToString()); } } </code></pre> <p>Many thanks Monday morning blues!</p>
[ { "answer_id": 239684, "author": "Joachim Kerschbaumer", "author_id": 20227, "author_profile": "https://Stackoverflow.com/users/20227", "pm_score": 0, "selected": false, "text": "<p>just add a \"break;\" after the first comboBox1.Items.Add().\nit will leave the loop after the insert (if this is what you want).</p>\n" }, { "answer_id": 239692, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 0, "selected": false, "text": "<p>Looks like the issue is in your GetValue() function. Plus you should check for null and for empty string before adding to the combobox.</p>\n" }, { "answer_id": 239694, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 0, "selected": false, "text": "<p>Assuming this is a string value what you may be seeing is a empty string coming back; it's hard to tell from the code.</p>\n\n<p>So instead of a null check cast the object first;</p>\n\n<pre><code>Object previousFiles = OurKey.GetValue(\"Files\" + i) as string;\n</code></pre>\n\n<p>Then use</p>\n\n<pre><code>string.IsNullOrEmpty()\n</code></pre>\n\n<p>instead of a plain null check.</p>\n" }, { "answer_id": 239864, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 1, "selected": false, "text": "<p>Well, it should hit the if() statement 6 times, the comboBox1.Items.Add() statement 3 times. The logical explanation is that the real problem is located in the code that writes the registry keys. Run Regedit.exe to find out what is really stored in these registry key values.</p>\n" }, { "answer_id": 239899, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>sorry it was in the code that wrote it, I was looking at an old reg key....sorry!</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
When reading the registry for file names I get 3 entries loading into my combo box for every 1 registry entry. If I have 1 file listed in the registry I would see : Combo box values: c:\file1.txt <-----Blank here c:\file1.txt I have found the problem lies in this code, it hits 'if (previousFiles != null)' 3 times. How should I correct this? ``` for (int i = 0; i <= 5; i++) { Object previousFiles = OurKey.GetValue("Files" + i); if (previousFiles != null) { comboBox1.Items.Add(previousFiles.ToString()); } } ``` Many thanks Monday morning blues!
Well, it should hit the if() statement 6 times, the comboBox1.Items.Add() statement 3 times. The logical explanation is that the real problem is located in the code that writes the registry keys. Run Regedit.exe to find out what is really stored in these registry key values.
239,725
<p>When I try to add a HTTP header key/value pair on a <code>WebRequest</code> object, I get the following exception:</p> <blockquote> <p>This header must be modified using the appropriate property</p> </blockquote> <p>I've tried adding new values to the <code>Headers</code> collection by using the Add() method but I still get the same exception.</p> <pre><code>webRequest.Headers.Add(HttpRequestHeader.Referer, "http://stackoverflow.com"); </code></pre> <p>I can get around this by casting the WebRequest object to a HttpWebRequest and setting the properties such as <code>httpWebReq.Referer ="http://stackoverflow.com"</code>, but this only works for a handful of headers that are exposed via properties.</p> <p>I'd like to know if there's a way to get a finer grained control over modifying headers with a request for a remote resource.</p>
[ { "answer_id": 239736, "author": "FOR", "author_id": 27826, "author_profile": "https://Stackoverflow.com/users/27826", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.net.webrequest(VS.71).aspx\" rel=\"nofollow noreferrer\">WebRequest</a> being abstract (and since any inheriting class must override the Headers property).. which concrete WebRequest are you using ? In other words, how do you get that WebRequest object to beign with ?</p>\n\n<p>ehr.. mnour answer made me realize that the error message you were getting is actually spot on: it's telling you that the header you are trying to add already exist and you should then modify its value using the appropriate property (the indexer, for instance), instead of trying to add it again. That's probably all you were looking for.</p>\n\n<p>Other classes inheriting from WebRequest might have even better properties wrapping certain headers; See <a href=\"http://weblogs.asp.net/cazzu/archive/2007/07/30/setting-http-headers-in-net-this-header-must-be-modified-using-the-appropriate-property.aspx\" rel=\"nofollow noreferrer\">this post</a> for instance.</p>\n" }, { "answer_id": 239847, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>Basically, no. That is an http header, so it is reasonable to cast to <code>HttpWebRequest</code> and set the <code>.Referer</code> (as you indicate in the question):</p>\n\n<pre><code>HttpWebRequest req = ...\nreq.Referer = \"your url\";\n</code></pre>\n" }, { "answer_id": 331317, "author": "Jerod Venema", "author_id": 25330, "author_profile": "https://Stackoverflow.com/users/25330", "pm_score": 4, "selected": false, "text": "<p>Anytime you're changing the headers of an <code>HttpWebRequest</code>, you need to use the appropriate properties on the object itself, if they exist. If you have a plain <code>WebRequest</code>, be sure to cast it to an <code>HttpWebRequest</code> first. Then <code>Referrer</code> in your case can be accessed via <code>((HttpWebRequest)request).Referrer</code>, so you don't need to modify the header directly - just set the property to the right value. <code>ContentLength</code>, <code>ContentType</code>, <code>UserAgent</code>, etc, all need to be set this way.</p>\n\n<p>IMHO, this is a shortcoming on MS part...setting the headers via <code>Headers.Add()</code> should automatically call the appropriate property behind the scenes, if that's what they want to do.</p>\n" }, { "answer_id": 2405654, "author": "Chmod", "author_id": 276619, "author_profile": "https://Stackoverflow.com/users/276619", "pm_score": 6, "selected": false, "text": "<p>I ran into this problem with a custom web client. I think people may be getting confused because of multiple ways to do this. When using <code>WebRequest.Create()</code> you can cast to an <code>HttpWebRequest</code> and use the property to add or modify a header. When using a <code>WebHeaderCollection</code> you may use the <code>.Add(\"referer\",\"my_url\")</code>.</p>\n\n<p>Ex 1</p>\n\n<pre><code>WebClient client = new WebClient();\nclient.Headers.Add(\"referer\", \"http://stackoverflow.com\");\nclient.Headers.Add(\"user-agent\", \"Mozilla/5.0\");\n</code></pre>\n\n<p>Ex 2</p>\n\n<pre><code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\nrequest.Referer = \"http://stackoverflow.com\";\nrequest.UserAgent = \"Mozilla/5.0\";\nresponse = (HttpWebResponse)request.GetResponse();\n</code></pre>\n" }, { "answer_id": 4752359, "author": "dubi", "author_id": 248916, "author_profile": "https://Stackoverflow.com/users/248916", "pm_score": 9, "selected": true, "text": "<p>If you need the short and technical answer go right to the last section of the answer.</p>\n\n<p>If you want to know better, read it all, and i hope you'll enjoy...</p>\n\n<hr>\n\n<p>I countered this problem too today, and what i discovered today is that:</p>\n\n<ol>\n<li><p>the above answers are true, as:</p>\n\n<p>1.1 it's telling you that the header you are trying to add already exist and you should then modify its value using the appropriate property (the indexer, for instance), instead of trying to add it again.</p>\n\n<p>1.2 Anytime you're changing the headers of an <code>HttpWebRequest</code>, you need to use the appropriate properties on the object itself, if they exist.</p></li>\n</ol>\n\n<p>Thanks FOR and Jvenema for the leading guidelines...</p>\n\n<ol start=\"2\">\n<li><p>But, What i found out, and <strong>that was the missing piece in the puzzle</strong> is that:</p>\n\n<p>2.1 The <code>WebHeaderCollection</code> class is generally accessed through <code>WebRequest</code>.Headers or <code>WebResponse</code>.Headers. <strong>Some common headers are considered restricted and are either exposed directly by the API (such as Content-Type) or protected by the system and cannot be changed.</strong></p></li>\n</ol>\n\n<p>The restricted headers are:</p>\n\n<ul>\n<li><code>Accept</code></li>\n<li><code>Connection</code></li>\n<li><code>Content-Length</code></li>\n<li><code>Content-Type</code></li>\n<li><code>Date</code></li>\n<li><code>Expect</code></li>\n<li><code>Host</code></li>\n<li><code>If-Modified-Since</code></li>\n<li><code>Range</code></li>\n<li><code>Referer</code></li>\n<li><code>Transfer-Encoding</code></li>\n<li><code>User-Agent</code></li>\n<li><code>Proxy-Connection</code></li>\n</ul>\n\n<hr>\n\n<p>So, next time you are facing this exception and don't know how to solve this, remember that there are some restricted headers, and the solution is to modify their values using the appropriate property explicitly from the <code>WebRequest</code>/<code>HttpWebRequest</code> class.</p>\n\n<hr>\n\n<p>Edit: (useful, from comments, comment by user <a href=\"https://stackoverflow.com/questions/239725/cannot-set-some-http-headers-when-using-system-net-webrequest#comment15470171_4752359\">Kaido</a>)</p>\n\n<blockquote>\n <p>Solution is to check if the header exists already or is restricted (<code>WebHeaderCollection.IsRestricted(key)</code>) before calling add</p>\n</blockquote>\n" }, { "answer_id": 23070923, "author": "Despertar", "author_id": 1160036, "author_profile": "https://Stackoverflow.com/users/1160036", "pm_score": 5, "selected": false, "text": "<p>All the previous answers describe the problem without providing a solution. Here is an extension method which solves the problem by allowing you to set any header via its string name. </p>\n\n<p><strong>Usage</strong></p>\n\n<pre><code>HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;\nrequest.SetRawHeader(\"content-type\", \"application/json\");\n</code></pre>\n\n<p><strong>Extension Class</strong></p>\n\n<pre><code>public static class HttpWebRequestExtensions\n{\n static string[] RestrictedHeaders = new string[] {\n \"Accept\",\n \"Connection\",\n \"Content-Length\",\n \"Content-Type\",\n \"Date\",\n \"Expect\",\n \"Host\",\n \"If-Modified-Since\",\n \"Keep-Alive\",\n \"Proxy-Connection\",\n \"Range\",\n \"Referer\",\n \"Transfer-Encoding\",\n \"User-Agent\"\n };\n\n static Dictionary&lt;string, PropertyInfo&gt; HeaderProperties = new Dictionary&lt;string, PropertyInfo&gt;(StringComparer.OrdinalIgnoreCase);\n\n static HttpWebRequestExtensions()\n {\n Type type = typeof(HttpWebRequest);\n foreach (string header in RestrictedHeaders)\n {\n string propertyName = header.Replace(\"-\", \"\");\n PropertyInfo headerProperty = type.GetProperty(propertyName);\n HeaderProperties[header] = headerProperty;\n }\n }\n\n public static void SetRawHeader(this HttpWebRequest request, string name, string value)\n {\n if (HeaderProperties.ContainsKey(name))\n {\n PropertyInfo property = HeaderProperties[name];\n if (property.PropertyType == typeof(DateTime))\n property.SetValue(request, DateTime.Parse(value), null);\n else if (property.PropertyType == typeof(bool))\n property.SetValue(request, Boolean.Parse(value), null);\n else if (property.PropertyType == typeof(long))\n property.SetValue(request, Int64.Parse(value), null);\n else\n property.SetValue(request, value, null);\n }\n else\n {\n request.Headers[name] = value;\n }\n }\n}\n</code></pre>\n\n<p><strong>Scenarios</strong></p>\n\n<p>I wrote a wrapper for <code>HttpWebRequest</code> and didn't want to expose all 13 restricted headers as properties in my wrapper. Instead I wanted to use a simple <code>Dictionary&lt;string, string&gt;</code>.</p>\n\n<p>Another example is an HTTP proxy where you need to take headers in a request and forward them to the recipient. </p>\n\n<p>There are a lot of other scenarios where its just not practical or possible to use properties. Forcing the user to set the header via a property is a very inflexible design which is why reflection is needed. The up-side is that the reflection is abstracted away, it's still fast (.001 second in my tests), and as an extension method feels natural.</p>\n\n<p><strong>Notes</strong></p>\n\n<p>Header names are case insensitive per the RFC, <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2\" rel=\"noreferrer\">http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2</a></p>\n" }, { "answer_id": 27709909, "author": "Rob", "author_id": 658216, "author_profile": "https://Stackoverflow.com/users/658216", "pm_score": 2, "selected": false, "text": "<p>The above answers are all fine, but the essence of the issue is that some headers are set one way, and others are set other ways. See above for 'restricted header' lists. FOr these, you just set them as a property. For others, you actually add the header. See here.</p>\n\n<pre><code> request.ContentType = \"application/x-www-form-urlencoded\";\n\n request.Accept = \"application/json\";\n\n request.Headers.Add(HttpRequestHeader.Authorization, \"Basic \" + info.clientId + \":\" + info.clientSecret);\n</code></pre>\n" }, { "answer_id": 28993152, "author": "Stefan Michev", "author_id": 754571, "author_profile": "https://Stackoverflow.com/users/754571", "pm_score": 0, "selected": false, "text": "<p>I'm using just: </p>\n\n<pre><code>request.ContentType = \"application/json; charset=utf-8\"\n</code></pre>\n" }, { "answer_id": 29850603, "author": "Bonomi", "author_id": 909986, "author_profile": "https://Stackoverflow.com/users/909986", "pm_score": 0, "selected": false, "text": "<p>You can just cast the WebRequest to an HttpWebRequest showed below:</p>\n\n<pre><code>var request = (HttpWebRequest)WebRequest.Create(myUri);\n</code></pre>\n\n<p>and then instead of trying to manipulate the header list, apply it directly in the request property request.Referer:</p>\n\n<pre><code>request.Referer = \"yourReferer\";\n</code></pre>\n\n<p>These properties are available in the request object.</p>\n" }, { "answer_id": 36038562, "author": "Mike Gledhill", "author_id": 391605, "author_profile": "https://Stackoverflow.com/users/391605", "pm_score": 4, "selected": false, "text": "<p>I had the same exception when my code tried to set the \"Accept\" header value like this:</p>\n\n<pre><code>WebRequest request = WebRequest.Create(\"http://someServer:6405/biprws/logon/long\");\nrequest.Headers.Add(\"Accept\", \"application/json\");\n</code></pre>\n\n<p>The solution was to change it to this:</p>\n\n<pre><code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create(\"http://someServer:6405/biprws/logon/long\");\nrequest.Accept = \"application/json\";\n</code></pre>\n" }, { "answer_id": 58585845, "author": "Sleeper", "author_id": 12283553, "author_profile": "https://Stackoverflow.com/users/12283553", "pm_score": 2, "selected": false, "text": "<p>Note: this solution will work with WebClientSocket as well as with HttpWebRequest or any other class that uses WebHeaderCollection to work with headers.</p>\n\n<p>If you look at the source code of WebHeaderCollection.cs you will see that Hinfo is used to keep information of all known headers: </p>\n\n<pre><code>private static readonly HeaderInfoTable HInfo = new HeaderInfoTable();\n</code></pre>\n\n<p>Looking at HeaderInfoTable class, you can notice all the data is stored into hash table </p>\n\n<pre><code>private static Hashtable HeaderHashTable;\n</code></pre>\n\n<p>Further, in static contructor of HeaderInfoTable, you can see all known headers are added in HeaderInfo array and then copied into hashtable.</p>\n\n<p>Final look at HeaderInfo class shows the names of the fields.</p>\n\n<pre><code>internal class HeaderInfo {\n\n internal readonly bool IsRequestRestricted;\n internal readonly bool IsResponseRestricted;\n internal readonly HeaderParser Parser;\n\n //\n // Note that the HeaderName field is not always valid, and should not\n // be used after initialization. In particular, the HeaderInfo returned\n // for an unknown header will not have the correct header name.\n //\n\n internal readonly string HeaderName;\n internal readonly bool AllowMultiValues;\n ...\n }\n</code></pre>\n\n<p>So, with all the above, here is a code that uses reflection to find static Hashtable in HeaderInfoTable class and then changes every request-restricted HeaderInfo inside hash table to be unrestricted</p>\n\n<pre><code> // use reflection to remove IsRequestRestricted from headerInfo hash table\n Assembly a = typeof(HttpWebRequest).Assembly;\n foreach (FieldInfo f in a.GetType(\"System.Net.HeaderInfoTable\").GetFields(BindingFlags.NonPublic | BindingFlags.Static))\n {\n if (f.Name == \"HeaderHashTable\")\n {\n Hashtable hashTable = f.GetValue(null) as Hashtable;\n foreach (string sKey in hashTable.Keys)\n {\n\n object headerInfo = hashTable[sKey];\n //Console.WriteLine(String.Format(\"{0}: {1}\", sKey, hashTable[sKey]));\n foreach (FieldInfo g in a.GetType(\"System.Net.HeaderInfo\").GetFields(BindingFlags.NonPublic | BindingFlags.Instance))\n {\n\n if (g.Name == \"IsRequestRestricted\")\n {\n bool b = (bool)g.GetValue(headerInfo);\n if (b)\n {\n g.SetValue(headerInfo, false);\n Console.WriteLine(sKey + \".\" + g.Name + \" changed to false\");\n }\n\n }\n }\n\n }\n }\n } \n</code></pre>\n" }, { "answer_id": 65000847, "author": "Vaibhav", "author_id": 880377, "author_profile": "https://Stackoverflow.com/users/880377", "pm_score": 0, "selected": false, "text": "<p>I ran into same issue below piece of code worked for me</p>\n<pre><code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n\nrequest.Headers[&quot;UserAgent&quot;] = &quot;Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; \nTrident/5.0)&quot;\n</code></pre>\n" }, { "answer_id": 73093313, "author": "pete", "author_id": 1165643, "author_profile": "https://Stackoverflow.com/users/1165643", "pm_score": 0, "selected": false, "text": "<pre><code>request.Headers.UserAgent.Add(new ProductInfoHeaderValue(&quot;my_string&quot;));\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17211/" ]
When I try to add a HTTP header key/value pair on a `WebRequest` object, I get the following exception: > > This header must be modified using the appropriate property > > > I've tried adding new values to the `Headers` collection by using the Add() method but I still get the same exception. ``` webRequest.Headers.Add(HttpRequestHeader.Referer, "http://stackoverflow.com"); ``` I can get around this by casting the WebRequest object to a HttpWebRequest and setting the properties such as `httpWebReq.Referer ="http://stackoverflow.com"`, but this only works for a handful of headers that are exposed via properties. I'd like to know if there's a way to get a finer grained control over modifying headers with a request for a remote resource.
If you need the short and technical answer go right to the last section of the answer. If you want to know better, read it all, and i hope you'll enjoy... --- I countered this problem too today, and what i discovered today is that: 1. the above answers are true, as: 1.1 it's telling you that the header you are trying to add already exist and you should then modify its value using the appropriate property (the indexer, for instance), instead of trying to add it again. 1.2 Anytime you're changing the headers of an `HttpWebRequest`, you need to use the appropriate properties on the object itself, if they exist. Thanks FOR and Jvenema for the leading guidelines... 2. But, What i found out, and **that was the missing piece in the puzzle** is that: 2.1 The `WebHeaderCollection` class is generally accessed through `WebRequest`.Headers or `WebResponse`.Headers. **Some common headers are considered restricted and are either exposed directly by the API (such as Content-Type) or protected by the system and cannot be changed.** The restricted headers are: * `Accept` * `Connection` * `Content-Length` * `Content-Type` * `Date` * `Expect` * `Host` * `If-Modified-Since` * `Range` * `Referer` * `Transfer-Encoding` * `User-Agent` * `Proxy-Connection` --- So, next time you are facing this exception and don't know how to solve this, remember that there are some restricted headers, and the solution is to modify their values using the appropriate property explicitly from the `WebRequest`/`HttpWebRequest` class. --- Edit: (useful, from comments, comment by user [Kaido](https://stackoverflow.com/questions/239725/cannot-set-some-http-headers-when-using-system-net-webrequest#comment15470171_4752359)) > > Solution is to check if the header exists already or is restricted (`WebHeaderCollection.IsRestricted(key)`) before calling add > > >
239,732
<p>I have heard from people who have switched either way and who swear by the one or the other.</p> <p>Being a huge Eclipse fan but having not had the time to try out IntelliJ, I am interested in hearing from IntelliJ users who are "ex-Eclipsians" some specific things that you can do with IntelliJ that you can not do with Eclipse.</p> <p><strong>Note</strong>: This is not a subjective question nor at all meant to turn into an IDE holy war. <strong><em>Please downvote any flamebait answers</em></strong>.</p>
[ { "answer_id": 239754, "author": "krosenvold", "author_id": 23691, "author_profile": "https://Stackoverflow.com/users/23691", "pm_score": 3, "selected": false, "text": "<p>IntelliJ has intellisense and refactoring support from code into jspx documents.</p>\n" }, { "answer_id": 239780, "author": "Mo.", "author_id": 1870, "author_profile": "https://Stackoverflow.com/users/1870", "pm_score": 4, "selected": false, "text": "<p>The IntelliJ debugger has a very handy feature called \"Evaluate Expression\", that is by far better than eclipses pendant. It has full code-completion and i concider it to be generally \"more useful\".</p>\n" }, { "answer_id": 239796, "author": "Mo.", "author_id": 1870, "author_profile": "https://Stackoverflow.com/users/1870", "pm_score": 5, "selected": false, "text": "<p>IntelliJ has some pretty advanced code inspections (comparable but different to FindBugs). </p>\n\n<p>Although I seriously miss a FindBugs plugin when using IntelliJ (The Eclipse/FindBugs integration is pretty cool). </p>\n\n<p><a href=\"http://www.jetbrains.com/idea/documentation/inspections.jsp\" rel=\"noreferrer\">Here</a> is an official list of CodeInspections supported by IntelliJ </p>\n\n<p>EDIT: Finally, there is a <a href=\"http://plugins.intellij.net/plugin/?id=3847\" rel=\"noreferrer\">findbugs-plugin</a> for IntelliJ. It is still a bit beta but the combination of Code Inspections and FindBugs is just awesome!</p>\n" }, { "answer_id": 240970, "author": "Chris Kessel", "author_id": 29734, "author_profile": "https://Stackoverflow.com/users/29734", "pm_score": 4, "selected": false, "text": "<p>Well, for me it's a thousand tiny things. Some of the macros, the GUI layout in general in Eclipse I find awful. I can't open multiple projects in different windows in Eclipse. I can open multiple projects, but then it's view based system swaps a bunch of things around on me when I switch files. IntelliJ's code inspections seem better. Its popup helpers to fix common issues is nice. Lots of simple usability things like the side bar where I can hover over a hot spot and it'll tell me every implementing subclass of a method or the method I'm implementing and from where. </p>\n\n<p>Whenever I've had to use, or watch someone use, Eclipse it seems like they can do most of the things I can do in IntelliJ, but it takes them longer and it's clunkier. </p>\n" }, { "answer_id": 241209, "author": "Pavel Feldman", "author_id": 5507, "author_profile": "https://Stackoverflow.com/users/5507", "pm_score": 9, "selected": true, "text": "<h2>CTRL-click works anywhere</h2>\n\n<p>CTRL-click that brings you to where clicked object is defined works everywhere - not only in Java classes and variables in Java code, but in Spring configuration (you can click on class name, or property, or bean name), in Hibernate (you can click on property name or class, or included resource), you can navigate within one click from Java class to where it is used as Spring or Hibernate bean; clicking on included JSP or JSTL tag also works, ctrl-click on JavaScript variable or function brings you to the place it is defined or shows a menu if there are more than one place, including other .js files and JS code in HTML or JSP files.</p>\n\n<h2>Autocomplete for many languagues</h2>\n\n<h3>Hibernate</h3>\n\n<p>Autocomplete in HSQL expressions, in Hibernate configuration (including class, property and DB column names), in Spring configuration</p>\n\n<pre><code>&lt;property name=\"propName\" ref=\"&lt;hit CTRL-SPACE&gt;\"\n</code></pre>\n\n<p>and it will show you list of those beans which you can inject into that property. </p>\n\n<h3>Java</h3>\n\n<p>Very smart autocomplete in Java code:</p>\n\n<pre><code>interface Person {\n String getName();\n String getAddress();\n int getAge();\n}\n//---\nPerson p;\nString name = p.&lt;CTRL-SHIFT-SPACE&gt;\n</code></pre>\n\n<p>and it shows you ONLY <em>getName()</em>, <em>getAddress()</em> and <em>toString()</em> (only they are compatible by type) and <em>getName()</em> is first in the list because it has more relevant name. Latest version 8 which is still in EAP has even more smart autocomplete.</p>\n\n<pre><code>interface Country{\n}\ninterface Address {\n String getStreetAddress();\n String getZipCode();\n Country getCountry();\n}\ninterface Person {\n String getName();\n Address getAddress();\n int getAge();\n}\n//--- \nPerson p;\nCountry c = p.&lt;CTRL-SHIFT-SPACE&gt;\n</code></pre>\n\n<p>and it will silently autocomplete it to</p>\n\n<pre><code>Country c = p.getAddress().getCountry();\n</code></pre>\n\n<h3>Javascript</h3>\n\n<p>Smart autocomplete in JavaScript.</p>\n\n<pre><code>function Person(name,address) {\n this.getName = function() { return name };\n this.getAddress = function() { return address };\n}\n\nPerson.prototype.hello = function() {\n return \"I'm \" + this.getName() + \" from \" + this.get&lt;CTRL-SPACE&gt;;\n}\n</code></pre>\n\n<p>and it shows ONLY <em>getName()</em> and <em>getAddress()</em>, no matter how may get* methods you have in other JS objects in your project, and ctrl-click on <em>this.getName()</em> brings you to where this one is defined, even if there are some other <em>getName()</em> functions in your project.</p>\n\n<h3>HTML</h3>\n\n<p>Did I mention autocomplete and ctrl-clicking in paths to files, like &lt;script src=\"\", &lt;img src=\"\", etc?</p>\n\n<p>Autocomplete in HTML tag attributes. Autocomplete in style attribute of HTML tags, both attribute names and values. Autocomplete in class attributes as well.<br>\nType &lt;div class=\"&lt;CTRL-SPACE> and it will show you list of CSS classes defined in your project. Pick one, ctrl-click on it and you will be redirected to where it is defined.</p>\n\n<h3>Easy own language higlighting</h3>\n\n<p>Latest version has language injection, so you can declare that you custom JSTL tag usually contains JavaScript and it will highlight JavaScript inside it.</p>\n\n<pre><code>&lt;ui:obfuscateJavaScript&gt;function something(){...}&lt;/ui:obfuscateJavaScript&gt;\n</code></pre>\n\n<h2>Indexed search across all project.</h2>\n\n<p>You can use Find Usages of any Java class or method and it will find where it is used including not only Java classes but Hibernate, Spring, JSP and other places. Rename Method refactoring renames method not only in Java classes but anywhere including comments (it can not be sure if string in comments is really method name so it will ask). And it will find only your method even if there are methods of another class with same name.\nGood source control integration (does SVN support changelists? IDEA support them for every source control), ability to create a patch with your changes so you can send your changes to other team member without committing them.</p>\n\n<h2>Improved debugger</h2>\n\n<p>When I look at <em>HashMap</em> in debugger's watch window, I see logical view - keys and values, last time I did it in Eclipse it was showing entries with hash and next fields - I'm not really debugging <em>HashMap</em>, I just want to look at it contents.</p>\n\n<h2>Spring &amp; Hibernate configuration validation</h2>\n\n<p>It validates Spring and Hibernate configuration right when you edit it, so I do not need to restart server to know that I misspelled class name, or added constructor parameter so my Spring cfg is invalid.</p>\n\n<p>Last time I tried, I could not run Eclipse on Windows XP x64.</p>\n\n<p>and it will suggest you <em>person.name</em> or <em>person.address</em>.\nCtrl-click on <em>person.name</em> and it will navigate you to <em>getName()</em> method of <em>Person</em> class.</p>\n\n<p>Type <code>Pattern.compile(\"\");</code> put \\\\ there, hit CTRL-SPACE and see helpful hint about what you can put into your regular expression. You can also use language injection here - define your own method that takes string parameter, declare in IntelliLang options dialog that your parameter is regular expression - and it will give you autocomplete there as well. Needless to say it highlights incorrect regular expressions.</p>\n\n<h2>Other features</h2>\n\n<p>There are few features which I'm not sure are present in Eclipse or not. But at least each member of our team who uses Eclipse, also uses some merging tool to merge local changes with changes from source control, usually WinMerge. I never need it - merging in IDEA is enough for me. By 3 clicks I can see list of file versions in source control, by 3 more clicks I can compare previous versions, or previous and current one and possibly merge.</p>\n\n<p>It allows to to specify that I need all .jars inside <code>WEB-INF\\lib</code> folder, without picking each file separately, so when someone commits new .jar into that folder it picks it up automatically.</p>\n\n<p>Mentioned above is probably 10% of what it does. I do not use Maven, Flex, Swing, EJB and a lot of other stuff, so I can not tell how it helps with them. But it does.</p>\n" }, { "answer_id": 241266, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 6, "selected": false, "text": "<p>Probably is not a matter of <strong>what</strong> can/can't be done, but <strong>how</strong>.</p>\n\n<p>For instance both have editor surrounded with dock panels for project, classpath, output, structure etc. But in Idea when I start to type all these collapse automatically let me focus on the code it self; In eclipse all these panels keep open leaving my editor area very reduced, about 1/5 of the total viewable area. So I have to grab the mouse and click to minimize in those panels. Doing this all day long is a very frustrating experience in eclipse.</p>\n\n<p>The exact opposite thing happens with the view output window. In Idea running a program brings the output window/panel to see the output of the program even if it was perviously minimized. In eclipse I have to grab my mouse again and look for the output tab and click it to view my program output, because the output window/panel is just another one, like all the rest of the windows, but in Idea it is treated in a special way: \"If the user want to run his program, is very likely he wants to see the output of that program!\" It seems so natural when I write it, but eclipse fails in this basic user interface concept.</p>\n\n<p>Probably there's a shortcut for this in eclipse ( autohide output window while editing and autoshow it when running the program ) , but as some other tens of features the shortcut must be hunted in forums, online help etc while in Idea is a little bit more \"natural\". </p>\n\n<p>This can be repeated for almost all the features both have, autocomplete, word wrap, quick documentation view, everything. I think the user experience is far more pleasant in Idea than in eclipse. Then the motto comes true \"Develop with pleasure\"</p>\n\n<p>Eclipse handles faster larger projects ( +300 jars and +4000 classes ) and I think IntelliJ Idea 8 is working on this.</p>\n\n<p>All this of course is subjective. How can we measure user experience? </p>\n" }, { "answer_id": 241366, "author": "Darron", "author_id": 22704, "author_profile": "https://Stackoverflow.com/users/22704", "pm_score": 4, "selected": false, "text": "<p>Structural search and replace.</p>\n\n<p>For example, search for something like:</p>\n\n<pre><code> System.out.println($string$ + $expr$);\n</code></pre>\n\n<p>Where $string$ is a literal, and $expr$ is an expression of type my.package.and.Class, and then replace with:</p>\n\n<pre><code> $expr$.inspect($string$);\n</code></pre>\n" }, { "answer_id": 241505, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 5, "selected": false, "text": "<p>If you have the cursor on a method then <kbd>CTRL+SHIFT+I</kbd> will popup the method implementation. If the method is an <code>interface</code> method, then you can use up- and down- arrows to cycle through the implementations:</p>\n\n<pre><code>Map&lt;String, Integer&gt; m = ...\nm.contains|Key(\"Wibble\");\n</code></pre>\n\n<p>Where | is (for example) where your cursor is.</p>\n" }, { "answer_id": 245629, "author": "yalestar", "author_id": 2177, "author_profile": "https://Stackoverflow.com/users/2177", "pm_score": 2, "selected": false, "text": "<p>Two things that IntelliJ does that Eclipse doesn't that are very valuable to me:</p>\n\n<p>Method separators: those faint gray lines between methods make code <em>much</em> more readable</p>\n\n<p>Text anti-aliasing: makes code look so nice in the IDE</p>\n" }, { "answer_id": 248026, "author": "Swapnonil Mukherjee", "author_id": 11602, "author_profile": "https://Stackoverflow.com/users/11602", "pm_score": -1, "selected": false, "text": "<p>Show Navigation Bar ALT-Home.</p>\n" }, { "answer_id": 264874, "author": "Gary", "author_id": 396747, "author_profile": "https://Stackoverflow.com/users/396747", "pm_score": 2, "selected": false, "text": "<p>One very useful feature is the ability to partially build a Maven reactor project so that only the parts you need are included. </p>\n\n<p>To make this a little clearer, consider the case of a collection of WAR files with a lot of common resources (e.g. JavaScript, Spring config files etc) being shared between them using the <a href=\"http://maven.apache.org/plugins/maven-war-plugin/examples/war-overlay.html\" rel=\"nofollow noreferrer\">overlay technique</a>. If you are working on some web page (running in Jetty) and want to change some of the overlay code that is held in a separate module then you'd normally expect to have to stop Jetty, run the Maven build, start Jetty again and continue. This is the case with Eclipse and just about every other IDE I've worked with. Not so in IntelliJ. Using the project settings you can define which facet of which module you would like to be included in a background build. Consequently you end up with a process that appears seamless. You make a change to pretty much any code in the project and instantly it is available after you refresh the browser.</p>\n\n<p>Very neat, and very fast.</p>\n\n<p>I couldn't imagine coding a front end in something like YUI backing onto DWR/SpringMVC without it.</p>\n" }, { "answer_id": 282314, "author": "jgindin", "author_id": 17941, "author_profile": "https://Stackoverflow.com/users/17941", "pm_score": 4, "selected": false, "text": "<p>One thing I use regularly is setting a breakpoint, but then controlling what it does. (At my last job, most everyone else used Eclipse... I remember being surprised that no one could find how to do this in Eclipse.)</p>\n\n<p>For example, can have the breakpoint not actually stop, but just log a message to the console. Which means, I don't have to litter my code with \"System.out.println(...)\" and then recompile.</p>\n" }, { "answer_id": 313479, "author": "Daniel Alexiuc", "author_id": 34553, "author_profile": "https://Stackoverflow.com/users/34553", "pm_score": 5, "selected": false, "text": "<p>Don't forget \"compare with clipboard\".</p>\n\n<p>Something that I use all the time in IntelliJ and which has no equivalent in Eclipse.</p>\n" }, { "answer_id": 373522, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 0, "selected": false, "text": "<p>I don't remember if word/line/method/class wrap is possible in Eclipse</p>\n\n<p>In Intellij Idea you use <kbd>Ctrl+W</kbd></p>\n" }, { "answer_id": 389406, "author": "Andrei", "author_id": 2718, "author_profile": "https://Stackoverflow.com/users/2718", "pm_score": 2, "selected": false, "text": "<p>A few other things:</p>\n\n<ul>\n<li>propagate parameters/exceptions when\nchanging method signature, very\nhandy for updating methods deep\ninside the call stack</li>\n<li>SQL code validation in the strings passed as arguments to jdbc calls\n(and the whole newly bundled\nlanguage injection stuff)</li>\n<li>implemented in/overwritten in icons for interfaces &amp; classes (and their methods) and\nthe smart implementation navigation\n(Ctrl+Alt+Click or Ctrl+Alt+B)</li>\n<li>linking between the EJB 2.1 interfaces and bean classes\n(including refactoring support); old\none, but still immensely valuable\nwhen working on older projects</li>\n</ul>\n" }, { "answer_id": 461270, "author": "krosenvold", "author_id": 23691, "author_profile": "https://Stackoverflow.com/users/23691", "pm_score": 5, "selected": false, "text": "<p>Idea 8.0 has the lovely <kbd>ctrl+shift+space</kbd> x 2 that does the following autocomplete:</p>\n\n<pre><code> City city = customer.&lt;ctrl-shift-space twice&gt;\n</code></pre>\n\n<p>resolves to </p>\n\n<pre><code> City city = customer.getAddress().getCity();\n</code></pre>\n\n<p>through any number of levels of getters/setters.</p>\n" }, { "answer_id": 523198, "author": "amit", "author_id": 62237, "author_profile": "https://Stackoverflow.com/users/62237", "pm_score": 6, "selected": false, "text": "<p>There is only one reason I use intellij and not eclipse: <em>Usability</em> </p>\n\n<p>Whether it is debugging, refactoring, auto-completion.. Intellij is much easier to use with consistent key bindings, options available where you look for them etc. Feature-wise, it will be tough for intellij to catch up with Eclipse, as the latter has much more plugins available that intellij, and is easily extensible.</p>\n" }, { "answer_id": 523509, "author": "Peter Lawrey", "author_id": 57695, "author_profile": "https://Stackoverflow.com/users/57695", "pm_score": 2, "selected": false, "text": "<p>Something which I use in IntelliJ all the time is refactoring as I type. I have re-written classes from a printout (originally written in eclipse) using both IDEs and I used about 40% less key strokes/mouse clicks to write the same classes in IntelliJ than eclipse.</p>\n\n<p>I wouldn't want to use Eclipse until they support as much refactoring with incomplete pieces of code.</p>\n\n<p>Here is a longer list of features in IntelliJ 8.0/8.1 [<a href=\"http://www.jetbrains.com/idea/features/index.html]\" rel=\"nofollow noreferrer\">http://www.jetbrains.com/idea/features/index.html]</a></p>\n" }, { "answer_id": 537390, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Far, far, far more refactorings.</p>\n" }, { "answer_id": 578147, "author": "alepuzio", "author_id": 45745, "author_profile": "https://Stackoverflow.com/users/45745", "pm_score": -1, "selected": false, "text": "<p>I not have coded a lot with IntellijIdea, but in IntellijIdea you can see where a block of code between brackets (<em>if, try/catch, cycle, etc</em>) begins and where finish.</p>\n\n<p>In Eclipse (I code in Eclipse 3.2) you can identify the block only manually. </p>\n" }, { "answer_id": 578188, "author": "Jim Dodd", "author_id": 45493, "author_profile": "https://Stackoverflow.com/users/45493", "pm_score": 2, "selected": false, "text": "<p>Preamble to my answer: My use of Eclipse is limited. We needed a Java IDE to work on both Windows and Mac and the Mac port slowed down day by day. This was years ago and I'm sure it's OK now. But that is what got us to switch to IntelliJ and we've been happy with it.</p>\n\n<p>Now for my answer: One big difference I haven't seen mentioned yet is that tech support is better with IntelliJ/Jet Brains. We send an e-mail to JetBrains and get a definitive answer back in less than an hour. Looking for answers to Eclipse problems results in the usual, \"You stupid idiot\" answers (usually a small number of the replies) along with the much larger number of insightful, helpful replies. But it takes some sorting through to get the real answer.</p>\n" }, { "answer_id": 885809, "author": "Paul Morie", "author_id": 73274, "author_profile": "https://Stackoverflow.com/users/73274", "pm_score": 5, "selected": false, "text": "<p>My favorite shortcut in IntelliJ that has no equivalent in Eclipse (that I've found) is called 'Go to symbol'. <kbd>CTRL-ALT-SHIFT-N</kbd> lets you start typing and glob up classes, method names, variable names, etc, from the entire project. </p>\n" }, { "answer_id": 1156334, "author": "rlovtang", "author_id": 141688, "author_profile": "https://Stackoverflow.com/users/141688", "pm_score": 3, "selected": false, "text": "<p>Introduce variable. (<kbd>Ctrl+Alt+V</kbd> on Windows, <kbd>Cmd+Alt+V</kbd> on OSX)</p>\n\n<p>Lets say you call a method, <code>service.listAllPersons()</code>\nHit <kbd>Ctrl+Alt+V</kbd> and <kbd>Enter</kbd>, and variable for return value from method call is inserted:</p>\n\n<pre><code>List&lt;Person&gt; list = service.listAllPersons();\n</code></pre>\n\n<p>Saves you typing, and you don't have to check the return type of the method you are calling. Especially useful when using generics, e.g.</p>\n\n<pre><code>new ArrayList&lt;String&gt;()\n</code></pre>\n\n<p>[introduce variable]</p>\n\n<pre><code>ArrayList&lt;String&gt; stringArrayList = new ArrayList&lt;String&gt;();\n</code></pre>\n\n<p>(of course you can easily change the name of the variable before hitting <kbd>Enter</kbd>)</p>\n" }, { "answer_id": 1156396, "author": "rlovtang", "author_id": 141688, "author_profile": "https://Stackoverflow.com/users/141688", "pm_score": 0, "selected": false, "text": "<p>Open a project from a Maven POM.\nJust select \"Open project...\" navigate to your top level pom.xml and hit Enter :)\nNetBeans now has this feature as well.</p>\n" }, { "answer_id": 1766571, "author": "Piotr Kochański", "author_id": 34102, "author_profile": "https://Stackoverflow.com/users/34102", "pm_score": 1, "selected": false, "text": "<p>I have discovered recently at least two advanteges of IntelliJ IDEA over Eclipse.</p>\n\n<p>If one tries to use code formating in the JSP code editor the JSP scriptlets get broken. Eclipse is getting a little bit crazy, it ads random pieces of code here and there. IDEA behaves very nicely.</p>\n\n<p>The other thing is speed of deployment of the application on the JBoss Server. IntelliJ is replacing the application in the JBoss's tmp folder, so the redeployment is really fast. Eclipse WTP is replacing application in the deploy folder, which, as it turns out, lasts much longer. </p>\n" }, { "answer_id": 2289140, "author": "Tony Ruddock", "author_id": 276127, "author_profile": "https://Stackoverflow.com/users/276127", "pm_score": 3, "selected": false, "text": "<p>Intellij has a far superior SVN plug-in than either Subversive or Subclipse and it works! The amount of time we've wasted merging source files using Eclipse doesn't bear thinking about. This isn't an issue with IntelliJ because the plugin helps you much more. </p>\n\n<p>Also the Subclipse plugin is unreliable - we regularly have instances where the plugin doesn't think there has been any code checked in to SVN by other developers, but there has - the CI server has processed them!</p>\n" }, { "answer_id": 2734193, "author": "mdma", "author_id": 326480, "author_profile": "https://Stackoverflow.com/users/326480", "pm_score": 3, "selected": false, "text": "<p>For me, it's IDEA's maven support, especially in version 9 is second to none. The on-the-fly synchronizing of the project to the maven model is just fantastic and makes development pleasant. </p>\n" }, { "answer_id": 2944692, "author": "Ari", "author_id": 354711, "author_profile": "https://Stackoverflow.com/users/354711", "pm_score": 4, "selected": false, "text": "<p>There are many things that idea solves in a much simpler way, or there's no equivalent:</p>\n\n<ul>\n<li><p>Autocomplete actions: Doing <kbd>ctrl+shift+a</kbd> you can call any idea action from the keyboard without remembering its key combination... Think about gnome-do or launchy in windows, and you've got the idea! Also, this feature supports CamelCasing abbreviations ;)</p></li>\n<li><p>Shelf: Lets you keep easily some pieces of code apart, and then review them through the diff viewer.</p></li>\n<li><p>Local history: It's far better managed, and simpler.</p></li>\n<li><p>SVN annotations and history: simpler to inspect, and also you can easily see the history only for such a part of a whole source file.</p></li>\n<li><p>Autocomplete everywhere, such as the evaluate expression and breakpoint condition windows.</p></li>\n<li><p>Maven integration... much, much simpler, and well integrated.</p></li>\n<li><p>Refactors much closer to the hand, such as loops insertion, wrapping/casting, renaming, and add variables.</p></li>\n<li><p>Find much powerful and well organized. Even in big projects</p></li>\n<li><p>Much stable to work with several branches of a big project at the same time (as a former bugfixer of 1.5Gb by branch sources, and the need to working in them simultaneously, idea shown its rock-solid capabilities)</p></li>\n<li><p>Cleaner and simpler interface...</p></li>\n<li><p>And, simpler to use only with the keyboard, letting apart the need of using the mouse for lots of simple taks, saving you time and giving you more focus on the code... where it matters!</p></li>\n</ul>\n\n<p>And now, being opensource... the Idea user base will grow exponentially.</p>\n" }, { "answer_id": 3034314, "author": "Ville Laitila", "author_id": 325736, "author_profile": "https://Stackoverflow.com/users/325736", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://en.wikipedia.org/wiki/Dataflow_analysis\" rel=\"nofollow noreferrer\">Data flow analysis</a> : inter-procedural backward flow analysis and forward flow analysis, as described <a href=\"http://blogs.jetbrains.com/idea/2009/08/analyzing-dataflow-with-intellij-idea/\" rel=\"nofollow noreferrer\">here</a>. My experiences are based on Community Edition, which does data flow analysis fairly well. It has failed (refused to do anything) in few cases when code is very complex.</p>\n" }, { "answer_id": 3069396, "author": "Maciek Kreft", "author_id": 203459, "author_profile": "https://Stackoverflow.com/users/203459", "pm_score": 2, "selected": false, "text": "<p><strong>VIM</strong> Emulator. This plugin provides nearly complete vi/vim/gvim emulation while editing files in IDEA.\n The following functionality is supported:\n <ul> \n <li>Motion keys</li> \n <li>Deletion/Changing</li> \n <li>Insert mode commands</li> \n <li>Marks</li> \n <li>Registers</li> \n <li>VIM undo/redo</li> \n <li>Visual mode commands</li> \n <li>Some Ex commands</li> \n <li>Some :set options</li> \n <li>Full VIM regular expressions for search and search/replace</li> \n <li>Macros</li> \n <li>Diagraphs</li> \n <li>Command line history</li> \n <li>Search history</li> \n <li>Jumplists</li> \n <li>VIM help</li> \n </ul> </p>\n\n<p>some comments about this plugin from <a href=\"http://plugins.jetbrains.net/plugin/?id=164\" rel=\"nofollow noreferrer\">http://plugins.jetbrains.net/plugin/?id=164</a></p>\n\n \n \n \n I can't see ever going back to any other ide because of this plugin.. \n \n \n \n Best of both worlds... Awesome!. \n \n \n \n that's what i was lacking in all IDEs. \n \n\n" }, { "answer_id": 3654854, "author": "G Craig", "author_id": 440970, "author_profile": "https://Stackoverflow.com/users/440970", "pm_score": 4, "selected": false, "text": "<p>My timing may be a little off in terms of this thread, but I just had to respond.</p>\n\n<p>I am a huge eclipse fan -- using it since it's first appearance. A friend told me then (10+ years ago) that it would be a player. He was right.</p>\n\n<p>However! I have just started using IntelliJ and if you haven't seen or used <b>changelists</b> -- you are missing out on programming heaven.</p>\n\n<p>The ability to track my changed files (on my development branch ala clearcase) was something I was looking for in a plugin for eclipse. Intellij tracks all of your changes for a single commit, extremely easy. You can isolate changed files with custom lists. I use that for configuration files that must be unique locally, but are constantly flagged when I sync or compare against the repository -- listing them under a changelist, I can monitor them, but neatly tuck them away so I can focus on the real additions I am making.</p>\n\n<p>Also, there's a Commit Log plugin that outputs a text of all changes for those SCCS that aren't integrated with your bug tracking software. Pasting the log into a ticket's work history captures the files, their version, date/time, and the branch/tags. It's cool as hell.</p>\n\n<p>All of this could be supported via plugins (or future enhancements) in eclipse, I wager; yet, Intellij makes this a breeze. </p>\n\n<p>Finally, I am really excited about the mainstream love for this product -- the keystrokes, so it's painful, but fun.</p>\n" }, { "answer_id": 4041725, "author": "Shawn Vader", "author_id": 21063, "author_profile": "https://Stackoverflow.com/users/21063", "pm_score": 2, "selected": false, "text": "<p>There is one thing that IntelliJ does much much better than Eclipse and that is empty your pockets! </p>\n\n<p>I do however prefer using it and one big advantage it has over Eclipce is the way it synchronises with the file system, for big projects and slow computers (yes in work environments the PC's are a lot slower than our ones at home) Eclipse seems to struggle where IntelliJ seems to be quicker albeit with a slower initial indexing time.</p>\n\n<p>IntelliJ Community edition obviously makes using it free but you soon want those extra refactoring and nice little goodies not included in the CC edition.</p>\n\n<p>In my opinion, its generally a better user experience but whether its worth the cost is a question for each developer to answer themselves. </p>\n\n<p>But lets be grateful we have up to three great IDEs for Java right now with NetBeans getting better all the time. </p>\n" }, { "answer_id": 4959097, "author": "Herrmann", "author_id": 10575, "author_profile": "https://Stackoverflow.com/users/10575", "pm_score": 2, "selected": false, "text": "<p>One of the good points in my opinion is the <strong>Dependency Structure Matrix</strong>:\n<a href=\"http://www.jetbrains.com/idea/features/dependency_analysis.html#link0\" rel=\"nofollow\">http://www.jetbrains.com/idea/features/dependency_analysis.html#link0</a></p>\n\n<p>There's a good introduction to DSM usage and benefits in Lattix' website (a standalone product):\n<a href=\"http://www.lattix.com/files/dl/slides/s.php?directory=4tour\" rel=\"nofollow\">http://www.lattix.com/files/dl/slides/s.php?directory=4tour</a></p>\n" }, { "answer_id": 4962306, "author": "alphageek", "author_id": 103844, "author_profile": "https://Stackoverflow.com/users/103844", "pm_score": -1, "selected": false, "text": "<p><kbd>Alt+Insert</kbd> to edit text in Column Mode.</p>\n" }, { "answer_id": 6132230, "author": "Scoobie", "author_id": 230814, "author_profile": "https://Stackoverflow.com/users/230814", "pm_score": 1, "selected": false, "text": "<p>At current, it is the only one that can have tabs torn out into another window. Handy when you have more screens.</p>\n" }, { "answer_id": 7338322, "author": "ustad", "author_id": 807367, "author_profile": "https://Stackoverflow.com/users/807367", "pm_score": 0, "selected": false, "text": "<p>Sorry if this is covered already, but simply having the 'changes' tab there where I can see my local changes, incoming changes, remote changes is just simply something I can't live without.. In Eclipse, I can't find such a feature! </p>\n\n<p>Also just a simple thing like middle clicking which binds to the 'open declaration' is a great UI addition - something I also cannot see implemented in Eclipse.</p>\n\n<p>There is only Eclipse at my work place but I'm seriously thinking of purchasing a personal Idea license....</p>\n" }, { "answer_id": 8156835, "author": "blicket", "author_id": 1050289, "author_profile": "https://Stackoverflow.com/users/1050289", "pm_score": 2, "selected": false, "text": "<p>First of all I love intellij. There are at least a hundred features it has that eclipse lack. I'm talking magnitudes better in reliability and intelligence that no hyperbole can describe when it comes to refactoring, renaming, moving and others which have already been mentioned.</p>\n\n<p>BUT, there is one thing that intellij does not allow which eclipse does. It does not allow running multiple projects at once under the same vm. </p>\n\n<p>When you have separate projects for the front, middle, core, agents..etc, where they all have to interact with each other, you can not quickly modify and debug at the same time, afaik. The only way I current cope with this is to use ant scripts to deploy and update jars in dependent projects, or use maven. </p>\n\n<p>Eclipse allows multiple projects to be debugged under one ide vm instance. </p>\n" }, { "answer_id": 8959080, "author": "TomW", "author_id": 858627, "author_profile": "https://Stackoverflow.com/users/858627", "pm_score": 0, "selected": false, "text": "<p>In IntelliJ, one can jump through a history of the last places edited with \"Last Edit Location\". Eclipse has a similar feature but Eclipse only goes back to one level of edit location. </p>\n\n<p>Having the history rather than just the one level that Eclipse offers is a great productivity feature: it acts as a form of auto-bookmarking, since you often want to jump back to the places where you have been making changes. I use this ability several times a day, and feel the pain of not having it when I am asked to use Eclipse for something.</p>\n" }, { "answer_id": 16624173, "author": "passsy", "author_id": 669294, "author_profile": "https://Stackoverflow.com/users/669294", "pm_score": 5, "selected": false, "text": "<p>I tried to switch to IntelliJ because of the new Android Studio. But I'm very disappointed now. I'm using Eclipse with the <strong>Code Recommanders</strong> Plugin. Here is a simple example why Eclipse is so awesome:</p>\n\n<p>I want to create a new <code>SimpleTimeZone</code>. <code>SimpleTimeZone</code> has no Constructor with zero arguments.</p>\n\n<p><kbd>Ctrl + Space</kbd> in Eclipse</p>\n\n<p><img src=\"https://i.stack.imgur.com/RAmrm.png\" alt=\"enter image description here\"></p>\n\n<p><kbd>Ctrl + Space</kbd> in IntelliJ</p>\n\n<p><img src=\"https://i.stack.imgur.com/HLH3M.png\" alt=\"enter image description here\"></p>\n\n<p>In IntelliJ I get no informations what kind of constructors <code>SimpleTimeZone</code> has.</p>\n\n<p>After <kbd>Enter</kbd> in Eclipse</p>\n\n<p><img src=\"https://i.stack.imgur.com/Rqj5y.png\" alt=\"enter image description here\"></p>\n\n<p>I get the previously selected constructor filled with predefined variable names. And I can see the type of every argument. With Code Recommanders Eclipse guesses the right constructor by the previously defined variable types in the current scope and fills the constructor with these vars.</p>\n\n<p>After <kbd>Enter</kbd> in IntelliJ nothing happens. I get an empty constructor. I have to press <kbd>Ctrl + P</kbd> to see the expected arguments.</p>\n\n<p><img src=\"https://i.stack.imgur.com/Ky67Y.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 22037421, "author": "CuNimb", "author_id": 1372914, "author_profile": "https://Stackoverflow.com/users/1372914", "pm_score": 0, "selected": false, "text": "<p>There are a number of features and workflows that are different in the two, as is evident in all the answers. However, I think that in deciding what framework to use one much also consider the general productivity improvement one can make with each tool.</p>\n\n<p>I am a big fan of Netbeans and Eclipse and have used both for many years. They are excellent tools and depending on what you are doing, you may want to choose one or the other.</p>\n\n<p>However, about six months ago, while working on a complex java web project involving a lot of javascript front end code for a HMT5 ui, I was forced to look for alternatives to Eclipse due to a js autocomplete bug. I was so desperate that I was considering going back to a simple text editor for my js code!!!</p>\n\n<p>It is only by luck that I ran across Intellij Idea (no time to research tools unfortunately).</p>\n\n<p>While it takes some time to get used to the Idea way of doing things, special features aside, the productivity increase it offers from small things left and right is the biggest asset in my opinion. It simply works better for me and I am now a subscription-paying client of Idea Ultimate. Once you get used to this, its is very difficult to go back to anything else.</p>\n\n<p>Nothing beats free and I am a big fan of open source, but in the end if you are doing this for a living, being able to do things faster pays out every time.</p>\n" }, { "answer_id": 22812079, "author": "Ali Motevallian", "author_id": 1186837, "author_profile": "https://Stackoverflow.com/users/1186837", "pm_score": 0, "selected": false, "text": "<p>I think you can stick to either of these IDEs.\nThe best sign to not to \"worry about missing a giant benefit in the IDE you are not using\" is the very long arguments we have seen between Eclipse fans and IntelliJ fans. This is a good sign that both sides have almost the same power which has led this long discussion to survive. </p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
I have heard from people who have switched either way and who swear by the one or the other. Being a huge Eclipse fan but having not had the time to try out IntelliJ, I am interested in hearing from IntelliJ users who are "ex-Eclipsians" some specific things that you can do with IntelliJ that you can not do with Eclipse. **Note**: This is not a subjective question nor at all meant to turn into an IDE holy war. ***Please downvote any flamebait answers***.
CTRL-click works anywhere ------------------------- CTRL-click that brings you to where clicked object is defined works everywhere - not only in Java classes and variables in Java code, but in Spring configuration (you can click on class name, or property, or bean name), in Hibernate (you can click on property name or class, or included resource), you can navigate within one click from Java class to where it is used as Spring or Hibernate bean; clicking on included JSP or JSTL tag also works, ctrl-click on JavaScript variable or function brings you to the place it is defined or shows a menu if there are more than one place, including other .js files and JS code in HTML or JSP files. Autocomplete for many languagues -------------------------------- ### Hibernate Autocomplete in HSQL expressions, in Hibernate configuration (including class, property and DB column names), in Spring configuration ``` <property name="propName" ref="<hit CTRL-SPACE>" ``` and it will show you list of those beans which you can inject into that property. ### Java Very smart autocomplete in Java code: ``` interface Person { String getName(); String getAddress(); int getAge(); } //--- Person p; String name = p.<CTRL-SHIFT-SPACE> ``` and it shows you ONLY *getName()*, *getAddress()* and *toString()* (only they are compatible by type) and *getName()* is first in the list because it has more relevant name. Latest version 8 which is still in EAP has even more smart autocomplete. ``` interface Country{ } interface Address { String getStreetAddress(); String getZipCode(); Country getCountry(); } interface Person { String getName(); Address getAddress(); int getAge(); } //--- Person p; Country c = p.<CTRL-SHIFT-SPACE> ``` and it will silently autocomplete it to ``` Country c = p.getAddress().getCountry(); ``` ### Javascript Smart autocomplete in JavaScript. ``` function Person(name,address) { this.getName = function() { return name }; this.getAddress = function() { return address }; } Person.prototype.hello = function() { return "I'm " + this.getName() + " from " + this.get<CTRL-SPACE>; } ``` and it shows ONLY *getName()* and *getAddress()*, no matter how may get\* methods you have in other JS objects in your project, and ctrl-click on *this.getName()* brings you to where this one is defined, even if there are some other *getName()* functions in your project. ### HTML Did I mention autocomplete and ctrl-clicking in paths to files, like <script src="", <img src="", etc? Autocomplete in HTML tag attributes. Autocomplete in style attribute of HTML tags, both attribute names and values. Autocomplete in class attributes as well. Type <div class="<CTRL-SPACE> and it will show you list of CSS classes defined in your project. Pick one, ctrl-click on it and you will be redirected to where it is defined. ### Easy own language higlighting Latest version has language injection, so you can declare that you custom JSTL tag usually contains JavaScript and it will highlight JavaScript inside it. ``` <ui:obfuscateJavaScript>function something(){...}</ui:obfuscateJavaScript> ``` Indexed search across all project. ---------------------------------- You can use Find Usages of any Java class or method and it will find where it is used including not only Java classes but Hibernate, Spring, JSP and other places. Rename Method refactoring renames method not only in Java classes but anywhere including comments (it can not be sure if string in comments is really method name so it will ask). And it will find only your method even if there are methods of another class with same name. Good source control integration (does SVN support changelists? IDEA support them for every source control), ability to create a patch with your changes so you can send your changes to other team member without committing them. Improved debugger ----------------- When I look at *HashMap* in debugger's watch window, I see logical view - keys and values, last time I did it in Eclipse it was showing entries with hash and next fields - I'm not really debugging *HashMap*, I just want to look at it contents. Spring & Hibernate configuration validation ------------------------------------------- It validates Spring and Hibernate configuration right when you edit it, so I do not need to restart server to know that I misspelled class name, or added constructor parameter so my Spring cfg is invalid. Last time I tried, I could not run Eclipse on Windows XP x64. and it will suggest you *person.name* or *person.address*. Ctrl-click on *person.name* and it will navigate you to *getName()* method of *Person* class. Type `Pattern.compile("");` put \\ there, hit CTRL-SPACE and see helpful hint about what you can put into your regular expression. You can also use language injection here - define your own method that takes string parameter, declare in IntelliLang options dialog that your parameter is regular expression - and it will give you autocomplete there as well. Needless to say it highlights incorrect regular expressions. Other features -------------- There are few features which I'm not sure are present in Eclipse or not. But at least each member of our team who uses Eclipse, also uses some merging tool to merge local changes with changes from source control, usually WinMerge. I never need it - merging in IDEA is enough for me. By 3 clicks I can see list of file versions in source control, by 3 more clicks I can compare previous versions, or previous and current one and possibly merge. It allows to to specify that I need all .jars inside `WEB-INF\lib` folder, without picking each file separately, so when someone commits new .jar into that folder it picks it up automatically. Mentioned above is probably 10% of what it does. I do not use Maven, Flex, Swing, EJB and a lot of other stuff, so I can not tell how it helps with them. But it does.
239,744
<p>I'm developing a SWT/JFace application using the libraries from Eclipse 3.4.1. I encounter the following problem on Windows (Vista 32bit) and Ubuntu 8.10 32bit:</p> <p>I create a menu bar in the createMenuManager method of the JFace ApplicationWindow. I add MenuManagers for file, edit and help.</p> <p>I then add an ExitAction to the file MenuManager like so:</p> <pre><code>filemenu.add(new ExitAction(this)); </code></pre> <p>The ExitAction is defined this way:</p> <pre><code>public class ExitAction extends Action { final ApplicationWindow window; public ExitAction(ApplicationWindow w) { this.window = w; setText("E&amp;xit"); setToolTipText("Exit the application"); setAccelerator(SWT.MOD1 + 'Q'); } } </code></pre> <p>Now when my application starts I want be able to press "CTRL+Q" to quit the application. This does however not work. Only AFTER I click on "File" in the menu bar and THEN clicking "CTRL+Q" the application will quit.</p> <p>I've tried this with different accelerators- same behavior.</p> <p>It does work however if I create a "MenuItem" instead of an "Action" to contribute to the menu bar.</p> <p>Is this a SWT bug or do I miss something?</p> <p>Torsten.</p>
[ { "answer_id": 247334, "author": "the.duckman", "author_id": 21368, "author_profile": "https://Stackoverflow.com/users/21368", "pm_score": 0, "selected": false, "text": "<p>AFAIK <code>setAccelerator(.)</code> does nothing else than adding the appropriate text to your <code>MenuItem</code>. You are responsible to register for an <code>KeyUp</code> event and react on it.</p>\n\n<p>You can use <code>Display.addFilter(SWT.KeyUp, myListener)</code> to register your <code>Listener</code> independently of your widgets.</p>\n" }, { "answer_id": 264839, "author": "Torsten Uhlmann", "author_id": 7143, "author_profile": "https://Stackoverflow.com/users/7143", "pm_score": 0, "selected": false, "text": "<p>Turns out that this is a bug in Eclipse 3.4.\nI have submitted a bug report: <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=253078\" rel=\"nofollow noreferrer\">https://bugs.eclipse.org/bugs/show_bug.cgi?id=253078</a></p>\n" }, { "answer_id": 265135, "author": "Torsten Uhlmann", "author_id": 7143, "author_profile": "https://Stackoverflow.com/users/7143", "pm_score": 2, "selected": true, "text": "<p>Update: There is a duplicate bug of mine which also contains a workaround.\nThe bug url is: <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=243758\" rel=\"nofollow noreferrer\">https://bugs.eclipse.org/bugs/show_bug.cgi?id=243758</a></p>\n\n<p>Basically the workaround is to call <code>create()</code> on the <code>ApplicationWindow</code> and then <code>getMenuBarManager().updateAll(true);</code> which will force all menu items to get initialized.</p>\n\n<p>Of course you have to call the above methods after you created the menu items.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239744", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7143/" ]
I'm developing a SWT/JFace application using the libraries from Eclipse 3.4.1. I encounter the following problem on Windows (Vista 32bit) and Ubuntu 8.10 32bit: I create a menu bar in the createMenuManager method of the JFace ApplicationWindow. I add MenuManagers for file, edit and help. I then add an ExitAction to the file MenuManager like so: ``` filemenu.add(new ExitAction(this)); ``` The ExitAction is defined this way: ``` public class ExitAction extends Action { final ApplicationWindow window; public ExitAction(ApplicationWindow w) { this.window = w; setText("E&xit"); setToolTipText("Exit the application"); setAccelerator(SWT.MOD1 + 'Q'); } } ``` Now when my application starts I want be able to press "CTRL+Q" to quit the application. This does however not work. Only AFTER I click on "File" in the menu bar and THEN clicking "CTRL+Q" the application will quit. I've tried this with different accelerators- same behavior. It does work however if I create a "MenuItem" instead of an "Action" to contribute to the menu bar. Is this a SWT bug or do I miss something? Torsten.
Update: There is a duplicate bug of mine which also contains a workaround. The bug url is: <https://bugs.eclipse.org/bugs/show_bug.cgi?id=243758> Basically the workaround is to call `create()` on the `ApplicationWindow` and then `getMenuBarManager().updateAll(true);` which will force all menu items to get initialized. Of course you have to call the above methods after you created the menu items.
239,746
<p>What is the correct way to check if a value is a date/number in Delphi?</p> <p>I know other languages have functions like isDate and isNaN, but what is the Delphi equivalent? at the minute I have this</p> <pre><code>function isNumeric(s1:string):boolean; begin // will throw exception if its not a number // there must be a better way to do this!! try StrTofloat(s1); result := TRUE ; except result := FALSE; end; end; </code></pre> <p>But throwing exceptions cant be good, and it makes debugging hard as I keep seeing the exception dialogue every time the code is called.</p>
[ { "answer_id": 239751, "author": "Alan", "author_id": 31223, "author_profile": "https://Stackoverflow.com/users/31223", "pm_score": 5, "selected": true, "text": "<p>For integers, you could use TryStrToInt to check and convert without throwing exceptions:</p>\n\n<pre><code>function TryStrToInt(const s: string; out i : integer): boolean;\n</code></pre>\n\n<p>I'm not absolutely sure there is a full equivalent for floats, though, so you might need to use StrToFloat() and accept the possibility of a TFormatException. </p>\n" }, { "answer_id": 239757, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 2, "selected": false, "text": "<p>There's a family of functions like <code>TryStrToFloat</code>, <code>TryStrToDateTime</code> etc. which do that. By the way, <code>StrToFloat</code> and others use the \"Try\" versions internally before raising exceptions.</p>\n" }, { "answer_id": 239774, "author": "Cruachan", "author_id": 7315, "author_profile": "https://Stackoverflow.com/users/7315", "pm_score": 2, "selected": false, "text": "<p>Firstly StrToFloatDef function is a useful alternative here if you want to stay in the language as delivered out the box. </p>\n\n<p>However your best option is to deploy the JEDI code libraries (<a href=\"http://www.delphi-jedi.org/\" rel=\"nofollow noreferrer\">http://www.delphi-jedi.org/</a>) and use the StrIsNumber function from there.</p>\n\n<p>JEDI is open source, highly useful in lots of ways, and pretty much a must anyway.</p>\n" }, { "answer_id": 240209, "author": "skamradt", "author_id": 9217, "author_profile": "https://Stackoverflow.com/users/9217", "pm_score": 0, "selected": false, "text": "<p>You CAN turn off the annoying exceptions you don't want by checking the \"ignore this exception\" box that pops up. Future exceptions will be then ignored for that exception class. To start asking again, just go to the Options|Debugger Options and uncheck the ones you are ignoring.</p>\n" }, { "answer_id": 241293, "author": "Kroden", "author_id": 31302, "author_profile": "https://Stackoverflow.com/users/31302", "pm_score": 2, "selected": false, "text": "<p>Catching exceptions is very slow. If you plan on using such a function repeatedly in rapid succession, such as when validating fields during a file import, it might be worth it to roll your own function that does some simple character level checking before falling into a try/except block. I've used something similar before with a huge performance increase when parsing large amounts of data that was not in the correct format.</p>\n\n<pre>\nfunction IsNumeric(aValue : string): boolean;\nvar\n i : integer;\nbegin\n result := false;\n for i := 1 to Length(aValue) do\n if (NOT (aValue[i] in ['0'..'9', '.', '-', '+', 'E', 'e'])) then\n exit;\n try\n StrToFloat(aValue);\n result := true;\n except\n end;\nend;\n</pre>\n\n<p>Obviously this may not be perfect, and has the limitation of hard-coded values in it. Depends entirely on your needs, this was just something simple that worked well for an internal process.</p>\n" }, { "answer_id": 51294403, "author": "user10067253", "author_id": 10067253, "author_profile": "https://Stackoverflow.com/users/10067253", "pm_score": 1, "selected": false, "text": "<p>I use strtointdef(singlecharacter,-1)</p>\n\n<pre><code>procedure TForm1.Button1Click(Sender: TObject);\nvar\nx,i:integer;\nteststring:string;\n\nbegin\nteststring:='1235';\nfor i:=1 to length(teststring) do begin\n x:= strtointdef(teststring[i],-1);\n if x=-1 then break;\nend;\nif x&lt;0 then showmessage('not numeric')\nelse showmessage('numeric');\n\nend;\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2098/" ]
What is the correct way to check if a value is a date/number in Delphi? I know other languages have functions like isDate and isNaN, but what is the Delphi equivalent? at the minute I have this ``` function isNumeric(s1:string):boolean; begin // will throw exception if its not a number // there must be a better way to do this!! try StrTofloat(s1); result := TRUE ; except result := FALSE; end; end; ``` But throwing exceptions cant be good, and it makes debugging hard as I keep seeing the exception dialogue every time the code is called.
For integers, you could use TryStrToInt to check and convert without throwing exceptions: ``` function TryStrToInt(const s: string; out i : integer): boolean; ``` I'm not absolutely sure there is a full equivalent for floats, though, so you might need to use StrToFloat() and accept the possibility of a TFormatException.
239,786
<p>I have put together the following mootools script</p> <pre><code> window.addEvent('domready', function() { var shouts = "timed.php"; var log = $('log_res'); function updateData (url,target) { new Ajax(url,{ method: 'get', update: $(target), onComplete: function() { log.removeClass('ajax-loading');} }).request(); log.empty().addClass('ajax-loading'); } var update = function(){ updateData ( shouts, 'log_res' ); }; update(); // call it immediately update.periodical(10000); // and then periodically }); </code></pre> <p>heres the html</p> <pre><code>&lt;div id="AJAX"&gt; &lt;h3&gt;Ajax Response&lt;/h3&gt; &lt;div id="log_res"&gt;exercise&lt;/div&gt; &lt;/div&gt; </code></pre> <p>its using moo 1.1.</p> <p>The above works fine, the page loads then the ajax request kicks in div id log_res has a class of ajax-loading whilst its updating, and when its finished the text exercise in the div is replaced with whatever the ajax has returned (yippee). But I want to put some custom HTML into the div WHILST the page is loading, because the ajax-loading class is not enough to contain the information, i also want to put a spinny flasher into the div whilst the ajax request is retrieving the information. Hope that makes sense!</p>
[ { "answer_id": 239869, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": true, "text": "<p>With MooTools 1.2, this works as requested:</p>\n\n<pre><code>function updateData (url, target)\n{\n var target = $(target);\n target.empty().addClass('ajax-loading');\n target.innerHTML = \"Loading...\";\n new Request({\n url: url, \n method: 'get',\n onComplete: function(responseText) {\n target.removeClass('ajax-loading');\n target.innerHTML = responseText;\n }\n }).send();\n}\n</code></pre>\n\n<p>Since you are no fun and use MooTools 1.1, I must dig a little... Actually, I got it working using nearly the same setup as you have (notice I use <code>target</code> instead of <code>log</code>, which was defined outside of the scope of this function):</p>\n\n<pre><code>function updateData (url, target)\n{\n var target = $(target);\n target.empty().addClass('ajax-loading');\n target.innerHTML = \"Loading...\";\n new Ajax(url, {\n method: 'get',\n update: target,\n onComplete: function() {\n target.removeClass('ajax-loading');\n }\n }).request();\n}\n</code></pre>\n" }, { "answer_id": 241716, "author": "Tom Haigh", "author_id": 22224, "author_profile": "https://Stackoverflow.com/users/22224", "pm_score": 1, "selected": false, "text": "<p>Can you not do something like this:</p>\n\n<pre><code>function updateData (url, target)\n{\n var target = $(target);\n target.innerHTML = 'Please wait...';\n\n //and the rest of the function\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28241/" ]
I have put together the following mootools script ``` window.addEvent('domready', function() { var shouts = "timed.php"; var log = $('log_res'); function updateData (url,target) { new Ajax(url,{ method: 'get', update: $(target), onComplete: function() { log.removeClass('ajax-loading');} }).request(); log.empty().addClass('ajax-loading'); } var update = function(){ updateData ( shouts, 'log_res' ); }; update(); // call it immediately update.periodical(10000); // and then periodically }); ``` heres the html ``` <div id="AJAX"> <h3>Ajax Response</h3> <div id="log_res">exercise</div> </div> ``` its using moo 1.1. The above works fine, the page loads then the ajax request kicks in div id log\_res has a class of ajax-loading whilst its updating, and when its finished the text exercise in the div is replaced with whatever the ajax has returned (yippee). But I want to put some custom HTML into the div WHILST the page is loading, because the ajax-loading class is not enough to contain the information, i also want to put a spinny flasher into the div whilst the ajax request is retrieving the information. Hope that makes sense!
With MooTools 1.2, this works as requested: ``` function updateData (url, target) { var target = $(target); target.empty().addClass('ajax-loading'); target.innerHTML = "Loading..."; new Request({ url: url, method: 'get', onComplete: function(responseText) { target.removeClass('ajax-loading'); target.innerHTML = responseText; } }).send(); } ``` Since you are no fun and use MooTools 1.1, I must dig a little... Actually, I got it working using nearly the same setup as you have (notice I use `target` instead of `log`, which was defined outside of the scope of this function): ``` function updateData (url, target) { var target = $(target); target.empty().addClass('ajax-loading'); target.innerHTML = "Loading..."; new Ajax(url, { method: 'get', update: target, onComplete: function() { target.removeClass('ajax-loading'); } }).request(); } ```
239,802
<p>I'm writing an app where 3rd party vendors can write plugin DLLs and drop them into the web app's bin directory. I want the ability for these plugins to be able to register their own HttpModules if necessary. </p> <p>Is there anyway that I can add or remove HttpModules from and to the pipeline at runtime without having a corresponding entry in the Web.Config, or do I have to programmatically edit the Web.Config when adding / removing modules? I know that either way is going to cause an AppDomain restart but I'd rather be able to do it in code than having to fudge the web.config to achieve the same effect. </p>
[ { "answer_id": 240110, "author": "Aaron Fischer", "author_id": 5618, "author_profile": "https://Stackoverflow.com/users/5618", "pm_score": 7, "selected": true, "text": "<blockquote>\n <p>It has to be done at just the right\n time in the HttpApplication life cycle\n which is when the HttpApplication\n object initializes (multiple times,\n once for each instance of\n HttpApplication). The only method\n where this works correct is\n HttpApplication Init().</p>\n \n <p>To hook up a module via code you can\n run code like the following instead of\n the HttpModule definition in\n web.config:</p>\n\n<pre><code> public class Global : System.Web.HttpApplication\n {\n // some modules use explicit interface implementation\n // by declaring this static member as the IHttpModule interface\n // we work around that\n public static IHttpModule Module = new xrnsToashxMappingModule();\n public override void Init()\n {\n base.Init();\n Module.Init(this);\n }\n }\n</code></pre>\n \n <p>All you do is override the HttpApplication's Init() method and\n then access the static instance's Init\n method. Init() of the module hooks up\n the event and off you go.</p>\n</blockquote>\n\n<p>Via <a href=\"http://www.west-wind.com/weblog/posts/44979.aspx\" rel=\"noreferrer\">Rick Strahl's blog</a></p>\n" }, { "answer_id": 3158765, "author": "Nikhil Kothari", "author_id": 40999, "author_profile": "https://Stackoverflow.com/users/40999", "pm_score": 5, "selected": false, "text": "<p>Realize this is an old question, but asp.net 4 provides some new capabilities that can help here.</p>\n\n<p>Specifically, ASP.NET 4 provides a <code>PreApplicationStartMethod</code> capability that can be used to add HttpModules programmatically.</p>\n\n<p>I just did a blog post on that at <a href=\"https://web.archive.org/web/20120719043729/http://www.nikhilk.net/Config-Free-HttpModule-Registration.aspx\" rel=\"nofollow noreferrer\">http://www.nikhilk.net/Config-Free-HttpModule-Registration.aspx</a>.</p>\n\n<p>The basic idea is you create a derived <code>HttpApplication</code> that provides ability to add HttpModules dynamically at startup time, and it then initializes them into the pipeline whenever each <code>HttpApplication</code> instance is created within the app-domain.</p>\n" }, { "answer_id": 4285836, "author": "Chris van de Steeg", "author_id": 336130, "author_profile": "https://Stackoverflow.com/users/336130", "pm_score": 4, "selected": false, "text": "<p>The dll Microsoft.Web.Infrastructure.dll has a method for this inside the class DynamicModuleUtility.\nThe dll is shipped with WebPages 1.0</p>\n\n<pre><code>public static class PreApplicationStartCode\n{\n private static bool _startWasCalled;\n\n public static void Start()\n {\n if (_startWasCalled) return;\n\n _startWasCalled = true;\n DynamicModuleUtility.RegisterModule(typeof(EventTriggeringHttpModule));\n }\n}\n</code></pre>\n" }, { "answer_id": 41058680, "author": "Peter Morris", "author_id": 61311, "author_profile": "https://Stackoverflow.com/users/61311", "pm_score": 2, "selected": false, "text": "<p>In new versions of ASP MVC you can use Package Manager to add a reference to WebActivatorX and then do something like this</p>\n\n<pre><code>using WhateverNameSpacesYouNeed;\n\n[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(YourApp.SomeNameSpace.YourClass), \"Initialize\")]\nnamespace YourApp.SomeNameSpace\n{\n public static void Initialize()\n {\n DynamicModuleUtility.RegisterModule( ... the type that implements IHttpModule ... );\n }\n}\n</code></pre>\n" }, { "answer_id": 54097973, "author": "Jesse", "author_id": 689411, "author_profile": "https://Stackoverflow.com/users/689411", "pm_score": 2, "selected": false, "text": "<p>This worked for me for dynamic registration.</p>\n\n<pre><code>RegisterModule(typeof(RequestLoggerModule));\n\npublic class RequestLoggerModule : IHttpModule\n { ... }\n</code></pre>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.web.httpapplication.registermodule?view=netframework-4.7.2\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.web.httpapplication.registermodule?view=netframework-4.7.2</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239802", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2285/" ]
I'm writing an app where 3rd party vendors can write plugin DLLs and drop them into the web app's bin directory. I want the ability for these plugins to be able to register their own HttpModules if necessary. Is there anyway that I can add or remove HttpModules from and to the pipeline at runtime without having a corresponding entry in the Web.Config, or do I have to programmatically edit the Web.Config when adding / removing modules? I know that either way is going to cause an AppDomain restart but I'd rather be able to do it in code than having to fudge the web.config to achieve the same effect.
> > It has to be done at just the right > time in the HttpApplication life cycle > which is when the HttpApplication > object initializes (multiple times, > once for each instance of > HttpApplication). The only method > where this works correct is > HttpApplication Init(). > > > To hook up a module via code you can > run code like the following instead of > the HttpModule definition in > web.config: > > > > ``` > public class Global : System.Web.HttpApplication > { > // some modules use explicit interface implementation > // by declaring this static member as the IHttpModule interface > // we work around that > public static IHttpModule Module = new xrnsToashxMappingModule(); > public override void Init() > { > base.Init(); > Module.Init(this); > } > } > > ``` > > All you do is override the HttpApplication's Init() method and > then access the static instance's Init > method. Init() of the module hooks up > the event and off you go. > > > Via [Rick Strahl's blog](http://www.west-wind.com/weblog/posts/44979.aspx)
239,823
<p>According <a href="http://msdn.microsoft.com/en-us/library/y3bwdsh3.aspx" rel="noreferrer">this MSDN article</a> <em>HttpApplication</em>.EndRequest can be used to close or dispose of resources. However this event is not fired/called in my application.</p> <p>We are attaching the handler in Page_Load the following way:</p> <pre><code>HttpContext.Current.ApplicationInstance.EndRequest += ApplicationInstance_EndRequest; </code></pre> <p>The only way is to use the Application_EndRequest handler in Global.asax, but this is not acceptable for us. </p>
[ { "answer_id": 239848, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>The page is probably being disposed before the event fires. You might want to try to do your work in the Page_Unload handler.</p>\n" }, { "answer_id": 239999, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 3, "selected": false, "text": "<p>Per the MSDN documentation, this event occurs AFTER the page is completed, just like BeginRequest. Therefore as far as I know it is not possible to catch this at the page level</p>\n" }, { "answer_id": 240199, "author": "Eduardo Campañó", "author_id": 12091, "author_profile": "https://Stackoverflow.com/users/12091", "pm_score": 5, "selected": true, "text": "<p>You can use your own HttpModule to capture the EndRequest if you don't want to use the global.asax.</p>\n\n<pre><code>public class CustomModule : IHttpModule \n{\n public void Init(HttpApplication context)\n {\n context.EndRequest += new EventHandler(context_EndRequest);\n }\n\n private void context_EndRequest(object sender, EventArgs e)\n {\n HttpContext context = ((HttpApplication)sender).Context;\n // use your contect here\n }\n}\n</code></pre>\n\n<p>You need to add the module to your web.config</p>\n\n<pre><code>&lt;httpModules&gt;\n &lt;add name=\"CustomModule\" type=\"CustomModule\"/&gt;\n&lt;/httpModules&gt;\n</code></pre>\n" }, { "answer_id": 4834596, "author": "crokusek", "author_id": 538763, "author_profile": "https://Stackoverflow.com/users/538763", "pm_score": 2, "selected": false, "text": "<p>I believe a better way to chain this event is by providing a base class to global.asax</p>\n\n<pre><code>Language=\"C#\" Inherits=\"YourBaseClass\"\n</code></pre>\n\n<p>and then overriding Init():</p>\n\n<pre><code>public override void Init()\n{\n base.Init();\n\n BeginRequest += new EventHandler(OnBeginRequest);\n EndRequest += new EventHandler(OnEndRequest);\n}\n</code></pre>\n\n<p>seems to be working for me (catch a breakpoint) but I'm really doing anything with it.</p>\n\n<p>Since there are multiple HttpApplication instances, setting it within Page_load may keep adding it to a non-specific instance. Oddly, I've also noticed that HttpApplication.Init() does not get called for the very first HttpApplication instance (but Application_start) does.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18859/" ]
According [this MSDN article](http://msdn.microsoft.com/en-us/library/y3bwdsh3.aspx) *HttpApplication*.EndRequest can be used to close or dispose of resources. However this event is not fired/called in my application. We are attaching the handler in Page\_Load the following way: ``` HttpContext.Current.ApplicationInstance.EndRequest += ApplicationInstance_EndRequest; ``` The only way is to use the Application\_EndRequest handler in Global.asax, but this is not acceptable for us.
You can use your own HttpModule to capture the EndRequest if you don't want to use the global.asax. ``` public class CustomModule : IHttpModule { public void Init(HttpApplication context) { context.EndRequest += new EventHandler(context_EndRequest); } private void context_EndRequest(object sender, EventArgs e) { HttpContext context = ((HttpApplication)sender).Context; // use your contect here } } ``` You need to add the module to your web.config ``` <httpModules> <add name="CustomModule" type="CustomModule"/> </httpModules> ```
239,865
<p>All numbers that divide evenly into x.</p> <p>I put in 4 it returns: 4, 2, 1</p> <p>edit: I know it sounds homeworky. I'm writing a little app to populate some product tables with semi random test data. Two of the properties are ItemMaximum and Item Multiplier. I need to make sure that the multiplier does not create an illogical situation where buying 1 more item would put the order over the maximum allowed. Thus the factors will give a list of valid values for my test data.</p> <p>edit++: This is what I went with after all the help from everyone. Thanks again!</p> <p>edit#: I wrote 3 different versions to see which I liked better and tested them against factoring small numbers and very large numbers. I'll paste the results.</p> <pre><code>static IEnumerable&lt;int&gt; GetFactors2(int n) { return from a in Enumerable.Range(1, n) where n % a == 0 select a; } private IEnumerable&lt;int&gt; GetFactors3(int x) { for (int factor = 1; factor * factor &lt;= x; factor++) { if (x % factor == 0) { yield return factor; if (factor * factor != x) yield return x / factor; } } } private IEnumerable&lt;int&gt; GetFactors1(int x) { int max = (int)Math.Ceiling(Math.Sqrt(x)); for (int factor = 1; factor &lt; max; factor++) { if(x % factor == 0) { yield return factor; if(factor != max) yield return x / factor; } } } </code></pre> <p>In ticks. When factoring the number 20, 5 times each:</p> <ul> <li>GetFactors1-5,445,881</li> <li>GetFactors2-4,308,234</li> <li>GetFactors3-2,913,659 </li> </ul> <p>When factoring the number 20000, 5 times each:</p> <ul> <li>GetFactors1-5,644,457</li> <li>GetFactors2-12,117,938</li> <li>GetFactors3-3,108,182</li> </ul>
[ { "answer_id": 239877, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 6, "selected": true, "text": "<p>pseudocode:</p>\n<ul>\n<li>Loop from 1 to the square root of the number, call the index &quot;i&quot;.</li>\n<li>if number mod i is 0, add i and number / i to the list of factors.</li>\n</ul>\n<p>realocode:</p>\n<pre><code>public List&lt;int&gt; Factor(int number) \n{\n var factors = new List&lt;int&gt;();\n int max = (int)Math.Sqrt(number); // Round down\n\n for (int factor = 1; factor &lt;= max; ++factor) // Test from 1 to the square root, or the int below it, inclusive.\n { \n if (number % factor == 0) \n {\n factors.Add(factor);\n if (factor != number/factor) // Don't add the square root twice! Thanks Jon\n factors.Add(number/factor);\n }\n }\n return factors;\n}\n</code></pre>\n<p>As Jon Skeet mentioned, you could implement this as an <code>IEnumerable&lt;int&gt;</code> as well - use <a href=\"http://msdn.microsoft.com/en-us/library/9k7k7cf0(VS.80).aspx\" rel=\"nofollow noreferrer\">yield</a> instead of adding to a list. The advantage with <code>List&lt;int&gt;</code> is that it could be sorted before return if required. Then again, you could get a sorted enumerator with a hybrid approach, yielding the first factor and storing the second one in each iteration of the loop, then yielding each value that was stored in reverse order.</p>\n<p>You will also want to do something to handle the case where a negative number passed into the function.</p>\n" }, { "answer_id": 239884, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "<p>The <code>%</code> (remainder) operator is the one to use here. If <code>x % y == 0</code> then <code>x</code> is divisible by <code>y</code>. (Assuming <code>0 &lt; y &lt;= x</code>)</p>\n\n<p>I'd personally implement this as a method returning an <code>IEnumerable&lt;int&gt;</code> using an iterator block.</p>\n" }, { "answer_id": 239901, "author": "Marcel Popescu", "author_id": 31793, "author_profile": "https://Stackoverflow.com/users/31793", "pm_score": -1, "selected": false, "text": "<p>Linq solution:</p>\n\n<pre><code>IEnumerable&lt;int&gt; GetFactors(int n)\n{\n Debug.Assert(n &gt;= 1);\n return from i in Enumerable.Range(1, n)\n where n % i == 0\n select i;\n}\n</code></pre>\n" }, { "answer_id": 239907, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 2, "selected": false, "text": "<p>As extension methods:</p>\n\n<pre><code> public static bool Divides(this int potentialFactor, int i)\n {\n return i % potentialFactor == 0;\n }\n\n public static IEnumerable&lt;int&gt; Factors(this int i)\n {\n return from potentialFactor in Enumerable.Range(1, i)\n where potentialFactor.Divides(i)\n select potentialFactor;\n }\n</code></pre>\n\n<p>Here's an example of usage:</p>\n\n<pre><code> foreach (int i in 4.Factors())\n {\n Console.WriteLine(i);\n }\n</code></pre>\n\n<p>Note that I have optimized for clarity, not for performance. For large values of <code>i</code> this algorithm can take a long time.</p>\n" }, { "answer_id": 239926, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 2, "selected": false, "text": "<p>Here it is again, only counting to the square root, as others mentioned. I suppose that people are attracted to that idea if you're hoping to improve performance. I'd rather write elegant code first, and optimize for performance later, after testing my software.</p>\n\n<p>Still, for reference, here it is:</p>\n\n<pre><code> public static bool Divides(this int potentialFactor, int i)\n {\n return i % potentialFactor == 0;\n }\n\n public static IEnumerable&lt;int&gt; Factors(this int i)\n {\n foreach (int result in from potentialFactor in Enumerable.Range(1, (int)Math.Sqrt(i))\n where potentialFactor.Divides(i)\n select potentialFactor)\n {\n yield return result;\n if (i / result != result)\n {\n yield return i / result;\n }\n }\n }\n</code></pre>\n\n<p>Not only is the result considerably less readable, but the factors come out of order this way, too.</p>\n" }, { "answer_id": 239973, "author": "mspmsp", "author_id": 21724, "author_profile": "https://Stackoverflow.com/users/21724", "pm_score": 1, "selected": false, "text": "<p>Wouldn't it also make sense to start at 2 and head towards an upper limit value that's continuously being recalculated based on the number you've just checked? See N/i (where N is the Number you're trying to find the factor of and i is the current number to check...) Ideally, instead of mod, you would use a divide function that returns N/i as well as any remainder it might have. That way you're performing one divide operation to recreate your upper bound as well as the remainder you'll check for even division.</p>\n\n<p>Math.DivRem\n<a href=\"http://msdn.microsoft.com/en-us/library/wwc1t3y1.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/wwc1t3y1.aspx</a></p>\n" }, { "answer_id": 240096, "author": "Pablo Retyk", "author_id": 30729, "author_profile": "https://Stackoverflow.com/users/30729", "pm_score": 2, "selected": false, "text": "<p>Another LINQ style and tying to keep the O(sqrt(n)) complexity</p>\n\n<pre><code> static IEnumerable&lt;int&gt; GetFactors(int n)\n {\n Debug.Assert(n &gt;= 1);\n var pairList = from i in Enumerable.Range(1, (int)(Math.Round(Math.Sqrt(n) + 1)))\n where n % i == 0\n select new { A = i, B = n / i };\n\n foreach(var pair in pairList)\n {\n yield return pair.A;\n yield return pair.B;\n }\n\n\n }\n</code></pre>\n" }, { "answer_id": 3433222, "author": "call me Steve", "author_id": 24334, "author_profile": "https://Stackoverflow.com/users/24334", "pm_score": 4, "selected": false, "text": "<p>Very late but the accepted answer (a while back) didn't not give the correct results.</p>\n<p>Thanks to Merlyn, I got now got the reason for the square as a 'max' below the corrected sample. althought the answer from Echostorm seems more complete.</p>\n<pre><code>public static IEnumerable&lt;uint&gt; GetFactors(uint x)\n{\n for (uint i = 1; i * i &lt;= x; i++)\n {\n if (x % i == 0)\n {\n yield return i;\n if (i != x / i)\n yield return x / i;\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 25285850, "author": "JEJoll", "author_id": 2558418, "author_profile": "https://Stackoverflow.com/users/2558418", "pm_score": 1, "selected": false, "text": "<p>If you use doubles, the following works: use a for loop iterating from 1 up to the number you want to factor. In each iteration, divide the number to be factored by i. If (number / i) % 1 == 0, then i is a factor, as is the quotient of number / i. Put one or both of these in a list, and you have all of the factors.</p>\n" }, { "answer_id": 36829780, "author": "Spencer", "author_id": 1133243, "author_profile": "https://Stackoverflow.com/users/1133243", "pm_score": 2, "selected": false, "text": "<p>I did it the lazy way. I don't know much, but I've been told that simplicity can sometimes imply elegance. This is one possible way to do it:</p>\n\n<pre><code> public static IEnumerable&lt;int&gt; GetDivisors(int number)\n {\n var searched = Enumerable.Range(1, number)\n .Where((x) =&gt; number % x == 0)\n .Select(x =&gt; number / x);\n\n foreach (var s in searched) \n yield return s;\n }\n</code></pre>\n\n<p><strong>EDIT</strong>: As Kraang Prime pointed out, this function cannot exceed the limit of an integer and is (admittedly) not the most efficient way to handle this problem.</p>\n" }, { "answer_id": 51896402, "author": "TaW", "author_id": 3152130, "author_profile": "https://Stackoverflow.com/users/3152130", "pm_score": 1, "selected": false, "text": "<p>And one more solution. Not sure if it has any advantages other than being readable..:</p>\n\n<pre><code>List&lt;int&gt; GetFactors(int n)\n{\n var f = new List&lt;int&gt;() { 1 }; // adding trivial factor, optional\n int m = n;\n int i = 2;\n while (m &gt; 1)\n {\n if (m % i == 0)\n {\n f.Add(i);\n m /= i;\n }\n else i++;\n }\n // f.Add(n); // adding trivial factor, optional\n return f;\n}\n</code></pre>\n" }, { "answer_id": 55038439, "author": "Muhammad Haroon Iqbal", "author_id": 5880348, "author_profile": "https://Stackoverflow.com/users/5880348", "pm_score": 0, "selected": false, "text": "<p>Program to get prime factors of whole numbers in javascript code.</p>\n\n<pre><code>function getFactors(num1){\n var factors = [];\n var divider = 2;\n while(num1 != 1){\n if(num1 % divider == 0){\n num1 = num1 / divider;\n factors.push(divider);\n }\n else{\n divider++;\n }\n }\n console.log(factors);\n return factors;\n}\n\ngetFactors(20);\n</code></pre>\n" }, { "answer_id": 69323785, "author": "Nima Ghomri", "author_id": 9882771, "author_profile": "https://Stackoverflow.com/users/9882771", "pm_score": 0, "selected": false, "text": "<p>In fact we don't have to check for factors not to be square root in each iteration from the accepted answer proposed by <a href=\"https://stackoverflow.com/a/239877/9882771\">chris</a> fixed by <a href=\"https://stackoverflow.com/users/22656/jon-skeet\">Jon</a>, which could slow down the method when the integer is large by adding an unnecessary Boolean check and a division. Just keep the <code>max</code> as double (don't cast it to an <code>int</code>) and change to loop to be exclusive not inclusive.</p>\n<pre><code> private static List&lt;int&gt; Factor(int number)\n {\n var factors = new List&lt;int&gt;();\n var max = Math.Sqrt(number); // (store in double not an int) - Round down\n if (max % 1 == 0)\n factors.Add((int)max);\n\n for (int factor = 1; factor &lt; max; ++factor) // (Exclusice) - Test from 1 to the square root, or the int below it, inclusive.\n {\n if (number % factor == 0)\n {\n factors.Add(factor);\n //if (factor != number / factor) // (Don't need check anymore) - Don't add the square root twice! Thanks Jon\n factors.Add(number / factor);\n }\n }\n return factors;\n }\n</code></pre>\n<p><strong>Usage</strong></p>\n<pre><code>Factor(16)\n// 4 1 16 2 8\nFactor(20)\n//1 20 2 10 4 5\n</code></pre>\n<p>And this is the extension version of the method for <code>int</code> type:</p>\n<pre><code>public static class IntExtensions\n{\n public static IEnumerable&lt;int&gt; Factors(this int value)\n {\n // Return 2 obvious factors\n yield return 1;\n yield return value;\n \n // Return square root if number is prefect square\n var max = Math.Sqrt(value);\n if (max % 1 == 0)\n yield return (int)max;\n\n // Return rest of the factors\n for (int i = 2; i &lt; max; i++)\n {\n if (value % i == 0)\n {\n yield return i;\n yield return value / i;\n }\n }\n }\n}\n</code></pre>\n<p><strong>Usage</strong></p>\n<pre><code>16.Factors()\n// 4 1 16 2 8\n20.Factors()\n//1 20 2 10 4 5\n</code></pre>\n" }, { "answer_id": 71245864, "author": "Richard Robertson", "author_id": 671496, "author_profile": "https://Stackoverflow.com/users/671496", "pm_score": 1, "selected": false, "text": "<p>I came here just looking for a solution to this problem for myself. After examining the previous replies I figured it would be fair to toss out an answer of my own even if I might be a bit late to the party.\nThe maximum number of factors of a number will be no more than one half of that number.There is no need to deal with floating point values or transcendent operations like a square root. Additionally finding one factor of a number automatically finds another. Just find one and you can return both by just dividing the original number by the found one.</p>\n<p>I doubt I'll need to use checks for my own implementation but I'm including them just for completeness (at least partially).</p>\n<pre><code>public static IEnumerable&lt;int&gt;Factors(int Num)\n{\n int ToFactor = Num;\n\n if(ToFactor == 0)\n { // Zero has only itself and one as factors but this can't be discovered through division\n // obviously. \n yield return 0;\n return 1;\n }\n \n if(ToFactor &lt; 0)\n {// Negative numbers are simply being treated here as just adding -1 to the list of possible \n // factors. In practice it can be argued that the factors of a number can be both positive \n // and negative, i.e. 4 factors into the following pairings of factors:\n // (-4, -1), (-2, -2), (1, 4), (2, 2) but normally when you factor numbers you are only \n // asking for the positive factors. By adding a -1 to the list it allows flagging the\n // series as originating with a negative value and the implementer can use that\n // information as needed.\n ToFactor = -ToFactor;\n \n yield return -1;\n }\n \n int FactorLimit = ToFactor / 2; // A good compiler may do this optimization already.\n // It's here just in case;\n \n for(int PossibleFactor = 1; PossibleFactor &lt;= FactorLimit; PossibleFactor++)\n {\n if(ToFactor % PossibleFactor == 0)\n {\n yield return PossibleFactor;\n yield return ToFactor / PossibleFactor;\n }\n }\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12862/" ]
All numbers that divide evenly into x. I put in 4 it returns: 4, 2, 1 edit: I know it sounds homeworky. I'm writing a little app to populate some product tables with semi random test data. Two of the properties are ItemMaximum and Item Multiplier. I need to make sure that the multiplier does not create an illogical situation where buying 1 more item would put the order over the maximum allowed. Thus the factors will give a list of valid values for my test data. edit++: This is what I went with after all the help from everyone. Thanks again! edit#: I wrote 3 different versions to see which I liked better and tested them against factoring small numbers and very large numbers. I'll paste the results. ``` static IEnumerable<int> GetFactors2(int n) { return from a in Enumerable.Range(1, n) where n % a == 0 select a; } private IEnumerable<int> GetFactors3(int x) { for (int factor = 1; factor * factor <= x; factor++) { if (x % factor == 0) { yield return factor; if (factor * factor != x) yield return x / factor; } } } private IEnumerable<int> GetFactors1(int x) { int max = (int)Math.Ceiling(Math.Sqrt(x)); for (int factor = 1; factor < max; factor++) { if(x % factor == 0) { yield return factor; if(factor != max) yield return x / factor; } } } ``` In ticks. When factoring the number 20, 5 times each: * GetFactors1-5,445,881 * GetFactors2-4,308,234 * GetFactors3-2,913,659 When factoring the number 20000, 5 times each: * GetFactors1-5,644,457 * GetFactors2-12,117,938 * GetFactors3-3,108,182
pseudocode: * Loop from 1 to the square root of the number, call the index "i". * if number mod i is 0, add i and number / i to the list of factors. realocode: ``` public List<int> Factor(int number) { var factors = new List<int>(); int max = (int)Math.Sqrt(number); // Round down for (int factor = 1; factor <= max; ++factor) // Test from 1 to the square root, or the int below it, inclusive. { if (number % factor == 0) { factors.Add(factor); if (factor != number/factor) // Don't add the square root twice! Thanks Jon factors.Add(number/factor); } } return factors; } ``` As Jon Skeet mentioned, you could implement this as an `IEnumerable<int>` as well - use [yield](http://msdn.microsoft.com/en-us/library/9k7k7cf0(VS.80).aspx) instead of adding to a list. The advantage with `List<int>` is that it could be sorted before return if required. Then again, you could get a sorted enumerator with a hybrid approach, yielding the first factor and storing the second one in each iteration of the loop, then yielding each value that was stored in reverse order. You will also want to do something to handle the case where a negative number passed into the function.
239,866
<p>I'm writing a license agreement dialog box with Win32 and I'm stumped. As usual with these things I want the "accept/don't accept" buttons to become enabled when the slider of the scroll bar of the richedit control hits bottom, but I can't find a way to get notified of that event. The earliest I've been able to learn about it is when the user releases the left mouse button.</p> <p>Is there a way to do this?</p> <p>Here's what I tried so far: </p> <ul> <li><code>WM_VSCROLL</code> and <code>WM_LBUTTONUP</code> in richedit's wndproc </li> <li><code>EN_MSGFILTER</code> notification in dlgproc (yes the filter mask is getting set)</li> <li><code>WM_VSCROLL</code> and <code>WM_LBUTTONUP</code> in dlgproc.</li> <li><code>EN_VSCROLL</code> notification in dlgproc</li> </ul> <p>I got so desperate I tried polling but that didn't work either because apparently timer messages stop arriving while the mouse button is down on the slider. I tried both:</p> <ul> <li>timer callback (to poll) in dlgproc</li> <li>timer callback (to poll) in richedit's wndproc</li> </ul>
[ { "answer_id": 239928, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 1, "selected": false, "text": "<p>You need to sub-class the edit box and intercept the messages to the edit box itself. <a href=\"http://msdn.microsoft.com/en-us/library/ms997565.aspx\" rel=\"nofollow noreferrer\">Here's an artical on MSDN about subclassing controls</a>.</p>\n\n<p>EDIT: Some code to demonstrate the scroll bar enabling a button: </p>\n\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;richedit.h&gt;\n\nLRESULT __stdcall RichEditSubclass\n(\n HWND window,\n UINT message,\n WPARAM w_param,\n LPARAM l_param\n)\n{\n HWND\n parent = reinterpret_cast &lt;HWND&gt; (GetWindowLong (window, GWL_HWNDPARENT));\n\n WNDPROC\n proc = reinterpret_cast &lt;WNDPROC&gt; (GetWindowLong (parent, GWL_USERDATA));\n\n switch (message)\n {\n case WM_VSCROLL:\n {\n SCROLLINFO\n scroll_info = \n {\n sizeof scroll_info,\n SIF_ALL\n };\n\n GetScrollInfo (window, SB_VERT, &amp;scroll_info);\n\n if (scroll_info.nPos + static_cast &lt;int&gt; (scroll_info.nPage) &gt;= scroll_info.nMax ||\n scroll_info.nTrackPos + static_cast &lt;int&gt; (scroll_info.nPage) &gt;= scroll_info.nMax)\n {\n HWND\n button = reinterpret_cast &lt;HWND&gt; (GetWindowLong (parent, 0));\n\n EnableWindow (button, TRUE);\n }\n }\n break;\n }\n\n return CallWindowProc (proc, window, message, w_param, l_param);\n}\n\nLRESULT __stdcall ApplicationWindowProc\n(\n HWND window,\n UINT message,\n WPARAM w_param,\n LPARAM l_param\n)\n{\n bool\n use_default_proc = false;\n\n LRESULT\n result = 0;\n\n switch (message)\n {\n case WM_CREATE:\n {\n CREATESTRUCT\n *creation_data = reinterpret_cast &lt;CREATESTRUCT *&gt; (l_param);\n\n RECT\n client;\n\n GetClientRect (window, &amp;client);\n\n HWND\n child = CreateWindow (RICHEDIT_CLASS,\n TEXT (\"The\\nQuick\\nBrown\\nFox\\nJumped\\nOver\\nThe\\nLazy\\nDog\\nThe\\nQuick\\nBrown\\nFox\\nJumped\\nOver\\nThe\\nLazy\\nDog\"),\n WS_CHILD | WS_VISIBLE | ES_MULTILINE | ES_AUTOVSCROLL | WS_VSCROLL | ES_DISABLENOSCROLL,\n 0, 0, client.right, client.bottom - 30,\n window,\n 0,\n creation_data-&gt;hInstance,\n 0);\n\n SetWindowLong (window, GWL_USERDATA, GetWindowLong (child, GWL_WNDPROC));\n SetWindowLong (child, GWL_WNDPROC, reinterpret_cast &lt;LONG&gt; (RichEditSubclass));\n SetWindowLong (child, GWL_ID, 0);\n\n child = CreateWindow (TEXT (\"BUTTON\"), TEXT (\"Go Ahead!\"), WS_CHILD | WS_VISIBLE | WS_DISABLED, 0, client.bottom - 30, client.right, 30, window, 0, creation_data-&gt;hInstance, 0);\n\n SetWindowLong (window, 0, reinterpret_cast &lt;LONG&gt; (child));\n SetWindowLong (child, GWL_ID, 1);\n }\n break;\n\n case WM_COMMAND:\n if (HIWORD (w_param) == BN_CLICKED &amp;&amp; LOWORD (w_param) == 1)\n {\n DestroyWindow (window);\n }\n break;\n\n default:\n use_default_proc = true;\n break;\n }\n\n return use_default_proc ? DefWindowProc (window, message, w_param, l_param) : result;\n}\n\nint __stdcall WinMain\n(\n HINSTANCE instance,\n HINSTANCE unused,\n LPSTR command_line,\n int show\n)\n{\n LoadLibrary (TEXT (\"riched20.dll\"));\n\n WNDCLASS\n window_class = \n {\n 0,\n ApplicationWindowProc,\n 0,\n 4,\n instance,\n 0,\n LoadCursor (0, IDC_ARROW),\n reinterpret_cast &lt;HBRUSH&gt; (COLOR_BACKGROUND + 1),\n 0,\n TEXT (\"ApplicationWindowClass\")\n };\n\n RegisterClass (&amp;window_class);\n\n HWND\n window = CreateWindow (TEXT (\"ApplicationWindowClass\"),\n TEXT (\"Application\"),\n WS_VISIBLE | WS_OVERLAPPED | WS_SYSMENU,\n CW_USEDEFAULT,\n CW_USEDEFAULT,\n 400, 300, 0, 0,\n instance,\n 0);\n\n MSG\n message;\n\n int\n success;\n\n while (success = GetMessage (&amp;message, window, 0, 0))\n { \n if (success == -1)\n {\n break;\n }\n else\n {\n TranslateMessage (&amp;message);\n DispatchMessage (&amp;message);\n }\n }\n\n return 0;\n}\n</code></pre>\n\n<p>The above doesn't handle the user moving the cursor in the edit box.</p>\n" }, { "answer_id": 239933, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": -1, "selected": false, "text": "<p>Even though it is possible, I don't think you should do it that way - the user will have no clue why the buttons are disabled. This can be very confusing, and confusing the user should be avoided at all costs ;-)</p>\n\n<p>That's why most license dialogs have radio buttons for accept/decline with decline enabled by default, so you actively have to enable accept. </p>\n" }, { "answer_id": 241674, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 0, "selected": false, "text": "<p>I would recommend starting up <strong>Spy++</strong> and seeing which windows messages are getting sent to where.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa264396(VS.60).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa264396(VS.60).aspx</a></p>\n" }, { "answer_id": 242060, "author": "David L Morris", "author_id": 3137, "author_profile": "https://Stackoverflow.com/users/3137", "pm_score": 0, "selected": false, "text": "<p>Why not use the EM_GETTHUMB message. (Assuming Rich Edit 2.0 or later).</p>\n\n<p>If you are lucky this bottom position will match EM_GETLINECOUNT.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31790/" ]
I'm writing a license agreement dialog box with Win32 and I'm stumped. As usual with these things I want the "accept/don't accept" buttons to become enabled when the slider of the scroll bar of the richedit control hits bottom, but I can't find a way to get notified of that event. The earliest I've been able to learn about it is when the user releases the left mouse button. Is there a way to do this? Here's what I tried so far: * `WM_VSCROLL` and `WM_LBUTTONUP` in richedit's wndproc * `EN_MSGFILTER` notification in dlgproc (yes the filter mask is getting set) * `WM_VSCROLL` and `WM_LBUTTONUP` in dlgproc. * `EN_VSCROLL` notification in dlgproc I got so desperate I tried polling but that didn't work either because apparently timer messages stop arriving while the mouse button is down on the slider. I tried both: * timer callback (to poll) in dlgproc * timer callback (to poll) in richedit's wndproc
You need to sub-class the edit box and intercept the messages to the edit box itself. [Here's an artical on MSDN about subclassing controls](http://msdn.microsoft.com/en-us/library/ms997565.aspx). EDIT: Some code to demonstrate the scroll bar enabling a button: ``` #include <windows.h> #include <richedit.h> LRESULT __stdcall RichEditSubclass ( HWND window, UINT message, WPARAM w_param, LPARAM l_param ) { HWND parent = reinterpret_cast <HWND> (GetWindowLong (window, GWL_HWNDPARENT)); WNDPROC proc = reinterpret_cast <WNDPROC> (GetWindowLong (parent, GWL_USERDATA)); switch (message) { case WM_VSCROLL: { SCROLLINFO scroll_info = { sizeof scroll_info, SIF_ALL }; GetScrollInfo (window, SB_VERT, &scroll_info); if (scroll_info.nPos + static_cast <int> (scroll_info.nPage) >= scroll_info.nMax || scroll_info.nTrackPos + static_cast <int> (scroll_info.nPage) >= scroll_info.nMax) { HWND button = reinterpret_cast <HWND> (GetWindowLong (parent, 0)); EnableWindow (button, TRUE); } } break; } return CallWindowProc (proc, window, message, w_param, l_param); } LRESULT __stdcall ApplicationWindowProc ( HWND window, UINT message, WPARAM w_param, LPARAM l_param ) { bool use_default_proc = false; LRESULT result = 0; switch (message) { case WM_CREATE: { CREATESTRUCT *creation_data = reinterpret_cast <CREATESTRUCT *> (l_param); RECT client; GetClientRect (window, &client); HWND child = CreateWindow (RICHEDIT_CLASS, TEXT ("The\nQuick\nBrown\nFox\nJumped\nOver\nThe\nLazy\nDog\nThe\nQuick\nBrown\nFox\nJumped\nOver\nThe\nLazy\nDog"), WS_CHILD | WS_VISIBLE | ES_MULTILINE | ES_AUTOVSCROLL | WS_VSCROLL | ES_DISABLENOSCROLL, 0, 0, client.right, client.bottom - 30, window, 0, creation_data->hInstance, 0); SetWindowLong (window, GWL_USERDATA, GetWindowLong (child, GWL_WNDPROC)); SetWindowLong (child, GWL_WNDPROC, reinterpret_cast <LONG> (RichEditSubclass)); SetWindowLong (child, GWL_ID, 0); child = CreateWindow (TEXT ("BUTTON"), TEXT ("Go Ahead!"), WS_CHILD | WS_VISIBLE | WS_DISABLED, 0, client.bottom - 30, client.right, 30, window, 0, creation_data->hInstance, 0); SetWindowLong (window, 0, reinterpret_cast <LONG> (child)); SetWindowLong (child, GWL_ID, 1); } break; case WM_COMMAND: if (HIWORD (w_param) == BN_CLICKED && LOWORD (w_param) == 1) { DestroyWindow (window); } break; default: use_default_proc = true; break; } return use_default_proc ? DefWindowProc (window, message, w_param, l_param) : result; } int __stdcall WinMain ( HINSTANCE instance, HINSTANCE unused, LPSTR command_line, int show ) { LoadLibrary (TEXT ("riched20.dll")); WNDCLASS window_class = { 0, ApplicationWindowProc, 0, 4, instance, 0, LoadCursor (0, IDC_ARROW), reinterpret_cast <HBRUSH> (COLOR_BACKGROUND + 1), 0, TEXT ("ApplicationWindowClass") }; RegisterClass (&window_class); HWND window = CreateWindow (TEXT ("ApplicationWindowClass"), TEXT ("Application"), WS_VISIBLE | WS_OVERLAPPED | WS_SYSMENU, CW_USEDEFAULT, CW_USEDEFAULT, 400, 300, 0, 0, instance, 0); MSG message; int success; while (success = GetMessage (&message, window, 0, 0)) { if (success == -1) { break; } else { TranslateMessage (&message); DispatchMessage (&message); } } return 0; } ``` The above doesn't handle the user moving the cursor in the edit box.
239,872
<p>VS2008 Code Analysis will flag a spelling mistake in an identifier using the <code>IdentifiersShouldBeSpelledCorrectly</code> warning type.</p> <p>This process is using an American dictionary by default because words are being flagged that are correctly spelt using the British spelling. For example, words like "Organisation" and "Customisation", etc...</p> <p>I am aware that you can create your own custom Xml dictionary files that contain any words you don't want to be flagged, however, can anyone tell me if you can configure Code Analysis to use a different default (or additional) dictionary from those available in Windows?</p>
[ { "answer_id": 239908, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 2, "selected": false, "text": "<p>This should do it for you <a href=\"http://blogs.msdn.com/fxcop/archive/2007/08/12/new-for-visual-studio-2008-spelling-rules.aspx\" rel=\"nofollow noreferrer\">Visual Studio 2008 - Spelling rules</a></p>\n\n<p>So simply replace en-AU with en-GB in the example given.</p>\n\n<p>It quotes the rule IdentifiersShouldBeSpelledCorrectly.</p>\n" }, { "answer_id": 240440, "author": "Andy McCluggage", "author_id": 3362, "author_profile": "https://Stackoverflow.com/users/3362", "pm_score": 4, "selected": true, "text": "<p>Excellent, thanks.</p>\n\n<p>A summary of the solution is...</p>\n\n<p>Add the <code> CodeAnalysisCulture</code> line to the Project file. Unfortunately I think this has to be done for every project being analysed...</p>\n\n<pre><code>&lt;PropertyGroup Condition=\" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' \"&gt;\n ...\n &lt;RunCodeAnalysis&gt;true&lt;/RunCodeAnalysis&gt;\n &lt;CodeAnalysisCulture&gt;en-GB&lt;/CodeAnalysisCulture&gt;\n ...\n</code></pre>\n\n<p>with \"en-GB\" as the value to get British English spellchecking.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3362/" ]
VS2008 Code Analysis will flag a spelling mistake in an identifier using the `IdentifiersShouldBeSpelledCorrectly` warning type. This process is using an American dictionary by default because words are being flagged that are correctly spelt using the British spelling. For example, words like "Organisation" and "Customisation", etc... I am aware that you can create your own custom Xml dictionary files that contain any words you don't want to be flagged, however, can anyone tell me if you can configure Code Analysis to use a different default (or additional) dictionary from those available in Windows?
Excellent, thanks. A summary of the solution is... Add the `CodeAnalysisCulture` line to the Project file. Unfortunately I think this has to be done for every project being analysed... ``` <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> ... <RunCodeAnalysis>true</RunCodeAnalysis> <CodeAnalysisCulture>en-GB</CodeAnalysisCulture> ... ``` with "en-GB" as the value to get British English spellchecking.
239,876
<p>What is the best way of storing data out to a file on a network, which will be later read in again programmatically. Target platform for the program is Linux (Fedora), but it will need to write out a file to a Windows (XP) machine</p> <p>This needs to be in C++, there will be a high number of write / read events so it needs to be efficient, and the data needs to be written out in such a way that it can be read back in easily.</p> <p>The whole file may not be being read back in, I'll need to search for a specific block of data in the file and read that back in.</p> <p>Will simple binary stream writer do? How should I store the data - XML?</p> <p>Anything else I need to worry about?</p> <hr> <p><strong>UPDATE :</strong> To clarify, here are some answers to <strong><em>peterchen's</em></strong> points</p> <blockquote> <p>Please clarify:</p> <p><strong>* do you only append blocks, or do you also need to remove / update them?</strong></p> </blockquote> <p>I only need to append to the end of the file, but will need to search through it and retrieve from any point in it</p> <blockquote> <pre><code>*** are all blocks of the same size?** </code></pre> </blockquote> <p>No, the data will vary in size - some will be free text comments (like a post here) others will be specific object-like data (sets of parameters)</p> <blockquote> <pre><code>*** is it necessary to be a single file?** </code></pre> </blockquote> <p>No, but desirable</p> <blockquote> <pre><code>*** by which criteria do you need to locate blocks?** </code></pre> </blockquote> <p>By data type and by timestamp. For example, if I periodically write out a specific set of parameters, in amognst other data, like free text, I want to find the value of those parameters at a cerain date/time - so I'll need to search for the time I wrote out those parameters nearest that date and read them back in.</p> <blockquote> <pre><code>*** must the data be readable for other applications?** </code></pre> </blockquote> <p>No.</p> <blockquote> <pre><code>*** do you need concurrent access?** </code></pre> </blockquote> <p>Yes, I may be continuing to write as I read. but should only ever do one write at a time.</p> <blockquote> <pre><code>*** Amount of data (per block / total) - kilo, mega, giga, tera?** </code></pre> </blockquote> <p>Amount of data will be low per write... from a number of bytes to a coupe hundred bytes - total should see no more than few hundred kilobytes possible a fwe megabytes. (still unsure as yet)</p> <p>**> If you need all of this, rolling your own will be a challenge, I would definitely </p> <blockquote> <p>recommend to use a database. If you need less than that, please specify so we can recommend.**</p> </blockquote> <p>A database would over complicate the system so that is not an option unfortunately.</p>
[ { "answer_id": 239906, "author": "Yuval F", "author_id": 1702, "author_profile": "https://Stackoverflow.com/users/1702", "pm_score": 3, "selected": false, "text": "<p>Your question is too general. I would first define my needs, then a record structure for the file, and then use a textual representation to save it. Take a look at <a href=\"http://www.faqs.org/docs/artu/ch05s02.html\" rel=\"nofollow noreferrer\">Eric Stone Raymond's data metaformat</a>, at <a href=\"http://www.json.org/\" rel=\"nofollow noreferrer\">JSON</a>, and maybe <a href=\"http://en.wikipedia.org/wiki/Comma-separated_values\" rel=\"nofollow noreferrer\">CSV</a> or <a href=\"http://xml.silmaril.ie/\" rel=\"nofollow noreferrer\">XML</a>. All of peterchen's points seem relevant.</p>\n" }, { "answer_id": 239913, "author": "Timo Geusch", "author_id": 29068, "author_profile": "https://Stackoverflow.com/users/29068", "pm_score": 1, "selected": false, "text": "<p>You'll need to look at the kind of data you are writing out. Once you are dealing with objects instead of PODs, simply writing out the binary representation of the object will not necessarily result in anything that you can deserialise successfully.</p>\n\n<p>If you are \"only\" writing out text, reading the data back in should be comparatively easy if you are writing out in the same text representation. If you are trying to write out more complex data types you'll probably need to look at something like boost::serialization.</p>\n" }, { "answer_id": 239936, "author": "artificialidiot", "author_id": 7988, "author_profile": "https://Stackoverflow.com/users/7988", "pm_score": 1, "selected": false, "text": "<p>Your application sounds like it needs a database. If you can afford, use one. But don't use an embedded database engine like sqlite for a file over a network storage, since it may be too unstable for your purposes. If you still want to use something like it, you have to use it through your own reader/writer process with your own access protocol, stability concerns still applies if you use a text based file format like XML instead, so you will have to do same for them.</p>\n\n<p>I can't be certain without knowing your workload though.</p>\n" }, { "answer_id": 240069, "author": "T.E.D.", "author_id": 29639, "author_profile": "https://Stackoverflow.com/users/29639", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>there will be a high number of write / read events so it needs to be efficient,</p>\n</blockquote>\n\n<p>That will not be efficient.</p>\n\n<p>I did a lot of timing on this back in the Win2K days, when I had to implement a program that essentially had a file copy in it. What I found was that by far the biggest bottleneck in my program seemed to be the overhead in each I/O operation. The single most effective thing I found in reducing total runtime was to reduce the number of I/O operations I requested.</p>\n\n<p>I started doing pretty stream I/O, but that was no good because the stupid compiler was issuing an I/O for every single character. Its performace compared to the shell \"copy\" command was just pitiful. Then I tried writing out an entire line at a time, but that was only marginally better. </p>\n\n<p>Eventually I ended up writing the program to attempt to read the entire file into memory so that in most cases there would be only 2 I/Os: one to read it in and another to write it out. This is where I saw the huge savings. The extra code involved in dealing with the manual buffering was more than made up for in less time waiting for I/Os to complete.</p>\n\n<p>Of course this was 7 years or so ago, so I suppose things may be much different now. Time it yourself if you want to be sure.</p>\n" }, { "answer_id": 240144, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 0, "selected": false, "text": "<p>Store it as binary if you're not doing text storage. Text is hideously inefficient; XML is even worse. The lack of efficiency of the storage format predicates larger file transfers which means more time. If you are having to store text, filter it through a zip library.</p>\n\n<p>Your main issue is going to be file locking and concurrency. Everything starts to get groady when you have to write/read/write in a concurrent fashion. At this point, get a DB of some sort installed and BLOB the file up or something, because you'll be writing your own DB at this point....and <em>no one</em> wants to reinvent that wheel(you know, if they aren't doing their own DB company of their own, or are a PhD student, or have a strange hobby...)</p>\n" }, { "answer_id": 240351, "author": "KeithB", "author_id": 2298, "author_profile": "https://Stackoverflow.com/users/2298", "pm_score": 1, "selected": false, "text": "<p>If you are only talking about a few megabytes, I wouldn't store in on disk at all. Have a process on the network that accepts data and stores it internally, and also accepts queries on that data. If you need a record of the data, this process can also write it to the disk. Note that this sounds a lot like a database, and this indeed may be the best way to do it. I don't see how this complicates the system. In fact, it makes it much easier. Just write a class that abstracts the database, and have the rest of the code use that.</p>\n\n<p>I went through this same process myself in the past, including dismissing a database as too complicated. It started off fairly simple, but after a couple of years we had written our own, poorly implemented, buggy, hard to use database. At that point, we junked our code and moved to postgres. We've never regretted the change.</p>\n" }, { "answer_id": 240406, "author": "João Augusto", "author_id": 6909, "author_profile": "https://Stackoverflow.com/users/6909", "pm_score": 2, "selected": false, "text": "<p>Probably you should have another file that would be read into a vector with fixed size data.</p>\n\n<pre><code>struct structBlockInfo\n {\n int iTimeStamp; // TimeStamp \n char cBlockType; // Type of Data (PArameters or Simple Text)\n long vOffset; // Position on the real File\n };\n</code></pre>\n\n<p>Every time you added a new block you would also add it to this vector the correspondent information and save it.</p>\n\n<p>Now if you wanted to to read a specific block you could do a search on this vector, position yourself on the \"Real File\" with fseek (or whatever) to the correspondent offset, and read X bytes (this offset to the start of the other or to the end of the file)\nAnd do a cast to something depending on the cBlockType, examples:</p>\n\n<pre><code> struct structBlockText\n { \n char cComment[];\n };\n\n struct structBlockValuesExample1\n { \n int iValue1;\n int iValue2;\n };\n\n struct structBlockValuesExample2\n { \n int iValue1;\n int iValue2;\n long lValue1;\n char cLittleText[];\n };\n</code></pre>\n\n<p>Read some Bytes....</p>\n\n<pre><code>fread(cBuffer, 1, iTotalBytes, p_File);\n</code></pre>\n\n<p>If it was a BLockText...</p>\n\n<pre><code>structBlockText* p_stBlock = (structBlockText*) cBuffer;\n</code></pre>\n\n<p>If it was a structBlockValuesExample1...</p>\n\n<pre><code>structBlockValuesExample1* p_stBlock = (structBlockValuesExample1*) cBuffer;\n</code></pre>\n\n<p>Note: that cBuffer can hold more than one Block.</p>\n" }, { "answer_id": 240513, "author": "graham.reeds", "author_id": 342, "author_profile": "https://Stackoverflow.com/users/342", "pm_score": 1, "selected": false, "text": "<p>This is what I have for reading/writing of data:</p>\n\n<pre><code>template&lt;class T&gt;\n int write_pod( std::ofstream&amp; out, T&amp; t )\n{\n out.write( reinterpret_cast&lt;const char*&gt;( &amp;t ), sizeof( T ) );\n return sizeof( T );\n}\n\ntemplate&lt;class T&gt;\n void read_pod( std::ifstream&amp; in, T&amp; t )\n{\n in.read( reinterpret_cast&lt;char*&gt;( &amp;t ), sizeof( T ) );\n}\n</code></pre>\n\n<p>This doesn't work for vectors, deque's etc. but it is easy to do by simply writing out the number of items followed by the data:</p>\n\n<pre><code>struct object {\n std::vector&lt;small_objects&gt; values;\n\n template &lt;class archive&gt;\n void deserialize( archive&amp; ar ) {\n size_t size;\n read_pod( ar, size );\n values.resize( size );\n for ( int i=0; i&lt;size; ++i ) {\n values[i].deserialize( ar );\n }\n }\n}\n</code></pre>\n\n<p>Of course you will need to implement the serialize &amp; deserialize functions but they are easy to implement...</p>\n" }, { "answer_id": 241197, "author": "mempko", "author_id": 8863, "author_profile": "https://Stackoverflow.com/users/8863", "pm_score": 1, "selected": false, "text": "<p>I would check out the <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/serialization/doc/index.html\" rel=\"nofollow noreferrer\">Boost Serialization library</a> </p>\n\n<p>One of their examples is:</p>\n\n<pre><code>#include &lt;fstream&gt;\n\n// include headers that implement a archive in simple text format\n#include &lt;boost/archive/text_oarchive.hpp&gt;\n#include &lt;boost/archive/text_iarchive.hpp&gt;\n\n/////////////////////////////////////////////////////////////\n// gps coordinate\n//\n// illustrates serialization for a simple type\n//\nclass gps_position\n{\nprivate:\n friend class boost::serialization::access;\n // When the class Archive corresponds to an output archive, the\n // &amp; operator is defined similar to &lt;&lt;. Likewise, when the class Archive\n // is a type of input archive the &amp; operator is defined similar to &gt;&gt;.\n template&lt;class Archive&gt;\n void serialize(Archive &amp; ar, const unsigned int version)\n {\n ar &amp; degrees;\n ar &amp; minutes;\n ar &amp; seconds;\n }\n int degrees;\n int minutes;\n float seconds;\npublic:\n gps_position(){};\n gps_position(int d, int m, float s) :\n degrees(d), minutes(m), seconds(s)\n {}\n};\n\nint main() {\n // create and open a character archive for output\n std::ofstream ofs(\"filename\");\n\n // create class instance\n const gps_position g(35, 59, 24.567f);\n\n // save data to archive\n {\n boost::archive::text_oarchive oa(ofs);\n // write class instance to archive\n oa &lt;&lt; g;\n // archive and stream closed when destructors are called\n }\n\n // ... some time later restore the class instance to its orginal state\n gps_position newg;\n {\n // create and open an archive for input\n std::ifstream ifs(\"filename\");\n boost::archive::text_iarchive ia(ifs);\n // read class state from archive\n ia &gt;&gt; newg;\n // archive and stream closed when destructors are called\n }\n return 0;\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15533/" ]
What is the best way of storing data out to a file on a network, which will be later read in again programmatically. Target platform for the program is Linux (Fedora), but it will need to write out a file to a Windows (XP) machine This needs to be in C++, there will be a high number of write / read events so it needs to be efficient, and the data needs to be written out in such a way that it can be read back in easily. The whole file may not be being read back in, I'll need to search for a specific block of data in the file and read that back in. Will simple binary stream writer do? How should I store the data - XML? Anything else I need to worry about? --- **UPDATE :** To clarify, here are some answers to ***peterchen's*** points > > Please clarify: > > > **\* do you only append blocks, or do you > also need to remove / update them?** > > > I only need to append to the end of the file, but will need to search through it and retrieve from any point in it > > > ``` > *** are all blocks of the same size?** > > ``` > > No, the data will vary in size - some will be free text comments (like a post here) others will be specific object-like data (sets of parameters) > > > ``` > *** is it necessary to be a single file?** > > ``` > > No, but desirable > > > ``` > *** by which criteria do you need to locate blocks?** > > ``` > > By data type and by timestamp. For example, if I periodically write out a specific set of parameters, in amognst other data, like free text, I want to find the value of those parameters at a cerain date/time - so I'll need to search for the time I wrote out those parameters nearest that date and read them back in. > > > ``` > *** must the data be readable for other applications?** > > ``` > > No. > > > ``` > *** do you need concurrent access?** > > ``` > > Yes, I may be continuing to write as I read. but should only ever do one write at a time. > > > ``` > *** Amount of data (per block / total) - kilo, mega, giga, tera?** > > ``` > > Amount of data will be low per write... from a number of bytes to a coupe hundred bytes - total should see no more than few hundred kilobytes possible a fwe megabytes. (still unsure as yet) \*\*> If you need all of this, rolling your own will be a challenge, I would definitely > > recommend to use a database. If you need less than that, please specify so we can > recommend.\*\* > > > A database would over complicate the system so that is not an option unfortunately.
Your question is too general. I would first define my needs, then a record structure for the file, and then use a textual representation to save it. Take a look at [Eric Stone Raymond's data metaformat](http://www.faqs.org/docs/artu/ch05s02.html), at [JSON](http://www.json.org/), and maybe [CSV](http://en.wikipedia.org/wiki/Comma-separated_values) or [XML](http://xml.silmaril.ie/). All of peterchen's points seem relevant.
239,905
<p>Lets say on MySQL database (if it matters).</p>
[ { "answer_id": 239916, "author": "Ilya Komakhin", "author_id": 21603, "author_profile": "https://Stackoverflow.com/users/21603", "pm_score": 2, "selected": false, "text": "<p>No, as you could still use D-SQL in your stored procedures... and validating and restricting your input is a good idea in any case. </p>\n" }, { "answer_id": 239919, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>It depends what your stored procs do. If they dynamically generate SQL based on their parameters, and then execute that SQL, then you're still vulnerable. Otherwise, you're far more likely to be fine - but I hesitate to sound 100% confident!</p>\n" }, { "answer_id": 239920, "author": "Allain Lalonde", "author_id": 2443, "author_profile": "https://Stackoverflow.com/users/2443", "pm_score": 3, "selected": false, "text": "<p>nope. If you're constructing SQL that invokes a stored procedure you're still a target.</p>\n\n<p>You should be creating parametized queries on the client side.</p>\n" }, { "answer_id": 239923, "author": "Michael Madsen", "author_id": 27528, "author_profile": "https://Stackoverflow.com/users/27528", "pm_score": 4, "selected": false, "text": "<p>You are only immune to SQL injections if you consistenly use parameterized queries. You are <em>nearly</em> immune to SQL injections if you use proper escaping everywhere (but there can be, and has been, bugs in the escaping routines, so it's not as foolproof as parameters).</p>\n\n<p>If you call a stored procedure, adding the arguments by concatenation, I can still add a random query at the end of one of the input fields - for example, if you have CALL CheckLogin @username='$username', @password='$password', with the $-things representing directly concatenated variables, nothing stops me from changing the $password variable to read \"'; DROP DATABASE; --\".</p>\n\n<p>Obviously, if you clean up the input beforehand, this also contributes to preventing SQL injection, but this can potentially filter out data that shouldn't have been cleaned.</p>\n" }, { "answer_id": 239960, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 5, "selected": true, "text": "<p>No, you will not be completely safe. As others have mentioned, parameterized queries are always the way to go -- no matter how you're accessing the database.</p>\n\n<p>It's a bit of an urban legend that with procs you're safe. I think the reason people are under this delusion is because most people assume that you'll call the procs with parameterized queries from your code. But if you don't, if for example you do something like the below, you're wide open:</p>\n\n<pre><code>SqlCommand cmd = new SqlCommand(\"exec @myProc \" + paramValue, con);\ncmd.ExecuteNonQuery();\n</code></pre>\n\n<p>Because you're using unfiltered content from the end user. Once again, all they have to do is terminate the line (\";\"), add their dangerous commands, and boom -- you're hosed. </p>\n\n<p>(As an aside, if you're on the web, don't take unfiltered junk from the query string of the browser -- that makes it absurdly easy to do extremely bad things to your data.)</p>\n\n<p>If you parameterize the queries, you're in much better shape. However, as others here have mentioned, if your proc is still generating dynamic SQL and executing that, there may still be issues.</p>\n\n<p>I should note that I'm not anti-proc. Procs can be very helpful for solving certain problems with data access. But procs are <strong>not</strong> a \"silver-bullet solution to SQL injections.</p>\n" }, { "answer_id": 239992, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "<p>Stored Procedures are not a guarantee, because what is actually vulnerable is any dynamic code, and that includes code inside stored procedures and dynamically generated calls to stored procedures.</p>\n\n<p>Parameterized queries and stored procs called with parameters are both invulnerable to injection as long as they don't use arbitrary inputs to generate code. Note that there is plenty of dynamic code which is also not vulnerable to injection (for instance integer parameters in dynamic code).</p>\n\n<p>The benefits of a largely (I'm not sure 100% is really possible) stored procs-based architecture, however, is that injection can even be somewhat defended against (but not perfectly) for dynamic code at the client side because:</p>\n\n<p>Only EXEC permissions are granted to any user context the app is connecting under, so any SELECT, INSERT, UPDATE, DELETE queries will simply fail. Of course, DROP etc should not be allowed anyway. So any injection would have to be in the form of EXEC, so ultimately, only operations which you have defined in your SP layer will even be available (not arbitrary SQL) to inject against.</p>\n\n<p>Amongst the many other benefits of defining your database services as a set of stored procedures (like any abstraction layer in software) are the ability to refactor your database underneath without affecting apps, the ability to better understand and monitor the usage patterns in your database with a profiler, and the ability to selectively optimize within the database without having to deploy new clients.</p>\n" }, { "answer_id": 241177, "author": "Omniwombat", "author_id": 31351, "author_profile": "https://Stackoverflow.com/users/31351", "pm_score": 2, "selected": false, "text": "<p>Additionally, consider using fine grained database access, (also called generally Role Based Access Control) The main user of your database should have exactly the permissions needed to do its job and nothing else. Don't need to create new tables after install? REVOKE that permission. Don't have a legitimate need to run as sysdba? Then don't! A sneaky injection instructing the user to \"DROP DATABASE\" will be stymied if the user has not been GRANTed that permission. Then all you need to worry about is data-leaking SELECT statements.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28098/" ]
Lets say on MySQL database (if it matters).
No, you will not be completely safe. As others have mentioned, parameterized queries are always the way to go -- no matter how you're accessing the database. It's a bit of an urban legend that with procs you're safe. I think the reason people are under this delusion is because most people assume that you'll call the procs with parameterized queries from your code. But if you don't, if for example you do something like the below, you're wide open: ``` SqlCommand cmd = new SqlCommand("exec @myProc " + paramValue, con); cmd.ExecuteNonQuery(); ``` Because you're using unfiltered content from the end user. Once again, all they have to do is terminate the line (";"), add their dangerous commands, and boom -- you're hosed. (As an aside, if you're on the web, don't take unfiltered junk from the query string of the browser -- that makes it absurdly easy to do extremely bad things to your data.) If you parameterize the queries, you're in much better shape. However, as others here have mentioned, if your proc is still generating dynamic SQL and executing that, there may still be issues. I should note that I'm not anti-proc. Procs can be very helpful for solving certain problems with data access. But procs are **not** a "silver-bullet solution to SQL injections.
239,909
<p>I have a property called "IsSecureConnection" that is part of my object's interface. This makes sense for most implementations of the interface, however, in some implementations I would like to make the property ReadOnly. </p> <p>Should I omit this property from the object's interface even though it is required by all of the implementations (though slightly different on occasion)?</p> <p>Thanks!</p>
[ { "answer_id": 239911, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Just add the getter in the interface.</p>\n\n<pre><code>public interface Foo{\n bool MyMinimallyReadOnlyPropertyThatCanAlsoBeReadWrite {get;}\n}\n</code></pre>\n\n<p>Interfaces specify the minimum an object must implement; it doesn't say what an object cannot do. For that, you need to look into creating base classes.</p>\n" }, { "answer_id": 239918, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<p>Interfaces are like salt : sprinkle them everywhere:</p>\n\n<pre><code>public interface ICanBeSecure\n{\n bool IsSecureConnection { get; }\n}\n\npublic interface IIsSecureable : ICanBeSecure\n{\n bool IsSecureConnection { get; set;}\n}\n</code></pre>\n" }, { "answer_id": 239922, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 2, "selected": false, "text": "<p>You need to evaluate the case. If it doesn't make sense to have it always be writeable, separate it into a second interface.</p>\n\n<pre><code>public interface IFoo {\n bool SecuredConnection{ get; }\n}\n\npublic interface ISecurableOptionFoo: IFoo {\n bool SecuredConnection{ get; set; }\n}\n</code></pre>\n" }, { "answer_id": 240029, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": true, "text": "<p>It really depends on what's most readable for your clients. I can think of a couple of options:</p>\n\n<p>1) The inherited interface, though I'm not a fan of hiding, and I think it makes it a bit ugly for any VB.NET or explicit clients to implement:</p>\n\n<pre><code>interface IObject {\n bool IsSecureConnection { get; }\n // ... other interface definitions //\n}\n\ninterface ISecurableObject : IObject {\n new bool IsSecureConnection { get; set; }\n}\n</code></pre>\n\n<p>2) Split the set from the property, with an inherited interface:</p>\n\n<pre><code>interface IObject {\n bool IsSecureConnection { get; }\n // ... other interface definitions //\n}\n\ninterface ISecurableObject : IObject {\n void SetConnectionSecurity(bool isSecure);\n}\n</code></pre>\n\n<p>3) Changing the semantics to <em>try</em> and acquire a secure connection, which an implementer is free to just return false from:</p>\n\n<pre><code>interface ISecurable {\n bool IsSecureConnection { get; }\n bool TrySecureConnection();\n}\n</code></pre>\n\n<p>4) Add an additional check property:</p>\n\n<pre><code>interface ISecurable {\n bool IsSecureConnection { get; set; }\n bool SupportsSecureConnection { get; }\n}\n</code></pre>\n\n<p>All of these are, IMO, valid designs for certain contexts. Since I don't have any info on the use cases, except that almost all of the time a secure connection can be established - I'd probably vote for 3. It's easy to implement, there's only 1 code path for clients, and there's no exception mechanism (which is another form of coupling). You do have the danger of clients not checking the return from TrySecureConnection, but I think it has less issues than the other choices.</p>\n\n<p>If clients <em>prefer</em> a secure connection, but don't <em>require</em> one - then 1 has the disadvantage of either requiring overloads or the client to check if their IObject is really a ISecurableObject. Both of which are kind of ugly. 2 has the same problem, but without the troublesome new/shadows trickery. However, if some clients require a secure connection, then this (or 2) is probably the way to go - otherwise, you can't really use type safety to enforce a securable connection.</p>\n\n<p>4, while a valid design IMO (some would disagree - see reactions to IO.Stream) is easy for clients to get wrong. If 90% of implementers are securable, it's easy to not check the SupportsSecureConnection. There's also an implementer's choice of either throwing an exception or discarding the IsSecureConnection = true call if it's not supported, requiring clients to both catch and check the new value of IsSecureConnection.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132931/" ]
I have a property called "IsSecureConnection" that is part of my object's interface. This makes sense for most implementations of the interface, however, in some implementations I would like to make the property ReadOnly. Should I omit this property from the object's interface even though it is required by all of the implementations (though slightly different on occasion)? Thanks!
It really depends on what's most readable for your clients. I can think of a couple of options: 1) The inherited interface, though I'm not a fan of hiding, and I think it makes it a bit ugly for any VB.NET or explicit clients to implement: ``` interface IObject { bool IsSecureConnection { get; } // ... other interface definitions // } interface ISecurableObject : IObject { new bool IsSecureConnection { get; set; } } ``` 2) Split the set from the property, with an inherited interface: ``` interface IObject { bool IsSecureConnection { get; } // ... other interface definitions // } interface ISecurableObject : IObject { void SetConnectionSecurity(bool isSecure); } ``` 3) Changing the semantics to *try* and acquire a secure connection, which an implementer is free to just return false from: ``` interface ISecurable { bool IsSecureConnection { get; } bool TrySecureConnection(); } ``` 4) Add an additional check property: ``` interface ISecurable { bool IsSecureConnection { get; set; } bool SupportsSecureConnection { get; } } ``` All of these are, IMO, valid designs for certain contexts. Since I don't have any info on the use cases, except that almost all of the time a secure connection can be established - I'd probably vote for 3. It's easy to implement, there's only 1 code path for clients, and there's no exception mechanism (which is another form of coupling). You do have the danger of clients not checking the return from TrySecureConnection, but I think it has less issues than the other choices. If clients *prefer* a secure connection, but don't *require* one - then 1 has the disadvantage of either requiring overloads or the client to check if their IObject is really a ISecurableObject. Both of which are kind of ugly. 2 has the same problem, but without the troublesome new/shadows trickery. However, if some clients require a secure connection, then this (or 2) is probably the way to go - otherwise, you can't really use type safety to enforce a securable connection. 4, while a valid design IMO (some would disagree - see reactions to IO.Stream) is easy for clients to get wrong. If 90% of implementers are securable, it's easy to not check the SupportsSecureConnection. There's also an implementer's choice of either throwing an exception or discarding the IsSecureConnection = true call if it's not supported, requiring clients to both catch and check the new value of IsSecureConnection.
239,912
<p>Is there a Python class that wraps the <code>file</code> interface (read, write etc.) around a string? I mean something like the <code>stringstream</code> classes in C++.</p> <p>I was thinking of using it to redirect the output of <code>print</code> into a string, like this</p> <pre><code>sys.stdout = string_wrapper() print "foo", "bar", "baz" s = sys.stdout.to_string() #now s == "foo bar baz" </code></pre> <p>EDIT: This is a duplicate of <a href="https://stackoverflow.com/questions/141449/how-do-i-wrap-a-string-in-a-file-in-python">How do I wrap a string in a file in Python?</a></p>
[ { "answer_id": 239929, "author": "Peter Hoffmann", "author_id": 720, "author_profile": "https://Stackoverflow.com/users/720", "pm_score": 5, "selected": true, "text": "<p>Yes, there is StringIO:</p>\n\n<pre><code>import StringIO\nimport sys\n\n\nsys.stdout = StringIO.StringIO()\nprint \"foo\", \"bar\", \"baz\"\ns = sys.stdout.getvalue()\n</code></pre>\n" }, { "answer_id": 239944, "author": "Jason Baker", "author_id": 2147, "author_profile": "https://Stackoverflow.com/users/2147", "pm_score": 2, "selected": false, "text": "<p>For better performance, note that you can also use cStringIO. But also note that this isn't very portable to python 3.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30579/" ]
Is there a Python class that wraps the `file` interface (read, write etc.) around a string? I mean something like the `stringstream` classes in C++. I was thinking of using it to redirect the output of `print` into a string, like this ``` sys.stdout = string_wrapper() print "foo", "bar", "baz" s = sys.stdout.to_string() #now s == "foo bar baz" ``` EDIT: This is a duplicate of [How do I wrap a string in a file in Python?](https://stackoverflow.com/questions/141449/how-do-i-wrap-a-string-in-a-file-in-python)
Yes, there is StringIO: ``` import StringIO import sys sys.stdout = StringIO.StringIO() print "foo", "bar", "baz" s = sys.stdout.getvalue() ```
239,934
<p>I am using Oracle 10g R2. Recently, after rebooting the server, I started having a problem where I couldn't connect to the instance. I am only connecting locally on the server itself. </p> <p>Oddly enough, the issue corrects itself if I start the Database Administration Assistant, and select my instance to supposedly change its settings. </p> <p>Does anybody have a clue on the roots of this problem?</p> <p>@akaDruid: I am testing my connection simply by trying to start SQLPlus on the server. </p> <p>@Matthew: It's Windows</p>
[ { "answer_id": 240005, "author": "Colin Pickard", "author_id": 12744, "author_profile": "https://Stackoverflow.com/users/12744", "pm_score": 2, "selected": false, "text": "<p>EDIT: I don't think I read your question properly: The listener should not affect connections on the local machine, so you can probably ignore the rest of the answer, unless it gives you a hint! How were you testing your connection? Was ORA-12514 the only error?</p>\n\n<hr>\n\n<p>(I'm assuming you're on Windows here)\nI guess the listener is not starting automatically when you reboot the server, and it's getting starting in oracle administration assistant - I don't use that tool unfortunately so couldn't say.</p>\n\n<p>Next time you reboot, before starting oracle administration assistant, open a command prompt and type lsnrctl status. If the listener has not yet started you will get something like this:</p>\n\n<pre><code>C:\\Documents and Settings\\user&gt;lsnrctl status\n\nLSNRCTL for 32-bit Windows: Version 10.2.0.1.0 - Production on 27-OCT-2008 14:00:21\n\nCopyright (c) 1991, 2005, Oracle. All rights reserved.\n\nConnecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC01)))\nTNS-12541: TNS:no listener\n TNS-12560: TNS:protocol adapter error\n TNS-00511: No listener\n 32-bit Windows Error: 2: No such file or directory\nConnecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=server.domain.co.uk)\n(PORT=1521)))\nTNS-12541: TNS:no listener\n TNS-12560: TNS:protocol adapter error\n TNS-00511: No listener\n 32-bit Windows Error: 61: Unknown error\n\nC:\\Documents and Settings\\user&gt;lsnrctl status\n</code></pre>\n\n<p>if it is running, you will get something like this:</p>\n\n<pre><code>LSNRCTL for 32-bit Windows: Version 10.2.0.1.0 - Production on 27-OCT-2008 14:03\n:33\n\nCopyright (c) 1991, 2005, Oracle. All rights reserved.\n\nConnecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC01)))\nSTATUS of the LISTENER\n------------------------\nAlias LISTENER\nVersion TNSLSNR for 32-bit Windows: Version 10.2.0.1.0 - Production\nStart Date 27-OCT-2008 14:03:27\nUptime 0 days 0 hr. 0 min. 5 sec\nTrace Level off\nSecurity ON: Local OS Authentication\nSNMP OFF\nListener Parameter File C:\\oracle\\product\\10.2.0\\db_1\\network\\admin\\listener.ora\nListener Log File C:\\oracle\\product\\10.2.0\\db_1\\network\\log\\listener.log\n\nListening Endpoints Summary...\n (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\\\.\\pipe\\EXTPROC01ipc)))\n (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=server.domain.co.uk)(PORT=1521))\n)\nServices Summary...\nService \"ORCL\" has 1 instance(s).\n Instance \"ORCL\", status UNKNOWN, has 1 handler(s) for this service...\nService \"ORCL1\" has 1 instance(s).\n Instance \"ORCL1\", status UNKNOWN, has 1 handler(s) for this service...\nService \"PLSExtProc\" has 1 instance(s).\n Instance \"PLSExtProc\", status UNKNOWN, has 1 handler(s) for this service...\nThe command completed successfully\n\nC:\\Documents and Settings\\user&gt;\n</code></pre>\n\n<p>If the listener is not starting, check that service is set to automatic. If it is, check the listener.ora makes sense, see what output you get from lsnrctl start, etc.</p>\n\n<p>Hope that helps, or at least sends you down the right path</p>\n" }, { "answer_id": 241826, "author": "Matthew Watson", "author_id": 3839, "author_profile": "https://Stackoverflow.com/users/3839", "pm_score": 0, "selected": false, "text": "<p>You haven't specified if this is windows or unix?</p>\n\n<p>I've seen similar issues on unix when ORACLE_HOME was defined slightly differently on the account which starts up oracle, and on connecting accounts, one account had ORACLE_HOME=/usr/oracle , the other had ORACLE_HOME=/usr/oracle/ , the trailing slash messed things up.</p>\n\n<p>How exactly are you staring up the server, do you have a script to do it, or are you connecting internally and issuing \"startup\"</p>\n\n<p>again, if this is windows, I have no idea :)</p>\n" }, { "answer_id": 6154499, "author": "Tim Abell", "author_id": 10245, "author_profile": "https://Stackoverflow.com/users/10245", "pm_score": 0, "selected": false, "text": "<p>I had the same error. Going to <a href=\"http://localhost:1158/em\" rel=\"nofollow\">http://localhost:1158/em</a> showed the listener was up, but the database instance was down.</p>\n\n<p>Click the \"Startup\" button next to the instance to bring it back online (I think)</p>\n" }, { "answer_id": 6185499, "author": "Tim Abell", "author_id": 10245, "author_profile": "https://Stackoverflow.com/users/10245", "pm_score": 0, "selected": false, "text": "<p>Another possible explanation:</p>\n\n<p><a href=\"http://www.orafaq.com/forum/t/66224/2/\" rel=\"nofollow\">http://www.orafaq.com/forum/t/66224/2/</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3751/" ]
I am using Oracle 10g R2. Recently, after rebooting the server, I started having a problem where I couldn't connect to the instance. I am only connecting locally on the server itself. Oddly enough, the issue corrects itself if I start the Database Administration Assistant, and select my instance to supposedly change its settings. Does anybody have a clue on the roots of this problem? @akaDruid: I am testing my connection simply by trying to start SQLPlus on the server. @Matthew: It's Windows
EDIT: I don't think I read your question properly: The listener should not affect connections on the local machine, so you can probably ignore the rest of the answer, unless it gives you a hint! How were you testing your connection? Was ORA-12514 the only error? --- (I'm assuming you're on Windows here) I guess the listener is not starting automatically when you reboot the server, and it's getting starting in oracle administration assistant - I don't use that tool unfortunately so couldn't say. Next time you reboot, before starting oracle administration assistant, open a command prompt and type lsnrctl status. If the listener has not yet started you will get something like this: ``` C:\Documents and Settings\user>lsnrctl status LSNRCTL for 32-bit Windows: Version 10.2.0.1.0 - Production on 27-OCT-2008 14:00:21 Copyright (c) 1991, 2005, Oracle. All rights reserved. Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC01))) TNS-12541: TNS:no listener TNS-12560: TNS:protocol adapter error TNS-00511: No listener 32-bit Windows Error: 2: No such file or directory Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=server.domain.co.uk) (PORT=1521))) TNS-12541: TNS:no listener TNS-12560: TNS:protocol adapter error TNS-00511: No listener 32-bit Windows Error: 61: Unknown error C:\Documents and Settings\user>lsnrctl status ``` if it is running, you will get something like this: ``` LSNRCTL for 32-bit Windows: Version 10.2.0.1.0 - Production on 27-OCT-2008 14:03 :33 Copyright (c) 1991, 2005, Oracle. All rights reserved. Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC01))) STATUS of the LISTENER ------------------------ Alias LISTENER Version TNSLSNR for 32-bit Windows: Version 10.2.0.1.0 - Production Start Date 27-OCT-2008 14:03:27 Uptime 0 days 0 hr. 0 min. 5 sec Trace Level off Security ON: Local OS Authentication SNMP OFF Listener Parameter File C:\oracle\product\10.2.0\db_1\network\admin\listener.ora Listener Log File C:\oracle\product\10.2.0\db_1\network\log\listener.log Listening Endpoints Summary... (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(PIPENAME=\\.\pipe\EXTPROC01ipc))) (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=server.domain.co.uk)(PORT=1521)) ) Services Summary... Service "ORCL" has 1 instance(s). Instance "ORCL", status UNKNOWN, has 1 handler(s) for this service... Service "ORCL1" has 1 instance(s). Instance "ORCL1", status UNKNOWN, has 1 handler(s) for this service... Service "PLSExtProc" has 1 instance(s). Instance "PLSExtProc", status UNKNOWN, has 1 handler(s) for this service... The command completed successfully C:\Documents and Settings\user> ``` If the listener is not starting, check that service is set to automatic. If it is, check the listener.ora makes sense, see what output you get from lsnrctl start, etc. Hope that helps, or at least sends you down the right path
239,938
<p>i'm trying to change the number of rows in a <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.aspx" rel="nofollow noreferrer">TableLayoutPanel</a> programatically (sometimes it needs to be four, sometimes five, and rarely six).</p> <p>Unfortunatly changing the number of rows does not keep the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.rowstyles.aspx" rel="nofollow noreferrer"><code>RowStyles</code></a> collection in sync, so you are then not able to set the height of the newly added rows. The following test code demonstrates this fact:</p> <pre><code>private void button1_Click(object sender, EventArgs e) { //TableLayoutPanels start with 2 rows by default. Debug.Assert(tableLayoutPanel1.RowStyles.Count == tableLayoutPanel1.RowCount); //Cannot remove rows tableLayoutPanel1.RowCount = 1; Debug.Assert(tableLayoutPanel1.RowStyles.Count == tableLayoutPanel1.RowCount); } </code></pre> <p>The second assertion fails.</p> <pre><code>private void button2_Click(object sender, EventArgs e) { //TableLayoutPanels start with 2 rows by default. Debug.Assert(tableLayoutPanel1.RowStyles.Count == tableLayoutPanel1.RowCount); //Cannot add rows tableLayoutPanel1.RowCount = 6; Debug.Assert(tableLayoutPanel1.RowStyles.Count == tableLayoutPanel1.RowCount); } </code></pre> <p>The second assertion fails.</p> <p>So what's the proper programatic way to set the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.rowcount.aspx" rel="nofollow noreferrer"><code>RowCount</code></a> property of a <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.aspx" rel="nofollow noreferrer"><code>TableLayoutPanel</code></a>?</p>
[ { "answer_id": 240004, "author": "Mark Heath", "author_id": 7532, "author_profile": "https://Stackoverflow.com/users/7532", "pm_score": 0, "selected": false, "text": "<p>Have you tried creating a new <code>RowStyle</code> and then adding it using the <code>tableLayoutPanel1.RowStyles.Add</code> method?</p>\n" }, { "answer_id": 240140, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 3, "selected": false, "text": "<p>This issue was reported to Microsoft in 2005, and they acknowledge it's a bug<strike>, but they were \"<em>still evaluating our options here</em>\"</strike> Microsoft has decided not to fix it (\"Closed\").</p>\n\n<p><strong><a href=\"http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=122017\" rel=\"nofollow noreferrer\">TableLayoutPanel Rows and RowStyles do not correspond.</a></strong></p>\n\n<p><strong>Description</strong></p>\n\n<blockquote>\n <p>When you create a tableLayoutPanel,\n and new rows are created (either by\n adding rows in the program or setting\n the RowCount property), new RowStyles\n are not added to the control.\n Additionally, if I add new Row Styles,\n the number of rows is increased, but\n not to the same number: if I start\n with two Rows and two RowStyles, set\n Rowcount to 4, and then add two\n RowStyles (in design view), the\n Rowcount has set to 6. It seems more\n intuitive for the ordinality of the\n RowStyles collection to match the\n current RowCount.</p>\n</blockquote>\n\n<h2>Comments</h2>\n\n<p>Posted by Microsoft on 10/24/2005 at 6:07 PM </p>\n\n<blockquote>\n <p>This issue has been reactivated as we begin planning for the next version of Visual Studio. Over the coming months we will reconsider feedback that was previously postponed. We welcome your comments and participation in this process.</p>\n</blockquote>\n\n<p>Posted by Microsoft on 6/27/2005 at 6:49 AM</p>\n\n<blockquote>\n <p>The Microsoft Sub-status is now\n \"Reproduced\"</p>\n \n <p>Thanks for reporting this bug, we have\n been able to repro this issue and are\n investigating.</p>\n \n <p>Thank you, Prabhu, VS2005 Product\n Team.</p>\n</blockquote>\n\n<p>Posted by Microsoft on 6/27/2005 at 5:55 PM </p>\n\n<blockquote>\n <p>Thankyou for reporting this issue.\n This is a peculiarity in our runtime\n object model that doesn't translate\n well to design time. At runtime the\n RowCount and ColCount really mean\n minRowCount and minColCount in terms\n of autogrow, because rows/cols don't\n need a supporting style. At design\n time we try to simplify that and keep\n a near 1:1 correspondence between\n styles and rows/cols. In this case,\n you are seeing by design runtime\n behavior. We already have a bug\n tracking this issue and are still\n evaluating our options here. Thanks\n again for contributing to a better\n Whidbey. </p>\n</blockquote>\n\n<p>Posted by Microsoft on 7/6/2005 at 3:43 PM</p>\n\n<blockquote>\n <p>Thankyou for\n reporting this issue. This is a\n peculiarity in our runtime object\n model that we have chosen to not\n address at design time. At runtime the\n RowCount and ColCount really mean\n minRowCount and minColCount in terms\n of autogrow, because rows/cols don't\n require a supporting style. At design\n time we generally try to simplify that\n and keep a near 1:1 correspondence\n between styles and rows/cols. In the\n case of rowSpan or colSpan on a table\n layot panel with autogrow you can get\n into a state where\n rows/rowcount/rowstyles are out of\n sync. To avoid this, simply add the\n columns/rows you need first, then set\n the controls *span property. Thanks.</p>\n</blockquote>\n\n<p>Posted by Microsoft on 10/24/2005 at 6:07 PM</p>\n\n<blockquote>\n <p>This issue has been reactivated as we\n begin planning for the next version of\n Visual Studio. Over the coming months\n we will reconsider feedback that was\n previously postponed. We welcome your\n comments and participation in this\n process.</p>\n \n <p>-- Visual Studio Team </p>\n</blockquote>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
i'm trying to change the number of rows in a [TableLayoutPanel](http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.aspx) programatically (sometimes it needs to be four, sometimes five, and rarely six). Unfortunatly changing the number of rows does not keep the [`RowStyles`](http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.rowstyles.aspx) collection in sync, so you are then not able to set the height of the newly added rows. The following test code demonstrates this fact: ``` private void button1_Click(object sender, EventArgs e) { //TableLayoutPanels start with 2 rows by default. Debug.Assert(tableLayoutPanel1.RowStyles.Count == tableLayoutPanel1.RowCount); //Cannot remove rows tableLayoutPanel1.RowCount = 1; Debug.Assert(tableLayoutPanel1.RowStyles.Count == tableLayoutPanel1.RowCount); } ``` The second assertion fails. ``` private void button2_Click(object sender, EventArgs e) { //TableLayoutPanels start with 2 rows by default. Debug.Assert(tableLayoutPanel1.RowStyles.Count == tableLayoutPanel1.RowCount); //Cannot add rows tableLayoutPanel1.RowCount = 6; Debug.Assert(tableLayoutPanel1.RowStyles.Count == tableLayoutPanel1.RowCount); } ``` The second assertion fails. So what's the proper programatic way to set the [`RowCount`](http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.rowcount.aspx) property of a [`TableLayoutPanel`](http://msdn.microsoft.com/en-us/library/system.windows.forms.tablelayoutpanel.aspx)?
This issue was reported to Microsoft in 2005, and they acknowledge it's a bug, but they were "*still evaluating our options here*" Microsoft has decided not to fix it ("Closed"). **[TableLayoutPanel Rows and RowStyles do not correspond.](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=122017)** **Description** > > When you create a tableLayoutPanel, > and new rows are created (either by > adding rows in the program or setting > the RowCount property), new RowStyles > are not added to the control. > Additionally, if I add new Row Styles, > the number of rows is increased, but > not to the same number: if I start > with two Rows and two RowStyles, set > Rowcount to 4, and then add two > RowStyles (in design view), the > Rowcount has set to 6. It seems more > intuitive for the ordinality of the > RowStyles collection to match the > current RowCount. > > > Comments -------- Posted by Microsoft on 10/24/2005 at 6:07 PM > > This issue has been reactivated as we begin planning for the next version of Visual Studio. Over the coming months we will reconsider feedback that was previously postponed. We welcome your comments and participation in this process. > > > Posted by Microsoft on 6/27/2005 at 6:49 AM > > The Microsoft Sub-status is now > "Reproduced" > > > Thanks for reporting this bug, we have > been able to repro this issue and are > investigating. > > > Thank you, Prabhu, VS2005 Product > Team. > > > Posted by Microsoft on 6/27/2005 at 5:55 PM > > Thankyou for reporting this issue. > This is a peculiarity in our runtime > object model that doesn't translate > well to design time. At runtime the > RowCount and ColCount really mean > minRowCount and minColCount in terms > of autogrow, because rows/cols don't > need a supporting style. At design > time we try to simplify that and keep > a near 1:1 correspondence between > styles and rows/cols. In this case, > you are seeing by design runtime > behavior. We already have a bug > tracking this issue and are still > evaluating our options here. Thanks > again for contributing to a better > Whidbey. > > > Posted by Microsoft on 7/6/2005 at 3:43 PM > > Thankyou for > reporting this issue. This is a > peculiarity in our runtime object > model that we have chosen to not > address at design time. At runtime the > RowCount and ColCount really mean > minRowCount and minColCount in terms > of autogrow, because rows/cols don't > require a supporting style. At design > time we generally try to simplify that > and keep a near 1:1 correspondence > between styles and rows/cols. In the > case of rowSpan or colSpan on a table > layot panel with autogrow you can get > into a state where > rows/rowcount/rowstyles are out of > sync. To avoid this, simply add the > columns/rows you need first, then set > the controls \*span property. Thanks. > > > Posted by Microsoft on 10/24/2005 at 6:07 PM > > This issue has been reactivated as we > begin planning for the next version of > Visual Studio. Over the coming months > we will reconsider feedback that was > previously postponed. We welcome your > comments and participation in this > process. > > > -- Visual Studio Team > > >
239,945
<p>I'm creating a really complex dynamic sql, it's got to return one row per user, but now I have to join against a one to many table. I do an outer join to make sure I get at least one row back (and can check for null to see if there's data in that table) but I have to make sure I only get one row back from this outer join part if there's multiple rows in this second table for this user. So far I've come up with this: (sybase)</p> <pre><code>SELECT a.user_id FROM table1 a ,table2 b WHERE a.user_id = b.user_id AND a.sub_id = ( SELECT min(c.sub_id) FROM table2 c WHERE b.sub_id = c.sub_id ) </code></pre> <p>The subquery finds the min value in the one to many table for that particular user.</p> <p>This works but I fear nastiness from doing correlated subqueries when table 1 and 2 get very large. Is there a better way? I'm trying to dream up a way to get joins to do it, but I'm not seeing it. Also saying "where rowcount=1" or "top 1" doesn't help me, because I'm not trying to fix the above query, I'm ADDING the above to an already complex query.</p>
[ { "answer_id": 239956, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 0, "selected": false, "text": "<p>Maybe your example is too simplified, but I'd use a group by:</p>\n\n<pre>\nSELECT\n a.user_id \nFROM \n table1 a\n LEFT OUTER JOIN table2 b ON (a.user_id = b.user_id)\nGROUP BY\n a.user_id\n</pre>\n\n<p>I fear the only other way would be using nested queries:</p>\n\n<p>The difference between this query and your example is a 'sub table' is only generated once, however in your example you generate a 'sub table' for each row in table1 (but may depend on the compiler, so you might want to use query analyser to check performance). </p>\n\n<pre>\nSELECT\n a.user_id,\n b.sub_id\nFROM \n table1 a\n LEFT OUTER JOIN (\n SELECT\n user_id,\n min(sub_id) as sub_id,\n FROM\n table2\n GROUP BY\n user_id\n ) b ON (a.user_id = b.user_id)\n</pre>\n\n<p>Also, if your query is getting quite complex I'd use temporary tables to simplify the code, it might cost a little more in processing time, but will make your queries much easier to maintain.</p>\n\n<p>A Temp Table example would be:</p>\n\n<pre>\nSELECT\n user_id\nINTO\n #table1\nFROM \n table1\nWHERE\n .....\n\nSELECT\n a.user_id,\n min(b.sub_id) as sub_id,\nINTO\n #table2\nFROM\n #table1 a\n INNER JOIN table2 b ON (a.user_id = b.user_id)\nGROUP BY\n a.user_id\n\nSELECT\n a.*,\n b.sub_id\nfrom\n #table1 a\n LEFT OUTER JOIN #table2 b ON (a.user_id = b.user_id)\n</pre>\n" }, { "answer_id": 240040, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 0, "selected": false, "text": "<p>How about:</p>\n\n<pre><code>select a.user_id \nfrom table1 a\nwhere exists (select null from table2 b \n where a.user_id = b.user_id \n )\n</code></pre>\n" }, { "answer_id": 240101, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 1, "selected": false, "text": "<p>In MySql you can ensure that any query returns at most X rows using</p>\n\n<pre><code>select *\nfrom foo\nwhere bar = 1\nlimit X;\n</code></pre>\n\n<p>Unfortunately, I'm fairly sure this is a MySQL-specific extension to SQL. However, a Google search for something like \"mysql sybase limit\" might turn up an equivalent for Sybase.</p>\n" }, { "answer_id": 240153, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>First of all, I believe the query you are trying to write as your example is:</p>\n\n<pre><code>select a.user_id \nfrom table1 a, table2 b \nwhere a.user_id = b.user_id \nand b.sub_id = (select min(c.sub_id) \n from table2 c \n where b.user_id = c.user_id)\n</code></pre>\n\n<p>Except you wanted an outer join (which I think someone edited out the Oracle syntax).</p>\n\n<pre><code>select a.user_id \nfrom table1 a\nleft outer join table2 b on a.user_id = b.user_id \nwhere b.sub_id = (select min(c.sub_id) \n from table2 c \n where b.user_id = c.user_id)\n</code></pre>\n" }, { "answer_id": 240240, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": 1, "selected": false, "text": "<p>A few quick points:</p>\n\n<ol>\n<li>You need to have definitive business rules. If the query returns more than one row then you need to think about why (beyond just \"it's a 1:many relationship - WHY is it a 1:many relationship?). You should come up with the business solution rather than just use \"min\" because it gives you 1 row. The business solution might simply be \"take the first one\", in which case min might be the answer, but you need to make sure that's a conscious decision.</li>\n<li>You should really try to use the ANSI syntax for joins. Not just because it's standard, but because the syntax that you have isn't really doing what you think it's doing (it's not an outer join) and some things are simply impossible to do with the syntax that you have.</li>\n</ol>\n\n<p>Assuming that you end up using the MIN solution, here's one possible solution without the subquery. You should test it with various other solutions to make sure that they are equivalent in outcome and to see which performs the best.</p>\n\n<pre><code>SELECT\n a.user_id, b.*\nFROM\n dbo.Table_1 a\nLEFT OUTER JOIN dbo.Table_2 b ON b.user_id = a.user_id AND b.sub_id = a.sub_id\nLEFT OUTER JOIN dbo.Table_2 c ON c.user_id = a.user_id AND c.sub_id &lt; b.sub_id\nWHERE\n c.user_id IS NULL\n</code></pre>\n\n<p>You'll need to test this to see if it's really giving what you want and you might need to tweak it, but the basic idea is to use the second LEFT OUTER JOIN to ensure that there are no rows that exist with a lower sub_id than the one found in the first LEFT OUTER JOIN (if any is found). You can adjust the criteria in the second LEFT OUTER JOIN depending on the final business rules.</p>\n" }, { "answer_id": 240259, "author": "neonski", "author_id": 17112, "author_profile": "https://Stackoverflow.com/users/17112", "pm_score": -1, "selected": false, "text": "<p>Well, you already have a query that works. If you are concerned about the speed you could</p>\n\n<ul>\n<li><p>Add a field to table2 which\n identifies which sub_id is the\n 'first one' or</p></li>\n<li><p>Keep track of table2's primary key in table1, or in another table</p></li>\n</ul>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12386/" ]
I'm creating a really complex dynamic sql, it's got to return one row per user, but now I have to join against a one to many table. I do an outer join to make sure I get at least one row back (and can check for null to see if there's data in that table) but I have to make sure I only get one row back from this outer join part if there's multiple rows in this second table for this user. So far I've come up with this: (sybase) ``` SELECT a.user_id FROM table1 a ,table2 b WHERE a.user_id = b.user_id AND a.sub_id = ( SELECT min(c.sub_id) FROM table2 c WHERE b.sub_id = c.sub_id ) ``` The subquery finds the min value in the one to many table for that particular user. This works but I fear nastiness from doing correlated subqueries when table 1 and 2 get very large. Is there a better way? I'm trying to dream up a way to get joins to do it, but I'm not seeing it. Also saying "where rowcount=1" or "top 1" doesn't help me, because I'm not trying to fix the above query, I'm ADDING the above to an already complex query.
In MySql you can ensure that any query returns at most X rows using ``` select * from foo where bar = 1 limit X; ``` Unfortunately, I'm fairly sure this is a MySQL-specific extension to SQL. However, a Google search for something like "mysql sybase limit" might turn up an equivalent for Sybase.
239,951
<p>For example for the following XML</p> <pre><code> &lt;Order&gt; &lt;Phone&gt;1254&lt;/Phone&gt; &lt;City&gt;City1&lt;/City&gt; &lt;State&gt;State&lt;/State&gt; &lt;/Order&gt; </code></pre> <p>I might want to find out whether the XElement contains "City" Node or not. </p>
[ { "answer_id": 239963, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 7, "selected": true, "text": "<p>Just use the other overload for <a href=\"http://msdn.microsoft.com/en-us/library/bb348975.aspx\" rel=\"noreferrer\">Elements</a>.</p>\n\n<pre><code>bool hasCity = OrderXml.Elements(\"City\").Any();\n</code></pre>\n" }, { "answer_id": 239969, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>It's been a while since I did XLinq, but here goes my WAG:</p>\n\n<pre><code>from x in XDocument\nwhere x.Elements(\"City\").Count &gt; 0\nselect x\n</code></pre>\n\n<p>;</p>\n" }, { "answer_id": 6420146, "author": "Mark", "author_id": 807738, "author_profile": "https://Stackoverflow.com/users/807738", "pm_score": 1, "selected": false, "text": "<p>David's is the best but if you want you can write your own predicate if you need some custom logic <code>OrderXML.Elements(\"City\").Exists(x=&gt;x.Name ==\"City\")</code></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/239951", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688440/" ]
For example for the following XML ``` <Order> <Phone>1254</Phone> <City>City1</City> <State>State</State> </Order> ``` I might want to find out whether the XElement contains "City" Node or not.
Just use the other overload for [Elements](http://msdn.microsoft.com/en-us/library/bb348975.aspx). ``` bool hasCity = OrderXml.Elements("City").Any(); ```
240,012
<p>This is a follow-up to a previous question I had about interfaces. I received an answer that I like, but I'm not sure how to implement it in VB.NET.</p> <p>Previous question:</p> <p><a href="https://stackoverflow.com/questions/239909/should-this-property-be-part-of-my-objects-interface">Should this property be part of my object&#39;s interface?</a></p> <pre><code>public interface Foo{ bool MyMinimallyReadOnlyPropertyThatCanAlsoBeReadWrite {get;} } </code></pre> <p>How can I achieve this with the VB.NET syntax? As far as I know, my only option is to mark the property as ReadOnly (I cannot implement the setter) or not (I must implement the setter).</p>
[ { "answer_id": 240036, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 3, "selected": true, "text": "<p>Simply define the getter in one interface, and create a second interface that has both the getter and the setter. If your concrete class is mutable, have it implement the second interface. In your code that deals with the class, check to see that it is an instance of the second interface, cast if so, then call the setter.</p>\n" }, { "answer_id": 240050, "author": "Martin Moser", "author_id": 24756, "author_profile": "https://Stackoverflow.com/users/24756", "pm_score": 1, "selected": false, "text": "<p>In VB.NET I would implement it this way:</p>\n\n<pre><code>Public Interface ICanBeSecure\n\n ReadOnly Property IsSecureConnection() As Boolean\nEnd Interface\n\nPublic Interface IIsSecureable\n Inherits ICanBeSecure\n\n Shadows Property IsSecureConnection() As Boolean\nEnd Interface\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/132931/" ]
This is a follow-up to a previous question I had about interfaces. I received an answer that I like, but I'm not sure how to implement it in VB.NET. Previous question: [Should this property be part of my object's interface?](https://stackoverflow.com/questions/239909/should-this-property-be-part-of-my-objects-interface) ``` public interface Foo{ bool MyMinimallyReadOnlyPropertyThatCanAlsoBeReadWrite {get;} } ``` How can I achieve this with the VB.NET syntax? As far as I know, my only option is to mark the property as ReadOnly (I cannot implement the setter) or not (I must implement the setter).
Simply define the getter in one interface, and create a second interface that has both the getter and the setter. If your concrete class is mutable, have it implement the second interface. In your code that deals with the class, check to see that it is an instance of the second interface, cast if so, then call the setter.
240,016
<p>I have created a class for a dashboard item which will hold information such as placement on the dashboard, description, etc. I am currently using a pair of Collections to hold those dashboard items contained in the "library" and those items showing on the dashboard itself. I have been asked to make this dashboard multi-tab, and my first inclination was to make a new Collection for each tab. For this I would want some type of array or collection which could have many of these dashboard item collections added to it as more tabs are added to the dashboard.</p> <p>Is this possible, and if so, could I get a little code snip for the declaration of such a collection? I have considered using a single collection with a variable to show which tab the item will be shown in... However, the display and routines to manage dashboard item movement between screen and library currently need those individual collections.</p> <p>Edit: Thank you for your answers. While I do find them all interesting I believe I am going to go with James solution and will be marking it as the accepted answer.</p>
[ { "answer_id": 240027, "author": "Charles Graham", "author_id": 7705, "author_profile": "https://Stackoverflow.com/users/7705", "pm_score": 1, "selected": false, "text": "<p>Why not create a class that contains your second collection and any of the previous information, and just have a collection of these items?</p>\n" }, { "answer_id": 240042, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": true, "text": "<pre><code>List&lt; List&lt;Placement&gt;&gt; ListofListOfPlacements = new List&lt; List&lt;Placement&gt;&gt; ();\n\nList&lt;Placement&gt; dashboard1 = new List&lt;Placement&gt;();\nList&lt;Placement&gt; dashboard2 = new List&lt;Placement&gt;();\nList&lt;Placement&gt; dashboard3 = new List&lt;Placement&gt;();\nList&lt;Placement&gt; dashboard4 = new List&lt;Placement&gt;();\n\nListofListOfPlacements.Add(dashboard1);\nListofListOfPlacements.Add(dashboard2);\nListofListOfPlacements.Add(dashboard3);\nListofListOfPlacements.Add(dashboard4);\n</code></pre>\n" }, { "answer_id": 240094, "author": "Hath", "author_id": 5186, "author_profile": "https://Stackoverflow.com/users/5186", "pm_score": 1, "selected": false, "text": "<p>why not put your collection of dash board items in a tabpage class?</p>\n\n<p>like so:</p>\n\n<pre><code>public class DashboardTabPage : TabPage\n{\n public List&lt;DashboardItem&gt; DashboardItems { get; set; }\n\n public DashboardTabPage() : this (new List&lt;DashboardItem&gt;())\n {\n\n }\n\n public DashboardTabPage(List&lt;DashboardItem&gt; items) :base (\"Dashboard Thing\")\n {\n DashboardItems = items;\n }\n\n}\n</code></pre>\n\n<p>public class DashboardItem { }</p>\n\n<p>then you can do this:</p>\n\n<pre><code>c.TabPages.Add(new DashboardTabPage());\n</code></pre>\n" }, { "answer_id": 240114, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>Since you are talking about tabs, it sounds to me like you want something closer to a dictionary keyed on the tab name, with a set of items per tab. .NET 3.5 added the <code>ILookup&lt;,&gt;</code> interface:</p>\n\n<pre><code> ILookup&lt;string, Foo&gt; items = null; //TODO\n foreach (Foo foo in items[\"SomeTab\"])\n {\n Console.WriteLine(foo.Bar);\n }\n</code></pre>\n\n<p>Note that the MS implementation is immutable - you can't edit it after creation; however, I wrote an <code>EditableLookup&lt;,&gt;</code> in <a href=\"http://www.pobox.com/~skeet/csharp/miscutil/\" rel=\"nofollow noreferrer\">MiscUtil</a> that allows you to work more effectively (just like a regular .NET collection):</p>\n\n<pre><code> var items = new EditableLookup&lt;string, Foo&gt;();\n items.Add(\"SomeTab\", new Foo { Bar = \"abc\" });\n items.Add(\"AnotherTab\", new Foo { Bar = \"def\" });\n items.Add(\"SomeTab\", new Foo { Bar = \"ghi\" });\n foreach (Foo foo in items[\"SomeTab\"])\n { // prints \"abc\" and \"ghi\"\n Console.WriteLine(foo.Bar);\n }\n</code></pre>\n\n<p>Without <code>EditableLookup&lt;,&gt;</code>, you need to build the lookup via the <code>Enumerable.ToLookup</code> extension method.</p>\n\n<p>If any part of this sounds like an option, I can add more detail...</p>\n" }, { "answer_id": 650140, "author": "Kunal S", "author_id": 64938, "author_profile": "https://Stackoverflow.com/users/64938", "pm_score": 0, "selected": false, "text": "<p>I think you should go with composition, as below</p>\n\n<p>Per user Dashboard-home(having multiple tabs) object containing list of dashboard objects containing list of dashboard item objects having various operations on them defined. Again the dashboard item can be a usercontrol having all possible events defined which are handled either there in dashboard item object and/or left to do for dashboard UI object that'll work with individual dashboard objects.</p>\n\n<p>I guess this would be better manageable, if you are going to follow SOA and reusable component based architecture.</p>\n" }, { "answer_id": 57409887, "author": "Shimmy Weitzhandler", "author_id": 75500, "author_profile": "https://Stackoverflow.com/users/75500", "pm_score": 0, "selected": false, "text": "<p>You can also use a tuple like this: <code>List&lt;(string Father, IEnumerable&lt;string&gt; Children)&gt;</code>.</p>\n\n<p>Example:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>var list = new List&lt;(string Parent, IEnumerable&lt;string&gt; Children)&gt;\n{\n (\"Bob\", new[] { \"Charlie\", \"Marie\" }),\n (\"Robert\", new[] { \"John\", \"Geoff\", \"Oliver\" }),\n};\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30838/" ]
I have created a class for a dashboard item which will hold information such as placement on the dashboard, description, etc. I am currently using a pair of Collections to hold those dashboard items contained in the "library" and those items showing on the dashboard itself. I have been asked to make this dashboard multi-tab, and my first inclination was to make a new Collection for each tab. For this I would want some type of array or collection which could have many of these dashboard item collections added to it as more tabs are added to the dashboard. Is this possible, and if so, could I get a little code snip for the declaration of such a collection? I have considered using a single collection with a variable to show which tab the item will be shown in... However, the display and routines to manage dashboard item movement between screen and library currently need those individual collections. Edit: Thank you for your answers. While I do find them all interesting I believe I am going to go with James solution and will be marking it as the accepted answer.
``` List< List<Placement>> ListofListOfPlacements = new List< List<Placement>> (); List<Placement> dashboard1 = new List<Placement>(); List<Placement> dashboard2 = new List<Placement>(); List<Placement> dashboard3 = new List<Placement>(); List<Placement> dashboard4 = new List<Placement>(); ListofListOfPlacements.Add(dashboard1); ListofListOfPlacements.Add(dashboard2); ListofListOfPlacements.Add(dashboard3); ListofListOfPlacements.Add(dashboard4); ```
240,031
<p>I'm working on a program to do some image wrangling in Python for work. I'm using FreeImagePy because PIL doesn't support multi-page TIFFs. Whenever I try to save a file with it from my program I get this error message (or something similar depending on which way I try to save):</p> <pre><code>Error returned. TIFF FreeImage_Save: failed to open file C:/OCRtmp/ocr page0 Traceback (most recent call last): File "C:\Python25\Projects\OCRPageUnzipper\PageUnzipper.py", line 102, in &lt;mod ule&gt; OCRBox.convertToPages("C:/OCRtmp/ocr page",FIPY.FIF_TIFF) File "C:\Python25\lib\site-packages\FreeImagePy\FreeImagePy\FreeImagePy.py", l ine 2080, in convertToPages self.Save(FIF, dib, fileNameOut, flags) File "C:\Python25\lib\site-packages\FreeImagePy\FreeImagePy\FreeImagePy.py", l ine 187, in Save return self.__lib.Save(typ, bitmap, fileName, flags) WindowsError: exception: priviledged instruction </code></pre> <p>When I try and do the same things from IDLE, it works fine.</p>
[ { "answer_id": 242366, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 1, "selected": false, "text": "<p>Looks like a permission issues, make sure you don't have the file open in another application, and that you have write permissions to the file location your trying to write to.</p>\n" }, { "answer_id": 244526, "author": "Tofystedeth", "author_id": 31801, "author_profile": "https://Stackoverflow.com/users/31801", "pm_score": 0, "selected": false, "text": "<p>That's what I thought too, but I figured it out a couple hours ago. Apparently if the directory/file I'm trying to write to doesn't exist, FreeImagePy isn't smart enough to create it (most of the time. Creating a new multipage image seems to work fine) but i guess running it within IDLE, IDLE figures it out and takes care of it or something. I managed to work around it by using os.mkdir to explicitly make sure things that I need exist.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31801/" ]
I'm working on a program to do some image wrangling in Python for work. I'm using FreeImagePy because PIL doesn't support multi-page TIFFs. Whenever I try to save a file with it from my program I get this error message (or something similar depending on which way I try to save): ``` Error returned. TIFF FreeImage_Save: failed to open file C:/OCRtmp/ocr page0 Traceback (most recent call last): File "C:\Python25\Projects\OCRPageUnzipper\PageUnzipper.py", line 102, in <mod ule> OCRBox.convertToPages("C:/OCRtmp/ocr page",FIPY.FIF_TIFF) File "C:\Python25\lib\site-packages\FreeImagePy\FreeImagePy\FreeImagePy.py", l ine 2080, in convertToPages self.Save(FIF, dib, fileNameOut, flags) File "C:\Python25\lib\site-packages\FreeImagePy\FreeImagePy\FreeImagePy.py", l ine 187, in Save return self.__lib.Save(typ, bitmap, fileName, flags) WindowsError: exception: priviledged instruction ``` When I try and do the same things from IDLE, it works fine.
Looks like a permission issues, make sure you don't have the file open in another application, and that you have write permissions to the file location your trying to write to.
240,046
<p>I'd like to use Oracle's utl_match.edit_distance function. It supposed to compare two strings and return the <a href="http://en.wikipedia.org/wiki/Levenshtein_Distance" rel="nofollow noreferrer">Levenshtein distance</a>.</p> <pre><code>select utl_match.edit_distance('a','b') from dual </code></pre> <p>returns 1 as expected, but</p> <pre><code>select utl_match.edit_distance('á','b') from dual </code></pre> <p>returns 2. Obviously I'd like to get 1.</p> <p>It seems to be, it does not work correctly for special characters. I'm using Oracle 10.2.0.4 and AL32UTF8 character set.</p>
[ { "answer_id": 240121, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 1, "selected": false, "text": "<p>I agree, it appears to be wrong. However, this package is undocumented by Oracle, so is perhaps unsupported at present.</p>\n" }, { "answer_id": 240356, "author": "Justin Cave", "author_id": 10397, "author_profile": "https://Stackoverflow.com/users/10397", "pm_score": 3, "selected": true, "text": "<p>This seems to be related to the character set. If I run the same test in a 10.2.0.3 and 11.1.0.7 database using ISO8859P15 as the character set, I get a distance of 1 as well. I'm guessing that Oracle is computing the distance in terms of bytes rather than characters in variable-width character sets.</p>\n\n<p>You can work around the problem using the CONVERT function to convert to a fixed-width character set (AL16UTF16 or a local character set)</p>\n\n<pre><code>SQL&gt; ed\nWrote file afiedt.buf\n\n 1 declare\n 2 l_char1 varchar2(1 char) := 'á';\n 3 l_char2 varchar2(1 char) := 'b';\n 4 begin\n 5 dbms_output.put_line(\n 6 'In AL32UTF8: ' ||\n 7 utl_match.edit_distance( l_char1, l_char2 ) );\n 8 dbms_output.put_line(\n 9 'In WE8ISO8859P15: ' ||\n 10 utl_match.edit_distance(\n 11 CONVERT( l_char1, 'WE8ISO8859P15', 'AL32UTF8' ),\n 12 CONVERT( l_char2, 'WE8ISO8859P15', 'AL32UTF8' ) ) );\n 13 dbms_output.put_line(\n 14 'In AL16UTF16: ' ||\n 15 utl_match.edit_distance(\n 16 CONVERT( l_char1, 'AL16UTF16', 'AL32UTF8' ),\n 17 CONVERT( l_char2, 'AL16UTF16', 'AL32UTF8' ) ) );\n 18* end;\nSQL&gt; /\nIn AL32UTF8: 2\nIn WE8ISO8859P15: 1\nIn AL16UTF16: 1\n\nPL/SQL procedure successfully completed.\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21348/" ]
I'd like to use Oracle's utl\_match.edit\_distance function. It supposed to compare two strings and return the [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_Distance). ``` select utl_match.edit_distance('a','b') from dual ``` returns 1 as expected, but ``` select utl_match.edit_distance('á','b') from dual ``` returns 2. Obviously I'd like to get 1. It seems to be, it does not work correctly for special characters. I'm using Oracle 10.2.0.4 and AL32UTF8 character set.
This seems to be related to the character set. If I run the same test in a 10.2.0.3 and 11.1.0.7 database using ISO8859P15 as the character set, I get a distance of 1 as well. I'm guessing that Oracle is computing the distance in terms of bytes rather than characters in variable-width character sets. You can work around the problem using the CONVERT function to convert to a fixed-width character set (AL16UTF16 or a local character set) ``` SQL> ed Wrote file afiedt.buf 1 declare 2 l_char1 varchar2(1 char) := 'á'; 3 l_char2 varchar2(1 char) := 'b'; 4 begin 5 dbms_output.put_line( 6 'In AL32UTF8: ' || 7 utl_match.edit_distance( l_char1, l_char2 ) ); 8 dbms_output.put_line( 9 'In WE8ISO8859P15: ' || 10 utl_match.edit_distance( 11 CONVERT( l_char1, 'WE8ISO8859P15', 'AL32UTF8' ), 12 CONVERT( l_char2, 'WE8ISO8859P15', 'AL32UTF8' ) ) ); 13 dbms_output.put_line( 14 'In AL16UTF16: ' || 15 utl_match.edit_distance( 16 CONVERT( l_char1, 'AL16UTF16', 'AL32UTF8' ), 17 CONVERT( l_char2, 'AL16UTF16', 'AL32UTF8' ) ) ); 18* end; SQL> / In AL32UTF8: 2 In WE8ISO8859P15: 1 In AL16UTF16: 1 PL/SQL procedure successfully completed. ```
240,047
<p>In SQL Server, why is this:</p> <pre><code>[dbo].[table_name] </code></pre> <p>preferable to this:</p> <pre><code>dbo.table_name </code></pre> <p>And along those lines, why even list the dbo at all if there's only one schema?</p>
[ { "answer_id": 240052, "author": "Iain Holder", "author_id": 1122, "author_profile": "https://Stackoverflow.com/users/1122", "pm_score": 3, "selected": true, "text": "<p>It's just in case you have a keyword as a tablename like [user]</p>\n" }, { "answer_id": 240056, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 2, "selected": false, "text": "<p>If the table name contains key words, you will have to enclose it inside [ ]. Most of the tools (like ORM) use this technique to avoid any errors or for consistency.</p>\n" }, { "answer_id": 240057, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>It allows keywords or punctuation in a table name. </p>\n\n<p>It's often used by code generators for all names, so they don't have to figure out if it actually needed.</p>\n" }, { "answer_id": 240059, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "<p>These usually come up in generated code - because it's easier to make the code generation produce fully-qualified and escaped references than to deduce what escaping/qualification is required when.</p>\n" }, { "answer_id": 240060, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 2, "selected": false, "text": "<p>If there is only one schema then prefixing the table name is not necessary or useful I think. Using the brackets [] is useful when you have an identifier that is a reserved word in sql server. If, for instance, you have a table named Select you can refernce it as <code>SELECT * FROM [Select]</code> but not as <code>SELECT * FROM Select</code>.</p>\n" }, { "answer_id": 240062, "author": "DiningPhilanderer", "author_id": 30934, "author_profile": "https://Stackoverflow.com/users/30934", "pm_score": 0, "selected": false, "text": "<p>Doesn't this allow you to have whatever 'bad' items you desire in there?<br>\nKeywords, spaces, etc...</p>\n" }, { "answer_id": 240064, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 0, "selected": false, "text": "<p>I would prefer to avoid using punctuation and reserved words in table and column names, and not use the square brackets. This makes the SQL far easier to read.</p>\n" }, { "answer_id": 240147, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 1, "selected": false, "text": "<p>I don't use the brackets, which are only necessary if you use keywords as schemas or table names, which you shouldn't.</p>\n\n<p>But I would recommend against dropping the dbo at the front. The reason is that eventually you might want to start organizing your code into schemas, and then you will need the prefix. If you get in the habit of using the schema.table format, it will be a <em>lot</em> easier to search your code for places where the tables are used.</p>\n\n<p>Let's say you have a table called dbo.user, and you decide to move it to another schema. If you have to search through a bunch of stored procedures or dynamic sql for \"user\", you will likely get a ton of false positives. You can't be totally sure that you made all the changes you needed to. Searching for \"dbo.user\" is a lot more concise.</p>\n" }, { "answer_id": 247974, "author": "pipTheGeek", "author_id": 28552, "author_profile": "https://Stackoverflow.com/users/28552", "pm_score": 1, "selected": false, "text": "<p>The [] are only required if the object name contains characters like spaces or if it is a keyword. It is generally regarded as best practice not to use any of these as object names so you should never need the []. Having said that they also do no harm, if it is generated code and includes the brackets then you may as well leave them.<br>\nUsing dbo is a good idea becuase</p>\n\n<ol>\n<li>Performance is better (see <a href=\"http://sqlblog.com/blogs/linchi_shea/archive/2007/07/05/performance-impact-of-procedure-calls-without-owner-qualification-sql-server-2000.aspx\" rel=\"nofollow noreferrer\">here</a> for some figures)</li>\n<li>dbo is required in some cases, like calling user defined functions. I think it is tidyer to always include it.</li>\n<li>Not qualifying the object name could lead to bugs in the future if you do create multiple schemas.</li>\n</ol>\n" }, { "answer_id": 24982794, "author": "Milica Medic Kiralj", "author_id": 2583780, "author_profile": "https://Stackoverflow.com/users/2583780", "pm_score": 0, "selected": false, "text": "<p>Apart from spaces, reserved keywords, and system functions in an identifier name, an identifier can also contain some characters that are not allowed in <a href=\"http://msdn.microsoft.com/en-us/library/ms175874(v=sql.105).ASPx\" rel=\"nofollow\">regular identifiers</a>, an it has to be separated with square brackets.</p>\n\n<p>You can find a detailed explanation and rules for regular and delimited identifiers in <a href=\"http://technet.microsoft.com/en-us/library/ms176027(v=sql.105).aspx\" rel=\"nofollow\">this article</a>.</p>\n\n<p>From the article:</p>\n\n<blockquote>\n <p>For example, delimited identifiers can contain spaces, any characters\n valid for regular identifiers, and any one of the following\n characters:</p>\n \n <p>tilde (~) hyphen, (-) exclamation point (!), left brace ({), percent (%),\n right brace (}), caret (^), apostrophe ('), ampersand (&amp;), period (.), left\n parenthesis ((), backslash (), right parenthesis ()), accent grave (`),</p>\n</blockquote>\n\n<p>Using two name qualifying convention may improve performance (avoid name resolutions) and avoid ambiguity in cases when you have e.g. the same table name in two or more schema. In that case SQL Server will search your object in dbo and if it isn't there it will stop searching. </p>\n\n<p>Also if you later want to use that object with the SCHEMABINDING option it doesn't allow unqualified object names.</p>\n\n<p>Hope this helps</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2147/" ]
In SQL Server, why is this: ``` [dbo].[table_name] ``` preferable to this: ``` dbo.table_name ``` And along those lines, why even list the dbo at all if there's only one schema?
It's just in case you have a keyword as a tablename like [user]
240,090
<p>We have a ASP.Net 2.0 web application up and running with the server in the Midwest (Eastern Standard Time). At this moment all of our customers are in the same time zone as the server. We are bringing another server online in Arizona (Mountain Standard Time).</p> <p>We are storing all our times in a SQL 2005 database via C# codebehind DateTime.UtcNow.</p> <p>During testing we encountered some time zone conversion issues. Our problem is that in the web browser our times are displaying the Mountain Standard Time instead of the time zone we are testing from which is Eastern Standard Time. </p> <p>When we enter new information it gets stored as UTC in the database, but when we go to view that info in the browser it is displaying the Mountain Standard Time. Below is the code which takes the UTC value from the database and displays it in the browser.</p> <pre><code>lblUpdatedDate.Text = Convert.ToDateTime(dr["UpdatedDate"]).ToLocalTime().ToString(); </code></pre> <p>The above code returns Mountain Standard Time where the server is, not Eastern Standard Time where the browser is running from. How do we get the time to display where the user is?</p>
[ { "answer_id": 240105, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>If you're using .NET 3.5 <em>and</em> you know the timezone that the user is in, <a href=\"http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx\" rel=\"nofollow noreferrer\">TimeZoneInfo</a> is your friend. If you're not using .NET 3.5 there are some P/Invoke samples around to get instances of <a href=\"http://msdn.microsoft.com/en-us/library/system.timezone.aspx\" rel=\"nofollow noreferrer\">TimeZone</a>, but it's worth avoiding that if you've got access to 3.5. (TimeZoneInfo has historical data etc, and is generally the preferred way to go.)</p>\n\n<p>Now ascertaining which timezone your users are in is a different problem - the simplest way of avoiding confusion is to give them options. (Getting the offset \"now\" only gives you limited information.)</p>\n" }, { "answer_id": 240109, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 2, "selected": false, "text": "<p>To local time will always on the server side convert to the physical location. You have a few options.</p>\n\n<ol>\n<li>Store the offset value from UTC to the Users, keep times in UTC</li>\n<li>Do the conversion client side via JS (Not elegant, nor appropriate, In my opinion)</li>\n<li>Look at some <a href=\"http://msdn.microsoft.com/en-us/library/ms973825.aspx\" rel=\"nofollow noreferrer\">MSDN recommendations</a> and the Timezone namespace</li>\n</ol>\n" }, { "answer_id": 240126, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I encountered something like this prior to using ASP.NET. Here was my general methodology.</p>\n\n<p>I sent JavaScript to do a document.write. The JavaScript determines the client's offset from GMT. So you can send a particular time and then let the JavaScript do a plus/minus on it.</p>\n" }, { "answer_id": 240130, "author": "TheCodeMonk", "author_id": 28956, "author_profile": "https://Stackoverflow.com/users/28956", "pm_score": 4, "selected": true, "text": "<p>I had the same issue. We sold our application to a user that was in a different time zone than the web server. We did not store any time information in UTC, but it was actually working correctly. Time displayed in the server's time zone was displaying exactly 3 hours behind. All we had to do was add a time zone drop down so they could select their time zone for the entire site (since the only users of the application would be in their time zone). We saved this setting and then inserted a function to take all datetime displays and convert from one time zone to the other using the TimeZoneInfo namespace. It works perfectly.</p>\n" }, { "answer_id": 240207, "author": "ScottCher", "author_id": 24179, "author_profile": "https://Stackoverflow.com/users/24179", "pm_score": 0, "selected": false, "text": "<p>We ran into the same or similar problem with remote clients calling to our database through webservices where the database and clients are in different timezones.</p>\n\n<p>We found it easiest to instruct the dataset to not care about timezones so the times aren't changed across timezone borders...</p>\n\n<p>We built a utility method (SetAllDateModes) that converts all date-time fields in the dataset by table - here's the business end (Foreach) and the call that sets the dateMode:</p>\n\n<pre><code>foreach (DataColumn dc in dt.Columns)\n{\n if (dc.DataType == typeof(DateTime))\n {\n dc.DateTimeMode = dateMode;\n }\n}\nSetAllDateModes(dt, DataSetDateTime.Unspecified);\n</code></pre>\n\n<p>DateSetDateTime.Unspecified does not include an offset so there is no conversion.</p>\n" }, { "answer_id": 240248, "author": "Clutch", "author_id": 25143, "author_profile": "https://Stackoverflow.com/users/25143", "pm_score": 0, "selected": false, "text": "<p>I thought the general idea was to not localize the date &amp; time until you present it the user. So unless a human is going to read it, it stays in UTC, GMT, CUT. One additional note use the Date/Time library so you don't have to worry to much about Daylight Savings time change problems.</p>\n" }, { "answer_id": 29891554, "author": "Minh Nguyen", "author_id": 2491685, "author_profile": "https://Stackoverflow.com/users/2491685", "pm_score": 1, "selected": false, "text": "<p>Just always store datetime as GMT format.</p>\n\n<p>There are 2 steps:</p>\n\n<p>Detect different timezone at client side using Javascript:</p>\n\n<pre><code>var dt = new Date();\nvar diffInMinutes = -dt.getTimezoneOffset();\n</code></pre>\n\n<p>Then at server side, C# code to convert server time to client time based on detected timezone offset above:</p>\n\n<pre><code>string queryStr = Request.QueryString[\"diffInMinutes\"];\nint diffInMinutes = 0;\nif (Int32.TryParse(queryStr, out diffInMinutes))\n{\n clientTime = serverTime.ToUniversalTime().AddMinutes(diffInMinutes);\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4096/" ]
We have a ASP.Net 2.0 web application up and running with the server in the Midwest (Eastern Standard Time). At this moment all of our customers are in the same time zone as the server. We are bringing another server online in Arizona (Mountain Standard Time). We are storing all our times in a SQL 2005 database via C# codebehind DateTime.UtcNow. During testing we encountered some time zone conversion issues. Our problem is that in the web browser our times are displaying the Mountain Standard Time instead of the time zone we are testing from which is Eastern Standard Time. When we enter new information it gets stored as UTC in the database, but when we go to view that info in the browser it is displaying the Mountain Standard Time. Below is the code which takes the UTC value from the database and displays it in the browser. ``` lblUpdatedDate.Text = Convert.ToDateTime(dr["UpdatedDate"]).ToLocalTime().ToString(); ``` The above code returns Mountain Standard Time where the server is, not Eastern Standard Time where the browser is running from. How do we get the time to display where the user is?
I had the same issue. We sold our application to a user that was in a different time zone than the web server. We did not store any time information in UTC, but it was actually working correctly. Time displayed in the server's time zone was displaying exactly 3 hours behind. All we had to do was add a time zone drop down so they could select their time zone for the entire site (since the only users of the application would be in their time zone). We saved this setting and then inserted a function to take all datetime displays and convert from one time zone to the other using the TimeZoneInfo namespace. It works perfectly.
240,098
<p>I'm using an HTML sanitizing whitelist code found here:<br> <a href="http://refactormycode.com/codes/333-sanitize-html" rel="nofollow noreferrer">http://refactormycode.com/codes/333-sanitize-html</a></p> <p>I needed to add the "font" tag as an additional tag to match, so I tried adding this condition after the <code>&lt;img</code> tag check </p> <pre><code>if (tagname.StartsWith("&lt;font")) { // detailed &lt;font&gt; tag checking // Non-escaped expression (for testing in a Regex editor app) // ^&lt;font(\s*size="\d{1}")?(\s*color="((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)")?(\s*face="(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)")?\s*?&gt;$ if (!IsMatch(tagname, @"&lt;font (\s*size=""\d{1}"")? (\s*color=""((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)"")? (\s*face=""(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)"")? \s*?&gt;")) { html = html.Remove(tag.Index, tag.Length); } } </code></pre> <p>Aside from the condition above, my code is almost identical to the code in the page I linked to. When I try to test this in C#, it throws an exception saying "<code>Not enough )'s</code>". I've counted the parenthesis several times and I've run the expression through a few online Javascript-based regex testers and none of them seem to tell me of any problems.</p> <p>Am I missing something in my Regex that is causing a parenthesis to escape? What do I need to do to fix this?</p> <p><strong>UPDATE</strong><br> After a lot of trial and error, I remembered that the <code>#</code> sign is a comment in regexes. The key to fixing this is to escape the <code>#</code> character. In case anyone else comes across the same problem, I've included my fix (just escaping the <code>#</code> sign) </p> <pre><code>if (tagname.StartsWith("&lt;font")) { // detailed &lt;font&gt; tag checking // Non-escaped expression (for testing in a Regex editor app) // ^&lt;font(\s*size="\d{1}")?(\s*color="((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)")?(\s*face="(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)")?\s*?&gt;$ if (!IsMatch(tagname, @"&lt;font (\s*size=""\d{1}"")? (\s*color=""((\#[0-9a-f]{6})|(\#[0-9a-f]{3})|red|green|blue|black|white)"")? (\s*face=""(Arial|Courier\sNew|Garamond|Georgia|Tahoma|Verdana)"")? \s*?&gt;")) { html = html.Remove(tag.Index, tag.Length); } } </code></pre>
[ { "answer_id": 240129, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 2, "selected": false, "text": "<p>I don't see anything obviously wrong with the regex. I would try isolating the problem by removing pieces of the regex until the problem goes away and then focus on the part that causes the issue.</p>\n" }, { "answer_id": 240136, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 1, "selected": false, "text": "<p>It works fine for me... what version of the .NET framework are you using, and what is the <em>exact</em> exception?</p>\n\n<p>Also - what does you <code>IsMatch</code> method look like? is this just a pass-thru to <code>Regex.IsMatch</code>?</p>\n\n<p>[update] The problem is that the OP's example code didn't show they are using the IgnorePatternWhitespace regex option; with this option it doesn't work; without this option (i.e. as presented) the code is fine.</p>\n" }, { "answer_id": 240211, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 4, "selected": true, "text": "<p>Your IsMatch Method is using the option <code>RegexOptions.IgnorePatternWhitespace</code>, that allows you to put comments inside the regular expressions, so you have to scape the # chatacter, otherwise it will be interpreted as a comment.</p>\n\n<pre><code>if (!IsMatch(tagname,@\"&lt;font(\\s*size=\"\"\\d{1}\"\")?\n (\\s*color=\"\"((\\#[0-9a-f]{6})|(\\#[0-9a-f]{3})|red|green|blue|black|white)\"\")?\n (\\s*face=\"\"(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)\"\")?\n \\s?&gt;\"))\n{\n html = html.Remove(tag.Index, tag.Length);\n}\n</code></pre>\n" }, { "answer_id": 240296, "author": "Dan Finucane", "author_id": 30026, "author_profile": "https://Stackoverflow.com/users/30026", "pm_score": 1, "selected": false, "text": "<p>Download Chris Sells <a href=\"http://www.sellsbrothers.com/tools/#regexd\" rel=\"nofollow noreferrer\">Regex Designer</a>. Its a great free tool for testing .NET regex's.</p>\n\n<p>I'm not sure this regex is going to do what you want because it depends on the order of the attributes matching what you have in the regex. If for example <code>face=\"Arial\"</code> preceeded <code>size=\"5\"</code> then <code>face=</code> wouldn't match.</p>\n\n<p>There are some escaping problems in your regex. You need to escape your <code>\"</code> with <code>\\</code> You need to escape your <code>#</code> with <code>\\</code> You need to use <code>\\s</code> in Courier New instead of just the space. You need to use the <code>RegexOptions.IgnorePatternWhitespace</code> and <code>RegexOptions.IgnoreCase options</code>.</p>\n\n<pre><code>&lt;font\n(\\s+size=\\\"\\d{1}\\\")?\n(\\s+color=\\\"((\\#[0-9a-f]{6})|(\\#[0-9a-f]{3})|red|green|blue|black|white)\\\")?\n(\\s+face=\\\"(Arial|Courier\\sNew|Garamond|Georgia|Tahoma|Verdana)\\\")?\n</code></pre>\n\n<p>The <code>#</code> characters are what was causing the exception with the somewhat misleading missing ) message.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
I'm using an HTML sanitizing whitelist code found here: <http://refactormycode.com/codes/333-sanitize-html> I needed to add the "font" tag as an additional tag to match, so I tried adding this condition after the `<img` tag check ``` if (tagname.StartsWith("<font")) { // detailed <font> tag checking // Non-escaped expression (for testing in a Regex editor app) // ^<font(\s*size="\d{1}")?(\s*color="((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)")?(\s*face="(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)")?\s*?>$ if (!IsMatch(tagname, @"<font (\s*size=""\d{1}"")? (\s*color=""((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)"")? (\s*face=""(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)"")? \s*?>")) { html = html.Remove(tag.Index, tag.Length); } } ``` Aside from the condition above, my code is almost identical to the code in the page I linked to. When I try to test this in C#, it throws an exception saying "`Not enough )'s`". I've counted the parenthesis several times and I've run the expression through a few online Javascript-based regex testers and none of them seem to tell me of any problems. Am I missing something in my Regex that is causing a parenthesis to escape? What do I need to do to fix this? **UPDATE** After a lot of trial and error, I remembered that the `#` sign is a comment in regexes. The key to fixing this is to escape the `#` character. In case anyone else comes across the same problem, I've included my fix (just escaping the `#` sign) ``` if (tagname.StartsWith("<font")) { // detailed <font> tag checking // Non-escaped expression (for testing in a Regex editor app) // ^<font(\s*size="\d{1}")?(\s*color="((#[0-9a-f]{6})|(#[0-9a-f]{3})|red|green|blue|black|white)")?(\s*face="(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)")?\s*?>$ if (!IsMatch(tagname, @"<font (\s*size=""\d{1}"")? (\s*color=""((\#[0-9a-f]{6})|(\#[0-9a-f]{3})|red|green|blue|black|white)"")? (\s*face=""(Arial|Courier\sNew|Garamond|Georgia|Tahoma|Verdana)"")? \s*?>")) { html = html.Remove(tag.Index, tag.Length); } } ```
Your IsMatch Method is using the option `RegexOptions.IgnorePatternWhitespace`, that allows you to put comments inside the regular expressions, so you have to scape the # chatacter, otherwise it will be interpreted as a comment. ``` if (!IsMatch(tagname,@"<font(\s*size=""\d{1}"")? (\s*color=""((\#[0-9a-f]{6})|(\#[0-9a-f]{3})|red|green|blue|black|white)"")? (\s*face=""(Arial|Courier New|Garamond|Georgia|Tahoma|Verdana)"")? \s?>")) { html = html.Remove(tag.Index, tag.Length); } ```
240,122
<p>Given the following java enum:</p> <pre><code>public enum AgeRange { A18TO23 { public String toString() { return "18 - 23"; } }, A24TO29 { public String toString() { return "24 - 29"; } }, A30TO35 { public String toString() { return "30 - 35"; } }, } </code></pre> <p>Is there any way to convert a string value of "18 - 23" to the corresponding enum value i.e. AgeRange.A18TO23 ?</p> <p>Thanks!</p>
[ { "answer_id": 240132, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>You could always create a map from string to value - do so statically so you only need to map it once, assuming that the returned string remains the same over time. There's nothing built-in as far as I'm aware.</p>\n" }, { "answer_id": 240148, "author": "John M", "author_id": 20734, "author_profile": "https://Stackoverflow.com/users/20734", "pm_score": 2, "selected": false, "text": "<pre><code>for (AgeRange ar: EnumSet.allOf(AgeRange)) {\n if (ar.toString().equals(inString)) {\n myAnswer = ar;\n break;\n }\n}\n</code></pre>\n\n<p>Or something like that? Just typed in, haven't run through a compiler. Forgive (comment on) typos...</p>\n\n<p>Or use logic like this to build a map once. Avoid iteration at runtime. Good idea, Jon.</p>\n" }, { "answer_id": 240165, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 2, "selected": false, "text": "<p>The class overrides \"toString()\" - so, to get the reverse operation, you need to override <code>valueOf()</code> to translate the output of <code>toString()</code> back to the Enum values.</p>\n\n<pre><code>public enum AgeRange {\n\n A18TO23 {\n public String toString() { \n return \"18 - 23\";\n }\n public AgeRange valueOf (Class enumClass, String name) {\n return A18T023\n }\n },\n\n .\n .\n .\n}\n</code></pre>\n\n<p>Buyer beware - uncompiled and untested...</p>\n\n<p>The mechanism for <code>toString()</code> and <code>valueOf()</code> is a documented part of the <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Enum.html\" rel=\"nofollow noreferrer\">API</a></p>\n" }, { "answer_id": 240175, "author": "sakana", "author_id": 28921, "author_profile": "https://Stackoverflow.com/users/28921", "pm_score": 6, "selected": true, "text": "<p>The best and simplest way to do it is like this:</p>\n\n<pre><code>public enum AgeRange {\n A18TO23 (\"18-23\"),\n A24TO29 (\"24-29\"),\n A30TO35(\"30-35\");\n\n private String value;\n\n AgeRange(String value){\n this.value = value;\n }\n\n public String toString(){\n return value;\n }\n\n public static AgeRange getByValue(String value){\n for (final AgeRange element : EnumSet.allOf(AgeRange.class)) {\n if (element.toString().equals(value)) {\n return element;\n }\n }\n return null;\n }\n}\n</code></pre>\n\n<p>Then you just need to invoke the <code>getByValue()</code> method with the <code>String</code> input in it.</p>\n" }, { "answer_id": 240214, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 0, "selected": false, "text": "<p>You could try something like the following?</p>\n\n<pre><code>static AgeRange fromString(String range) {\n for (AgeRange ageRange : values()) {\n if (range.equals(ageRange.toString())) {\n return ageRange;\n }\n }\n return null; \n}\n</code></pre>\n\n<p>Or, as others suggested, using a caching approach:</p>\n\n<pre><code>private static Map&lt;String, AgeRange&gt; map;\n\nprivate static synchronized void registerAgeRange(AgeRange ageRange) {\n if (map == null) {\n map = new HashMap&lt;String, AgeRange&gt;();\n }\n map.put(ageRange.toString(), ageRange);\n}\n\nAgeRange() {\n registerAgeRange(this);\n}\n\nstatic AgeRange fromString(String range) {\n return map.get(range);\n}\n</code></pre>\n" }, { "answer_id": 9781903, "author": "wsu_cic", "author_id": 1280111, "author_profile": "https://Stackoverflow.com/users/1280111", "pm_score": 2, "selected": false, "text": "<p>According to effective java (2nd ed) item 30, it can be (it is much faster than the loop)</p>\n\n<pre><code>public enum AgeRange {\n A18TO23(\"18-23\"),\n A24TO29(\"24-29\"),\n A30TO35(\"30-35\");\n\n private final String value;\n\n AgeRange(String value){\n this.value = value;\n }\n\n @Override public String toString(){\n return value;\n }\n\n private static final Map&lt;String, AgeRange&gt; stringToEnum =\n new HashMap&lt;String, AgeRange&gt;();\n\n static {\n for (AgeRange r : values()) {\n stringToEnum.put(r.toString(), r);\n }\n }\n\n public static AgeRange getByValue(String value){\n return stringToEnum.get(value);\n }\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27163/" ]
Given the following java enum: ``` public enum AgeRange { A18TO23 { public String toString() { return "18 - 23"; } }, A24TO29 { public String toString() { return "24 - 29"; } }, A30TO35 { public String toString() { return "30 - 35"; } }, } ``` Is there any way to convert a string value of "18 - 23" to the corresponding enum value i.e. AgeRange.A18TO23 ? Thanks!
The best and simplest way to do it is like this: ``` public enum AgeRange { A18TO23 ("18-23"), A24TO29 ("24-29"), A30TO35("30-35"); private String value; AgeRange(String value){ this.value = value; } public String toString(){ return value; } public static AgeRange getByValue(String value){ for (final AgeRange element : EnumSet.allOf(AgeRange.class)) { if (element.toString().equals(value)) { return element; } } return null; } } ``` Then you just need to invoke the `getByValue()` method with the `String` input in it.
240,125
<p>I have a form a user can enter their name, then it will add it to $message to be sent in an email.</p> <p>Is it better to use <code>$_POST</code> or <code>$_REQUEST</code>?</p> <p>Here is a snippet of using <code>$_REQUEST</code></p> <pre><code>$message.= "Name: ".$_REQUEST["fname"]." ".$_REQUEST["mname"]." ".$_REQUEST["lname"]."\n"; </code></pre>
[ { "answer_id": 240141, "author": "DylanJ", "author_id": 87, "author_profile": "https://Stackoverflow.com/users/87", "pm_score": 1, "selected": false, "text": "<p>doesn't matter which one you use. just make sure you use some form of security with forms.</p>\n" }, { "answer_id": 240150, "author": "Michael Madsen", "author_id": 27528, "author_profile": "https://Stackoverflow.com/users/27528", "pm_score": 4, "selected": true, "text": "<p>The answer is: It depends on how you want it to be used.</p>\n\n<p>If you're using <code>$_POST</code>, that means it can only come in via POST.\nIf you're using <code>$_REQUEST</code>, that means you accept POST, GET (and COOKIE, but it's mainly the first two we're interested in).</p>\n\n<p>For something like this, <code>$_POST</code> would probably be neater, but if you were making a search engine, allowing to set up a search URL would probably be a good idea. However, you might want to allow for a ton of special parameters to narrow down the search, and if that can take up a lot of URL space, you'll probably want to allow POSTDATA as well.</p>\n\n<p>As Dylan mentions, keep in mind that neither is a replacement for any kind of security.</p>\n" }, { "answer_id": 240159, "author": "Bobby Jack", "author_id": 5058, "author_profile": "https://Stackoverflow.com/users/5058", "pm_score": 0, "selected": false, "text": "<p>_POST if data is being updated somewhere (i.e. if the action has a side-effect), _REQUEST otherwise, <strong>and</strong> if you don't care whether or not the data comes via GET, POST, or any other method.</p>\n" }, { "answer_id": 240167, "author": "Mark Biek", "author_id": 305, "author_profile": "https://Stackoverflow.com/users/305", "pm_score": 3, "selected": false, "text": "<p>My approach used to be to use <strong>$_REQUEST</strong> for everything which I think is a big mistake. Lately, I've been trying to be more diligent about using GET only for read-requests &amp; POST only for write-requests.</p>\n\n<p>To that end, I think using <strong>$_GET</strong> for GET requests &amp; <strong>$_POST</strong> for POST requests makes my intent much more clear in my code.</p>\n" }, { "answer_id": 240169, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 0, "selected": false, "text": "<p>Unless you have a good reason to do otherwise (such as the search engine mentioned by Michael), it's probably better to use $_GET and $_POST for their respective methods instead of $_REQUEST, to avoid any ambiguity or confusion over possibly having the same argument name in the GET and POST data.</p>\n" }, { "answer_id": 240256, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 1, "selected": false, "text": "<p>I just listened to <a href=\"http://www.grc.com/securitynow.htm\" rel=\"nofollow noreferrer\">Security Now</a> episode #166 which was all about cross-site request forgery, and in it, Steve makes a good case for using <code>$_POST</code> for forms rather than <code>$_REQUEST</code>. (Indirectly, he doesn't talk about PHP itself, but does say that you shouldn't accept both GET and POST for forms.) The reason is that it's easy to use GET requests for CSRF attacks but not so easy to use POST. </p>\n\n<p>Using <code>$_POST</code> itself doesn't eliminate the possibility of CSRF attacks, but it does reduce it. Steve also suggests using a cryptographically strong pseudo-random hidden field in the request that will eliminate the possibility of \"blind\" requests.</p>\n" }, { "answer_id": 246468, "author": "AdamTheHutt", "author_id": 1103, "author_profile": "https://Stackoverflow.com/users/1103", "pm_score": 0, "selected": false, "text": "<p>The only time I use $_REQUEST is when I need to be able to support data from either $_POST or $_GET. </p>\n\n<p>For example, if I have a form that's supposed to modify a record, I might initially pass the record ID in the url as id=X. So when first loading the form, I could use $_GET['id'] to figure out what record we're trying to modify. </p>\n\n<p>However, when submitting the modify operation, the form should be POSTed, since it will be changing data and is not idempotent. In this case, the record ID would be accessible as $_POST['id'] when processing the form submission.</p>\n\n<p>But what happens if there's an error in the form submission and I need to reload the form with a helpful error message? In this case, the form generation code needs to figure out what record to use by looking at the POSTed id, which is not in the URL.</p>\n\n<p>In cases like this, I would use $_REQUEST['id'] in the form display logic, so that it could support either scenario. But for form processing, I would use $_POST['id'] for strict checking.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26130/" ]
I have a form a user can enter their name, then it will add it to $message to be sent in an email. Is it better to use `$_POST` or `$_REQUEST`? Here is a snippet of using `$_REQUEST` ``` $message.= "Name: ".$_REQUEST["fname"]." ".$_REQUEST["mname"]." ".$_REQUEST["lname"]."\n"; ```
The answer is: It depends on how you want it to be used. If you're using `$_POST`, that means it can only come in via POST. If you're using `$_REQUEST`, that means you accept POST, GET (and COOKIE, but it's mainly the first two we're interested in). For something like this, `$_POST` would probably be neater, but if you were making a search engine, allowing to set up a search URL would probably be a good idea. However, you might want to allow for a ton of special parameters to narrow down the search, and if that can take up a lot of URL space, you'll probably want to allow POSTDATA as well. As Dylan mentions, keep in mind that neither is a replacement for any kind of security.
240,163
<p>I am trying to upload files using the FileReference class. Files >2MB all work correctly but files &lt;2MB cause this error:</p> <blockquote> <p>"java.io.IOException: Corrupt form data: premature ending"</p> </blockquote> <p>On the server I am using the com.oreilly.servlet package to handle the request.</p> <p>I have used this package many times to successfully handle file uploads from flex, but for some reason, now I am having this problem.</p> <p>Here is the stack trace for some more info:</p> <pre><code>java.io.IOException: Corrupt form data: premature ending at com.oreilly.servlet.multipart.MultipartParser.&lt;init&gt;(MultipartParser.java:205) at com.oreilly.servlet.MultipartRequest.&lt;init&gt;(MultipartRequest.java:222) at com.oreilly.servlet.MultipartRequest.&lt;init&gt;(MultipartRequest.java:173) at com.mydomain.FileUploadServlet.doPost(FileUploadServlet.java:46) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.struts2.dispatcher.ActionContextCleanUp.doFilter(ActionContextCleanUp.java:99) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:414) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) </code></pre>
[ { "answer_id": 240213, "author": "asterite", "author_id": 20459, "author_profile": "https://Stackoverflow.com/users/20459", "pm_score": 3, "selected": true, "text": "<p>In WPF you have <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.dependencypropertydescriptor.addvaluechanged.aspx\" rel=\"nofollow noreferrer\">DependencyPropertyDescriptor.AddValueChanged</a>, but unfortunately in Silverlight there's no such thing. So the answer is no.</p>\n\n<p>Maybe if you explain what are you trying to do you can workaround the situation, or use bindings.</p>\n" }, { "answer_id": 258583, "author": "Daniel Crenna", "author_id": 18440, "author_profile": "https://Stackoverflow.com/users/18440", "pm_score": 1, "selected": false, "text": "<p>As Jon Galloway posted on another thread, you might be able to use something like WeakReference to wrap properties you're interested in and re-register them in your own class. This is WPF code but the concept doesn't rely on DependencyPropertyDescriptor.</p>\n\n<p><a href=\"http://agsmith.wordpress.com/2008/04/07/propertydescriptor-addvaluechanged-alternative/\" rel=\"nofollow noreferrer\">Article link</a></p>\n" }, { "answer_id": 660264, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Check out the following link. It showns how to get around the problem in silverlight where you don't have DependencyPropertyDescriptor.AddValueChanged</p>\n\n<p><a href=\"http://themechanicalbride.blogspot.com/2008/10/building-observable-model-in.html\" rel=\"nofollow noreferrer\">http://themechanicalbride.blogspot.com/2008/10/building-observable-model-in.html</a></p>\n" }, { "answer_id": 1835057, "author": "amazedsaint", "author_id": 45956, "author_profile": "https://Stackoverflow.com/users/45956", "pm_score": 3, "selected": false, "text": "<p>You can. Atleast I did. Still need to see the pros and Cons.</p>\n\n<pre><code> /// Listen for change of the dependency property\n public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)\n {\n\n //Bind to a depedency property\n Binding b = new Binding(propertyName) { Source = element };\n var prop = System.Windows.DependencyProperty.RegisterAttached(\n \"ListenAttached\"+propertyName,\n typeof(object),\n typeof(UserControl),\n new System.Windows.PropertyMetadata(callback));\n\n element.SetBinding(prop, b);\n }\n</code></pre>\n\n<p>And now, you can call RegisterForNotification to register for a change notification of a property of an element, like .</p>\n\n<pre><code>RegisterForNotification(\"Text\", this.txtMain,(d,e)=&gt;MessageBox.Show(\"Text changed\"));\n RegisterForNotification(\"Value\", this.sliderMain, (d, e) =&gt; MessageBox.Show(\"Value changed\"));\n</code></pre>\n\n<p>See my post here on the same <a href=\"http://amazedsaint.blogspot.com/2009/12/silverlight-listening-to-dependency.html\" rel=\"noreferrer\">http://amazedsaint.blogspot.com/2009/12/silverlight-listening-to-dependency.html</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240163", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22/" ]
I am trying to upload files using the FileReference class. Files >2MB all work correctly but files <2MB cause this error: > > "java.io.IOException: Corrupt form data: premature ending" > > > On the server I am using the com.oreilly.servlet package to handle the request. I have used this package many times to successfully handle file uploads from flex, but for some reason, now I am having this problem. Here is the stack trace for some more info: ``` java.io.IOException: Corrupt form data: premature ending at com.oreilly.servlet.multipart.MultipartParser.<init>(MultipartParser.java:205) at com.oreilly.servlet.MultipartRequest.<init>(MultipartRequest.java:222) at com.oreilly.servlet.MultipartRequest.<init>(MultipartRequest.java:173) at com.mydomain.FileUploadServlet.doPost(FileUploadServlet.java:46) at javax.servlet.http.HttpServlet.service(HttpServlet.java:710) at javax.servlet.http.HttpServlet.service(HttpServlet.java:803) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:269) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.struts2.dispatcher.ActionContextCleanUp.doFilter(ActionContextCleanUp.java:99) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) at org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:414) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:215) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:188) ```
In WPF you have [DependencyPropertyDescriptor.AddValueChanged](http://msdn.microsoft.com/en-us/library/system.componentmodel.dependencypropertydescriptor.addvaluechanged.aspx), but unfortunately in Silverlight there's no such thing. So the answer is no. Maybe if you explain what are you trying to do you can workaround the situation, or use bindings.
240,166
<p>I'm using the javax.mail system, and having problems with "Invalid Address" exceptions. Here's the basics of the code:</p> <pre><code> // Get system properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", m_sending_host); // Get session Session session = Session.getDefaultInstance(props, new Authenticator(){ @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(m_sending_user, m_sending_pass); } }); // Define message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(m_sending_from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(vcea.get(i).emailaddr)); message.setSubject( replaceEnvVars(subject) ); message.setText(replaceEnvVars(body)); // Send message try { Transport.send(message); } catch (Exception e){ Log.Error("Error sending e-mail to addr (%s): %s", vcea.get(i).emailaddr, e.getLocalizedMessage() ); } </code></pre> <p>The issue is that the above code does work, sometimes. But for some e-mail addresses that I know to be valid (because I can send to them via a standard e-mail client), the above code will throw an "Invalid Address" exception when trying to send.</p> <p>Any clues or hints would be greatly appreciated.</p> <p>--Update: problem with authentication.</p> <p>Ok, here's what I've discovered was going on. When receiving e-mail, the code above correctly sets up authentication and the Authenticator.getPasswordAuthentication() callback is actually invoked.</p> <p>Not so when sending e-mail. You have to do a bit more. Add this:</p> <pre><code> // Setup mail server props.put("mail.smtp.host", m_sending_host); props.put("mail.smtp.auth", "true"); </code></pre> <p>which will force the javax.mail API to do the login authentication. And then use an actual Transport instance instead of the static .send() method:</p> <pre><code> Transport t = session.getTransport(m_sending_protocol); t.connect(m_sending_user, m_sending_pass); </code></pre> <p>...</p> <pre><code> // Send message try { t.sendMessage(message, message.getAllRecipients()); } catch (Exception e){ </code></pre> <p>Without forcing the authentication, the mail server saw me as an unauthorized relay, and just shut me down. The difference between the addresses that "worked" and the addresses that didn't was that the ones that "worked" were all local to the mail server. Therefore, it simply accepted them. But for any non-local "relay" addresses, it would reject the message because my authentication information hadn't been presented by the javax.mail API when I thought it would have.</p> <p>Thanks for the clues to prompt me to look at the mail server side of things as well.</p>
[ { "answer_id": 240208, "author": "Agusti-N", "author_id": 24639, "author_profile": "https://Stackoverflow.com/users/24639", "pm_score": 0, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>String to=\"[email protected]\";\nString cc=\"[email protected],[email protected]\"; //The separator ',' works good\n\nmessage.setRecipients(Message.RecipientType.TO,new InternetAddress[] { \nnew InternetAddress(to) }); // This is only one mail\n\nInternetAddress[] addr = parseAddressList(cc); //Here add all the rest of the mails\nmessage.setRecipients(Message.RecipientType.CC,addr);\n</code></pre>\n\n<p>Sorry for my english. It's not good.</p>\n" }, { "answer_id": 240298, "author": "Alex B", "author_id": 6180, "author_profile": "https://Stackoverflow.com/users/6180", "pm_score": 2, "selected": false, "text": "<p>I would change the call to InternetAddress to use the \"strict\" interpretation and see if you get further errors on the addresses you are having trouble with.</p>\n\n<pre><code>message.addRecipient(Message.RecipientType.TO, \n new InternetAddress(vcea.get(i).emailaddr, true ));\n// ^^^^ turns on strict interpretation\n</code></pre>\n\n<p><a href=\"http://java.sun.com/products/javamail/javadocs/javax/mail/internet/InternetAddress.html#InternetAddress(java.lang.String,%20boolean)\" rel=\"nofollow noreferrer\">Javadoc for InternetAddress constructor</a></p>\n\n<p>If this fails, it will throw an <code>AddressException</code> which has a method called <code>getPos()</code> which returns the position of the failure (<a href=\"http://java.sun.com/products/javamail/javadocs/javax/mail/internet/AddressException.html#getPos()\" rel=\"nofollow noreferrer\">Javadoc</a>)</p>\n" }, { "answer_id": 240462, "author": "Steven M. Cherry", "author_id": 24193, "author_profile": "https://Stackoverflow.com/users/24193", "pm_score": 4, "selected": true, "text": "<p>--Update: problem with authentication.</p>\n\n<p>Ok, here's what I've discovered was going on. When receiving e-mail, the code above correctly sets up authentication and the Authenticator.getPasswordAuthentication() callback is actually invoked.</p>\n\n<p>Not so when sending e-mail. You have to do a bit more. Add this:</p>\n\n<pre><code>// Setup mail server\nprops.put(\"mail.smtp.host\", m_sending_host);\nprops.put(\"mail.smtp.auth\", \"true\");\n</code></pre>\n\n<p>which will force the javax.mail API to do the login authentication. And then use an actual Transport instance instead of the static .send() method:</p>\n\n<pre><code>Transport t = session.getTransport(m_sending_protocol);\nt.connect(m_sending_user, m_sending_pass);\n</code></pre>\n\n<p>...</p>\n\n<pre><code> // Send message\n try {\n t.sendMessage(message, message.getAllRecipients());\n } catch (Exception e){\n</code></pre>\n\n<p>Without forcing the authentication, the mail server saw me as an unauthorized relay, and just shut me down. The difference between the addresses that \"worked\" and the addresses that didn't was that the ones that \"worked\" were all local to the mail server. Therefore, it simply accepted them. But for any non-local \"relay\" addresses, it would reject the message because my authentication information hadn't been presented by the javax.mail API when I thought it would have.</p>\n\n<p>Thanks for the clues to prompt me to look at the mail server side of things as well.</p>\n" }, { "answer_id": 241460, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>This seems to me like a problem that happened at my work.\nIf the code you are showing is being concurrent, then using directly System.getProperties\ncould be a problem, because the host value you put on them can be overwritten by next request, while still keeping the user and password from the overwritten host.</p>\n\n<p>In our case, we solved that using a clone of the System.getProperties() hashtable.</p>\n\n<p>Hope that helps (this problem was really hard to track).</p>\n" }, { "answer_id": 6871251, "author": "Alex Cheptsov", "author_id": 869099, "author_profile": "https://Stackoverflow.com/users/869099", "pm_score": 0, "selected": false, "text": "<p>A good hint for those using the ssl encryption in the smtp configuration, you should enable it by specifying the property <code>mail.smtp.ssl.enable</code>, as shown below: </p>\n\n<pre><code>props.put(\"mail.smtp.ssl.enable\", \"true\");\n</code></pre>\n\n<p>Otherwise it can lead to similar problems as described above.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24193/" ]
I'm using the javax.mail system, and having problems with "Invalid Address" exceptions. Here's the basics of the code: ``` // Get system properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", m_sending_host); // Get session Session session = Session.getDefaultInstance(props, new Authenticator(){ @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(m_sending_user, m_sending_pass); } }); // Define message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(m_sending_from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(vcea.get(i).emailaddr)); message.setSubject( replaceEnvVars(subject) ); message.setText(replaceEnvVars(body)); // Send message try { Transport.send(message); } catch (Exception e){ Log.Error("Error sending e-mail to addr (%s): %s", vcea.get(i).emailaddr, e.getLocalizedMessage() ); } ``` The issue is that the above code does work, sometimes. But for some e-mail addresses that I know to be valid (because I can send to them via a standard e-mail client), the above code will throw an "Invalid Address" exception when trying to send. Any clues or hints would be greatly appreciated. --Update: problem with authentication. Ok, here's what I've discovered was going on. When receiving e-mail, the code above correctly sets up authentication and the Authenticator.getPasswordAuthentication() callback is actually invoked. Not so when sending e-mail. You have to do a bit more. Add this: ``` // Setup mail server props.put("mail.smtp.host", m_sending_host); props.put("mail.smtp.auth", "true"); ``` which will force the javax.mail API to do the login authentication. And then use an actual Transport instance instead of the static .send() method: ``` Transport t = session.getTransport(m_sending_protocol); t.connect(m_sending_user, m_sending_pass); ``` ... ``` // Send message try { t.sendMessage(message, message.getAllRecipients()); } catch (Exception e){ ``` Without forcing the authentication, the mail server saw me as an unauthorized relay, and just shut me down. The difference between the addresses that "worked" and the addresses that didn't was that the ones that "worked" were all local to the mail server. Therefore, it simply accepted them. But for any non-local "relay" addresses, it would reject the message because my authentication information hadn't been presented by the javax.mail API when I thought it would have. Thanks for the clues to prompt me to look at the mail server side of things as well.
--Update: problem with authentication. Ok, here's what I've discovered was going on. When receiving e-mail, the code above correctly sets up authentication and the Authenticator.getPasswordAuthentication() callback is actually invoked. Not so when sending e-mail. You have to do a bit more. Add this: ``` // Setup mail server props.put("mail.smtp.host", m_sending_host); props.put("mail.smtp.auth", "true"); ``` which will force the javax.mail API to do the login authentication. And then use an actual Transport instance instead of the static .send() method: ``` Transport t = session.getTransport(m_sending_protocol); t.connect(m_sending_user, m_sending_pass); ``` ... ``` // Send message try { t.sendMessage(message, message.getAllRecipients()); } catch (Exception e){ ``` Without forcing the authentication, the mail server saw me as an unauthorized relay, and just shut me down. The difference between the addresses that "worked" and the addresses that didn't was that the ones that "worked" were all local to the mail server. Therefore, it simply accepted them. But for any non-local "relay" addresses, it would reject the message because my authentication information hadn't been presented by the javax.mail API when I thought it would have. Thanks for the clues to prompt me to look at the mail server side of things as well.
240,171
<p>How can I launch an application using C#?</p> <p>Requirements: Must work on <a href="http://en.wikipedia.org/wiki/Windows_XP" rel="noreferrer">Windows&nbsp;XP</a> and <a href="http://en.wikipedia.org/wiki/Windows_Vista" rel="noreferrer">Windows&nbsp;Vista</a>.</p> <p>I have seen a sample from DinnerNow.net sampler that only works in Windows&nbsp;Vista.</p>
[ { "answer_id": 240189, "author": "Mark S. Rasmussen", "author_id": 12469, "author_profile": "https://Stackoverflow.com/users/12469", "pm_score": 6, "selected": false, "text": "<pre><code>System.Diagnostics.Process.Start(\"PathToExe.exe\");\n</code></pre>\n" }, { "answer_id": 240191, "author": "Igal Tabachnik", "author_id": 8205, "author_profile": "https://Stackoverflow.com/users/8205", "pm_score": 9, "selected": true, "text": "<p>Use <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx\" rel=\"noreferrer\"><code>System.Diagnostics.Process.Start()</code></a> method.</p>\n\n<p>Check out <a href=\"http://www.codeproject.com/KB/cs/start_an_external_app.aspx\" rel=\"noreferrer\">this article</a> on how to use it.</p>\n\n<pre><code>Process.Start(\"notepad\", \"readme.txt\");\n\nstring winpath = Environment.GetEnvironmentVariable(\"windir\");\nstring path = System.IO.Path.GetDirectoryName(\n System.Windows.Forms.Application.ExecutablePath);\n\nProcess.Start(winpath + @\"\\Microsoft.NET\\Framework\\v1.0.3705\\Installutil.exe\",\npath + \"\\\\MyService.exe\");\n</code></pre>\n" }, { "answer_id": 240481, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 3, "selected": false, "text": "<p>Additionally you will want to use the Environment Variables for your paths if at all possible: <a href=\"http://en.wikipedia.org/wiki/Environment_variable#Default_Values_on_Microsoft_Windows\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Environment_variable#Default_Values_on_Microsoft_Windows</a></p>\n\n<p>E.G.</p>\n\n<ul>\n<li>%WINDIR% = Windows Directory</li>\n<li>%APPDATA% = Application Data -\nVaries alot between Vista and XP.</li>\n</ul>\n\n<p>There are many more check out the link for a longer list.</p>\n" }, { "answer_id": 240610, "author": "sfuqua", "author_id": 30384, "author_profile": "https://Stackoverflow.com/users/30384", "pm_score": 8, "selected": false, "text": "<p>Here's a snippet of helpful code:</p>\n\n<pre><code>using System.Diagnostics;\n\n// Prepare the process to run\nProcessStartInfo start = new ProcessStartInfo();\n// Enter in the command line arguments, everything you would enter after the executable name itself\nstart.Arguments = arguments; \n// Enter the executable to run, including the complete path\nstart.FileName = ExeName;\n// Do you want to show a console window?\nstart.WindowStyle = ProcessWindowStyle.Hidden;\nstart.CreateNoWindow = true;\nint exitCode;\n\n\n// Run the external process &amp; wait for it to finish\nusing (Process proc = Process.Start(start))\n{\n proc.WaitForExit();\n\n // Retrieve the app's exit code\n exitCode = proc.ExitCode;\n}\n</code></pre>\n\n<p>There is much more you can do with these objects, you should read the documentation: <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.processstartinfo.aspx\" rel=\"noreferrer\">ProcessStartInfo</a>, <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx\" rel=\"noreferrer\">Process</a>.</p>\n" }, { "answer_id": 1558487, "author": "Adam Kane", "author_id": 90837, "author_profile": "https://Stackoverflow.com/users/90837", "pm_score": 5, "selected": false, "text": "<pre><code>System.Diagnostics.Process.Start( @\"C:\\Windows\\System32\\Notepad.exe\" );\n</code></pre>\n" }, { "answer_id": 24025158, "author": "NDB", "author_id": 3704760, "author_profile": "https://Stackoverflow.com/users/3704760", "pm_score": 4, "selected": false, "text": "<p>If you have problems using System.Diagnostics like I had, use the following simple code that will work without it:</p>\n<pre><code>using System.Diagnostics;\n\nProcess notePad = new Process();\nnotePad.StartInfo.FileName = &quot;notepad.exe&quot;;\nnotePad.StartInfo.Arguments = &quot;mytextfile.txt&quot;;\nnotePad.Start();\n</code></pre>\n" }, { "answer_id": 32240290, "author": "Deadlock", "author_id": 2915792, "author_profile": "https://Stackoverflow.com/users/2915792", "pm_score": 2, "selected": false, "text": "<p>Use <strong>Process.Start</strong> to start a process. </p>\n\n<pre><code>using System.Diagnostics;\nclass Program\n{\n static void Main()\n {\n //\n // your code\n //\n Process.Start(\"C:\\\\process.exe\");\n }\n} \n</code></pre>\n" }, { "answer_id": 36636828, "author": "Amin Mohamed", "author_id": 6206889, "author_profile": "https://Stackoverflow.com/users/6206889", "pm_score": 3, "selected": false, "text": "<p>Just put your file.exe in the \\bin\\Debug folder and use:</p>\n\n<pre><code>Process.Start(\"File.exe\");\n</code></pre>\n" }, { "answer_id": 37685792, "author": "user6436606", "author_id": 6436606, "author_profile": "https://Stackoverflow.com/users/6436606", "pm_score": 1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>Process.Start(\"Location Of File.exe\");\n</code></pre>\n\n<p>(Make sure you use the System.Diagnostics library)</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240171", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5147/" ]
How can I launch an application using C#? Requirements: Must work on [Windows XP](http://en.wikipedia.org/wiki/Windows_XP) and [Windows Vista](http://en.wikipedia.org/wiki/Windows_Vista). I have seen a sample from DinnerNow.net sampler that only works in Windows Vista.
Use [`System.Diagnostics.Process.Start()`](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx) method. Check out [this article](http://www.codeproject.com/KB/cs/start_an_external_app.aspx) on how to use it. ``` Process.Start("notepad", "readme.txt"); string winpath = Environment.GetEnvironmentVariable("windir"); string path = System.IO.Path.GetDirectoryName( System.Windows.Forms.Application.ExecutablePath); Process.Start(winpath + @"\Microsoft.NET\Framework\v1.0.3705\Installutil.exe", path + "\\MyService.exe"); ```
240,178
<p>I created a list of lists:</p> <pre><code>xs = [[1] * 4] * 3 # xs == [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]] </code></pre> <p>Then, I changed one of the innermost values:</p> <pre><code>xs[0][0] = 5 # xs == [[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]] </code></pre> <p>Why did every first element of each sublist change to <code>5</code>?</p>
[ { "answer_id": 240202, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 6, "selected": false, "text": "<pre><code>[[1] * 4] * 3\n</code></pre>\n\n<p>or even:</p>\n\n<pre><code>[[1, 1, 1, 1]] * 3\n</code></pre>\n\n<p>Creates a list that references the internal <code>[1,1,1,1]</code> 3 times - not three copies of the inner list, so any time you modify the list (in any position), you'll see the change three times.</p>\n\n<p>It's the same as this example:</p>\n\n<pre><code>&gt;&gt;&gt; inner = [1,1,1,1]\n&gt;&gt;&gt; outer = [inner]*3\n&gt;&gt;&gt; outer\n[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]\n&gt;&gt;&gt; inner[0] = 5\n&gt;&gt;&gt; outer\n[[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]]\n</code></pre>\n\n<p>where it's probably a little less surprising.</p>\n" }, { "answer_id": 240205, "author": "CAdaker", "author_id": 30579, "author_profile": "https://Stackoverflow.com/users/30579", "pm_score": 11, "selected": true, "text": "<p>When you write <code>[x]*3</code> you get, essentially, the list <code>[x, x, x]</code>. That is, a list with 3 references to the same <code>x</code>. When you then modify this single <code>x</code> it is visible via all three references to it:</p>\n<pre><code>x = [1] * 4\nxs = [x] * 3\nprint(f&quot;id(x): {id(x)}&quot;)\n# id(x): 140560897920048\nprint(\n f&quot;id(xs[0]): {id(xs[0])}\\n&quot;\n f&quot;id(xs[1]): {id(xs[1])}\\n&quot;\n f&quot;id(xs[2]): {id(xs[2])}&quot;\n)\n# id(xs[0]): 140560897920048\n# id(xs[1]): 140560897920048\n# id(xs[2]): 140560897920048\n\nx[0] = 42\nprint(f&quot;x: {x}&quot;)\n# x: [42, 1, 1, 1]\nprint(f&quot;xs: {xs}&quot;)\n# xs: [[42, 1, 1, 1], [42, 1, 1, 1], [42, 1, 1, 1]]\n</code></pre>\n<p>To fix it, you need to make sure that you create a new list at each position. One way to do it is</p>\n<pre><code>[[1]*4 for _ in range(3)]\n</code></pre>\n<p>which will reevaluate <code>[1]*4</code> each time instead of evaluating it once and making 3 references to 1 list.</p>\n<hr />\n<p>You might wonder why <code>*</code> can't make independent objects the way the list comprehension does. That's because the multiplication operator <code>*</code> operates on objects, without seeing expressions. When you use <code>*</code> to multiply <code>[[1] * 4]</code> by 3, <code>*</code> only sees the 1-element list <code>[[1] * 4]</code> evaluates to, not the <code>[[1] * 4</code> expression text. <code>*</code> has no idea how to make copies of that element, no idea how to reevaluate <code>[[1] * 4]</code>, and no idea you even want copies, and in general, there might not even be a way to copy the element.</p>\n<p>The only option <code>*</code> has is to make new references to the existing sublist instead of trying to make new sublists. Anything else would be inconsistent or require major redesigning of fundamental language design decisions.</p>\n<p>In contrast, a list comprehension reevaluates the element expression on every iteration. <code>[[1] * 4 for n in range(3)]</code> reevaluates <code>[1] * 4</code> every time for the same reason <code>[x**2 for x in range(3)]</code> reevaluates <code>x**2</code> every time. Every evaluation of <code>[1] * 4</code> generates a new list, so the list comprehension does what you wanted.</p>\n<p>Incidentally, <code>[1] * 4</code> also doesn't copy the elements of <code>[1]</code>, but that doesn't matter, since integers are immutable. You can't do something like <code>1.value = 2</code> and turn a 1 into a 2.</p>\n" }, { "answer_id": 240215, "author": "PierreBdR", "author_id": 7136, "author_profile": "https://Stackoverflow.com/users/7136", "pm_score": 6, "selected": false, "text": "<p>Actually, this is exactly what you would expect. Let's decompose what is happening here:</p>\n<p>You write</p>\n<pre><code>lst = [[1] * 4] * 3\n</code></pre>\n<p>This is equivalent to:</p>\n<pre><code>lst1 = [1]*4\nlst = [lst1]*3\n</code></pre>\n<p>This means <code>lst</code> is a list with 3 elements all pointing to <code>lst1</code>. This means the two following lines are equivalent:</p>\n<pre><code>lst[0][0] = 5\nlst1[0] = 5\n</code></pre>\n<p>As <code>lst[0]</code> is nothing but <code>lst1</code>.</p>\n<p>To obtain the desired behavior, you can use a list comprehension:</p>\n<pre><code>lst = [ [1]*4 for n in range(3) ]\n</code></pre>\n<p>In this case, the expression is re-evaluated for each <code>n</code>, leading to a different list.</p>\n" }, { "answer_id": 18454568, "author": "nadrimajstor", "author_id": 1952047, "author_profile": "https://Stackoverflow.com/users/1952047", "pm_score": 7, "selected": false, "text": "<pre><code>size = 3\nmatrix_surprise = [[0] * size] * size\nmatrix = [[0]*size for _ in range(size)]\n</code></pre>\n<p><a href=\"http://pythontutor.com/visualize.html#code=size%20%3D%203%0Amatrix_surprise%20%3D%20%5B%5B0%5D%20*%20size%5D%20*%20size%0Amatrix%20%3D%20%5B%5B0%5D*size%20for%20_%20in%20range%28size%29%5D&amp;cumulative=false&amp;curInstr=9&amp;heapPrimitives=false&amp;mode=display&amp;origin=opt-frontend.js&amp;py=3&amp;rawInputLstJSON=%5B%5D&amp;textReferences=false\" rel=\"noreferrer\">Live visualization</a> using Python Tutor:</p>\n<p><a href=\"https://i.stack.imgur.com/AE8xf.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/AE8xf.png\" alt=\"Frames and Objects\" /></a></p>\n" }, { "answer_id": 30759580, "author": "bagrat", "author_id": 3264192, "author_profile": "https://Stackoverflow.com/users/3264192", "pm_score": 3, "selected": false, "text": "<p>Let's rewrite your code in the following way:</p>\n<pre><code>x = 1\ny = [x]\nz = y * 4\n\nmy_list = [z] * 3\n</code></pre>\n<p>Then having this, run the following code to make everything more clear. What the code does is basically print the <a href=\"https://docs.python.org/3/library/functions.html#id\" rel=\"nofollow noreferrer\"><code>id</code></a>s of the obtained objects, which</p>\n<blockquote>\n<p>Return[s] the “identity” of an object</p>\n</blockquote>\n<p>and will help us identify them and analyse what happens:</p>\n<pre><code>print(&quot;my_list:&quot;)\nfor i, sub_list in enumerate(my_list):\n print(&quot;\\t[{}]: {}&quot;.format(i, id(sub_list)))\n for j, elem in enumerate(sub_list):\n print(&quot;\\t\\t[{}]: {}&quot;.format(j, id(elem)))\n</code></pre>\n<p>And you will get the following output:</p>\n<pre><code>x: 1\ny: [1]\nz: [1, 1, 1, 1]\nmy_list:\n [0]: 4300763792\n [0]: 4298171528\n [1]: 4298171528\n [2]: 4298171528\n [3]: 4298171528\n [1]: 4300763792\n [0]: 4298171528\n [1]: 4298171528\n [2]: 4298171528\n [3]: 4298171528\n [2]: 4300763792\n [0]: 4298171528\n [1]: 4298171528\n [2]: 4298171528\n [3]: 4298171528\n</code></pre>\n<hr />\n<p>So now let's go step-by-step. You have <code>x</code> which is <code>1</code>, and a single element list <code>y</code> containing <code>x</code>. Your first step is <code>y * 4</code> which will get you a new list <code>z</code>, which is basically <code>[x, x, x, x]</code>, i.e. it creates a new list which will have 4 elements, which are references to the initial <code>x</code> object. The next step is pretty similar. You basically do <code>z * 3</code>, which is <code>[[x, x, x, x]] * 3</code> and returns <code>[[x, x, x, x], [x, x, x, x], [x, x, x, x]]</code>, for the same reason as for the first step.</p>\n" }, { "answer_id": 30898048, "author": "Mazdak", "author_id": 2867928, "author_profile": "https://Stackoverflow.com/users/2867928", "pm_score": 3, "selected": false, "text": "<p>Alongside the accepted answer that explained the problem correctly, instead of creating a list with duplicated elements using following code:</p>\n<pre><code>[[1]*4 for _ in range(3)]\n</code></pre>\n<p>Also, you can use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.repeat\" rel=\"nofollow noreferrer\"><code>itertools.repeat()</code></a> to create an iterator object of repeated elements:</p>\n<pre><code>&gt;&gt;&gt; a = list(repeat(1,4))\n[1, 1, 1, 1]\n&gt;&gt;&gt; a[0] = 5\n&gt;&gt;&gt; a\n[5, 1, 1, 1]\n</code></pre>\n<p>P.S. If you're using NumPy and you only want to create an array of ones or zeroes you can use <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.ones.html\" rel=\"nofollow noreferrer\"><code>np.ones</code></a> and <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.zeros.html\" rel=\"nofollow noreferrer\"><code>np.zeros</code></a> and/or for other numbers use <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.repeat.html\" rel=\"nofollow noreferrer\"><code>np.repeat</code></a>:</p>\n<pre><code>&gt;&gt;&gt; import numpy as np\n&gt;&gt;&gt; np.ones(4)\narray([1., 1., 1., 1.])\n&gt;&gt;&gt; np.ones((4, 2))\narray([[1., 1.],\n [1., 1.],\n [1., 1.],\n [1., 1.]])\n&gt;&gt;&gt; np.zeros((4, 2))\narray([[0., 0.],\n [0., 0.],\n [0., 0.],\n [0., 0.]])\n&gt;&gt;&gt; np.repeat([7], 10)\narray([7, 7, 7, 7, 7, 7, 7, 7, 7, 7])\n</code></pre>\n" }, { "answer_id": 36452923, "author": "Zbyněk Winkler", "author_id": 3185929, "author_profile": "https://Stackoverflow.com/users/3185929", "pm_score": 3, "selected": false, "text": "<p>Python containers contain references to other objects. See this example:</p>\n\n<pre><code>&gt;&gt;&gt; a = []\n&gt;&gt;&gt; b = [a]\n&gt;&gt;&gt; b\n[[]]\n&gt;&gt;&gt; a.append(1)\n&gt;&gt;&gt; b\n[[1]]\n</code></pre>\n\n<p>In this <code>b</code> is a list that contains one item that is a reference to list <code>a</code>. The list <code>a</code> is mutable.</p>\n\n<p>The multiplication of a list by an integer is equivalent to adding the list to itself multiple times (see <a href=\"https://docs.python.org/3/library/stdtypes.html#typesseq-common\" rel=\"noreferrer\">common sequence operations</a>). So continuing with the example:</p>\n\n<pre><code>&gt;&gt;&gt; c = b + b\n&gt;&gt;&gt; c\n[[1], [1]]\n&gt;&gt;&gt;\n&gt;&gt;&gt; a[0] = 2\n&gt;&gt;&gt; c\n[[2], [2]]\n</code></pre>\n\n<p>We can see that the list <code>c</code> now contains two references to list <code>a</code> which is equivalent to <code>c = b * 2</code>.</p>\n\n<p>Python FAQ also contains explanation of this behavior: <a href=\"https://docs.python.org/3/faq/programming.html#faq-multidimensional-list\" rel=\"noreferrer\">How do I create a multidimensional list?</a></p>\n" }, { "answer_id": 36823796, "author": "awulll", "author_id": 1428655, "author_profile": "https://Stackoverflow.com/users/1428655", "pm_score": 2, "selected": false, "text": "<p>Everyone is explaining what is happening. I'll suggest one way to solve it:</p>\n<pre><code>my_list = [[1 for i in range(4)] for j in range(3)]\n\nmy_list[0][0] = 5\nprint(my_list)\n</code></pre>\n<p>And then you get:</p>\n<pre><code>[[5, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]\n</code></pre>\n" }, { "answer_id": 37804636, "author": "Neeraj Komuravalli", "author_id": 5801215, "author_profile": "https://Stackoverflow.com/users/5801215", "pm_score": 2, "selected": false, "text": "<p>In simple words this is happening because in python everything works <strong>by reference</strong>, so when you create a list of list that way you basically end up with such problems.</p>\n\n<p>To solve your issue you can do either one of them:\n1. Use numpy array <a href=\"http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.empty.html\" rel=\"nofollow noreferrer\">documentation for numpy.empty</a>\n2. Append the list as you get to a list.\n3. You can also use dictionary if you want </p>\n" }, { "answer_id": 38397772, "author": "Anand Tripathi", "author_id": 5230702, "author_profile": "https://Stackoverflow.com/users/5230702", "pm_score": 2, "selected": false, "text": "<p>By using the inbuilt list function you can do like this</p>\n\n<pre><code>a\nout:[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]\n#Displaying the list\n\na.remove(a[0])\nout:[[1, 1, 1, 1], [1, 1, 1, 1]]\n# Removed the first element of the list in which you want altered number\n\na.append([5,1,1,1])\nout:[[1, 1, 1, 1], [1, 1, 1, 1], [5, 1, 1, 1]]\n# append the element in the list but the appended element as you can see is appended in last but you want that in starting\n\na.reverse()\nout:[[5, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]\n#So at last reverse the whole list to get the desired list\n</code></pre>\n" }, { "answer_id": 38866487, "author": "Adil Abbasi", "author_id": 2285848, "author_profile": "https://Stackoverflow.com/users/2285848", "pm_score": 2, "selected": false, "text": "<p>Trying to explain it more descriptively,</p>\n\n<p>Operation 1:</p>\n\n<pre><code>x = [[0, 0], [0, 0]]\nprint(type(x)) # &lt;class 'list'&gt;\nprint(x) # [[0, 0], [0, 0]]\n\nx[0][0] = 1\nprint(x) # [[1, 0], [0, 0]]\n</code></pre>\n\n<p>Operation 2:</p>\n\n<pre><code>y = [[0] * 2] * 2\nprint(type(y)) # &lt;class 'list'&gt;\nprint(y) # [[0, 0], [0, 0]]\n\ny[0][0] = 1\nprint(y) # [[1, 0], [1, 0]]\n</code></pre>\n\n<p>Noticed why doesn't modifying the first element of the first list didn't modify the second element of each list? That's because <code>[0] * 2</code> really is a list of two numbers, and a reference to 0 cannot be modified.</p>\n\n<p>If you want to create clone copies, try Operation 3:</p>\n\n<pre><code>import copy\ny = [0] * 2 \nprint(y) # [0, 0]\n\ny = [y, copy.deepcopy(y)] \nprint(y) # [[0, 0], [0, 0]]\n\ny[0][0] = 1\nprint(y) # [[1, 0], [0, 0]]\n</code></pre>\n\n<p>another interesting way to create clone copies, Operation 4:</p>\n\n<pre><code>import copy\ny = [0] * 2\nprint(y) # [0, 0]\n\ny = [copy.deepcopy(y) for num in range(1,5)]\nprint(y) # [[0, 0], [0, 0], [0, 0], [0, 0]]\n\ny[0][0] = 5\nprint(y) # [[5, 0], [0, 0], [0, 0], [0, 0]]\n</code></pre>\n" }, { "answer_id": 43246520, "author": "jerrymouse", "author_id": 842837, "author_profile": "https://Stackoverflow.com/users/842837", "pm_score": 4, "selected": false, "text": "<p><code>my_list = [[1]*4] * 3</code> creates one list object <code>[1,1,1,1]</code> in memory and copies its reference 3 times over. This is equivalent to <code>obj = [1,1,1,1]; my_list = [obj]*3</code>. Any modification to <code>obj</code> will be reflected at three places, wherever <code>obj</code> is referenced in the list.\nThe right statement would be:</p>\n<pre><code>my_list = [[1]*4 for _ in range(3)]\n</code></pre>\n<p>or</p>\n<pre><code>my_list = [[1 for __ in range(4)] for _ in range(3)]\n</code></pre>\n<p><strong>Important thing to note here</strong> is that the <code>*</code> operator is <em>mostly</em> used to create a <strong>list of literals</strong>. Although <code>1</code> is immutable, <code>obj = [1]*4</code> will still create a list of <code>1</code> repeated 4 times over to form <code>[1,1,1,1]</code>. But if any reference to an immutable object is made, the object is overwritten with a new one.</p>\n<p>This means if we do <code>obj[1] = 42</code>, then <code>obj</code> will become <code>[1,42,1,1]</code> <strong>not</strong> <strike><code>[42,42,42,42]</code></strike> as some may assume. This can also be verified:</p>\n<pre><code>&gt;&gt;&gt; my_list = [1]*4\n&gt;&gt;&gt; my_list\n[1, 1, 1, 1]\n\n&gt;&gt;&gt; id(my_list[0])\n4522139440\n&gt;&gt;&gt; id(my_list[1]) # Same as my_list[0]\n4522139440\n</code></pre>\n<hr />\n<pre><code>&gt;&gt;&gt; my_list[1] = 42 # Since my_list[1] is immutable, this operation overwrites my_list[1] with a new object changing its id.\n&gt;&gt;&gt; my_list\n[1, 42, 1, 1]\n\n&gt;&gt;&gt; id(my_list[0])\n4522139440\n&gt;&gt;&gt; id(my_list[1]) # id changed\n4522140752\n&gt;&gt;&gt; id(my_list[2]) # id still same as my_list[0], still referring to value `1`.\n4522139440\n</code></pre>\n" }, { "answer_id": 57426328, "author": "ouxiaogu", "author_id": 1819824, "author_profile": "https://Stackoverflow.com/users/1819824", "pm_score": 2, "selected": false, "text": "<p>@spelchekr from <a href=\"https://stackoverflow.com/questions/6688223/python-list-multiplication-3-makes-3-lists-which-mirror-each-other-when\">Python list multiplication: [[...]]*3 makes 3 lists which mirror each other when modified</a> and I had the same question about\n&quot;Why does only the outer <code>*3</code> create more references while the inner one doesn't? Why isn't it all 1s?&quot;</p>\n<pre class=\"lang-py prettyprint-override\"><code>li = [0] * 3\nprint([id(v) for v in li]) # [140724141863728, 140724141863728, 140724141863728]\nli[0] = 1\nprint([id(v) for v in li]) # [140724141863760, 140724141863728, 140724141863728]\nprint(id(0)) # 140724141863728\nprint(id(1)) # 140724141863760\nprint(li) # [1, 0, 0]\n\nma = [[0]*3] * 3 # mainly discuss inner &amp; outer *3 here\nprint([id(li) for li in ma]) # [1987013355080, 1987013355080, 1987013355080]\nma[0][0] = 1\nprint([id(li) for li in ma]) # [1987013355080, 1987013355080, 1987013355080]\nprint(ma) # [[1, 0, 0], [1, 0, 0], [1, 0, 0]]\n</code></pre>\n<p>Here is my explanation after trying the code above:</p>\n<ul>\n<li>The inner <code>*3</code> also creates references, but its references are immutable, something like <code>[&amp;0, &amp;0, &amp;0]</code>, then when you change <code>li[0]</code>, you can't change any underlying reference of const int <code>0</code>, so you can just change the reference address into the new one <code>&amp;1</code>;</li>\n<li>while <code>ma = [&amp;li, &amp;li, &amp;li]</code> and <code>li</code> is mutable, so when you call <code>ma[0][0] = 1</code>, <code>ma[0][0]</code> is equal to <code>&amp;li[0]</code>, so all the <code>&amp;li</code> instances will change its 1st address into <code>&amp;1</code>.</li>\n</ul>\n" }, { "answer_id": 62497944, "author": "Deepak Patankar", "author_id": 7003331, "author_profile": "https://Stackoverflow.com/users/7003331", "pm_score": 3, "selected": false, "text": "<p>I am adding my answer to explain the same diagrammatically.</p>\n<p>The way you created the 2D, creates a shallow list</p>\n<pre><code>arr = [[0]*cols]*row\n</code></pre>\n<p>Instead, if you want to update the elements of the list, you should use</p>\n<pre><code>rows, cols = (5, 5) \narr = [[0 for i in range(cols)] for j in range(rows)] \n</code></pre>\n<p><strong>Explanation</strong>:</p>\n<p>One can create a list using:</p>\n<pre><code>arr = [0]*N \n</code></pre>\n<p>or</p>\n<pre><code>arr = [0 for i in range(N)] \n</code></pre>\n<p>In the first case all the indices of the array point to the same integer object</p>\n<p><a href=\"https://i.stack.imgur.com/FAYdnm.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/FAYdnm.png\" alt=\"enter image description here\" /></a></p>\n<p>and when you assign a value to a particular index, a new int object is created, for example <code>arr[4] = 5</code> creates</p>\n<p><a href=\"https://i.stack.imgur.com/WkaFam.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WkaFam.png\" alt=\"enter image description here\" /></a></p>\n<p>Now let us see what happens when we create a list of list, in this case, all the elements of our top list will point to the same list</p>\n<p><a href=\"https://i.stack.imgur.com/OiCywl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/OiCywl.png\" alt=\"enter image description here\" /></a></p>\n<p>And if you update the value of any index a new int object will be created. But since all the top-level list indexes are pointing at the same list, all the rows will look the same. And you will get the feeling that updating an element is updating all the elements in that column.</p>\n<p><a href=\"https://i.stack.imgur.com/iUSlRl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/iUSlRl.png\" alt=\"enter image description here\" /></a></p>\n<p><strong>Credits:</strong> Thanks to <a href=\"https://auth.geeksforgeeks.org/user/Pranav%20Devarakonda/articles\" rel=\"nofollow noreferrer\">Pranav Devarakonda</a> for the easy explanation <a href=\"https://www.geeksforgeeks.org/python-using-2d-arrays-lists-the-right-way/\" rel=\"nofollow noreferrer\">here</a></p>\n" }, { "answer_id": 64489659, "author": "Brian", "author_id": 8126390, "author_profile": "https://Stackoverflow.com/users/8126390", "pm_score": 0, "selected": false, "text": "<p>I arrived here because I was looking to see how I could nest an arbitrary number of lists. There are a lot of explanations and specific examples above, but you can generalize N dimensional list of lists of lists of ... with the following recursive function:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import copy\n\ndef list_ndim(dim, el=None, init=None):\n if init is None:\n init = el\n\n if len(dim)&gt; 1:\n return list_ndim(dim[0:-1], None, [copy.copy(init) for x in range(dim[-1])])\n\n return [copy.deepcopy(init) for x in range(dim[0])]\n</code></pre>\n<p>You make your first call to the function like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>dim = (3,5,2)\nel = 1.0\nl = list_ndim(dim, el)\n</code></pre>\n<p>where <code>(3,5,2)</code> is a tuple of the dimensions of the structure (similar to numpy <code>shape</code> argument), and <code>1.0</code> is the element you want the structure to be initialized with (works with None as well). Note that the <code>init</code> argument is only provided by the recursive call to carry forward the nested child lists</p>\n<p>output of above:</p>\n<pre class=\"lang-py prettyprint-override\"><code>[[[1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0]],\n [[1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0]],\n [[1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0]]]\n</code></pre>\n<p>set specific elements:</p>\n<pre class=\"lang-py prettyprint-override\"><code>l[1][3][1] = 56\nl[2][2][0] = 36.0+0.0j\nl[0][1][0] = 'abc'\n</code></pre>\n<p>resulting output:</p>\n<pre class=\"lang-py prettyprint-override\"><code>[[[1.0, 1.0], ['abc', 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 1.0]],\n [[1.0, 1.0], [1.0, 1.0], [1.0, 1.0], [1.0, 56.0], [1.0, 1.0]],\n [[1.0, 1.0], [1.0, 1.0], [(36+0j), 1.0], [1.0, 1.0], [1.0, 1.0]]]\n</code></pre>\n<p>the non-typed nature of lists is demonstrated above</p>\n" }, { "answer_id": 64958758, "author": "mishsx", "author_id": 7841468, "author_profile": "https://Stackoverflow.com/users/7841468", "pm_score": 0, "selected": false, "text": "<p><strong>Note that items in the sequence are not copied; they are referenced multiple times</strong>. This often haunts new Python programmers; consider:</p>\n<pre><code>&gt;&gt;&gt; lists = [[]] * 3\n&gt;&gt;&gt; lists\n[[], [], []]\n&gt;&gt;&gt; lists[0].append(3)\n&gt;&gt;&gt; lists\n[[3], [3], [3]]\n</code></pre>\n<p>What has happened is that <code>[[]]</code> is a one-element list containing an empty list, so all three elements of <code>[[]] * 3</code> are references to this single empty list. Modifying any of the elements of lists modifies this single list.</p>\n<p>Another example to explain this is using <em>multi-dimensional arrays</em>.</p>\n<p>You probably tried to make a multidimensional array like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>&gt;&gt;&gt; A = [[None] * 2] * 3\n</code></pre>\n<p>This looks correct if you print it:</p>\n<pre><code>&gt;&gt;&gt; A\n[[None, None], [None, None], [None, None]]\n</code></pre>\n<p>But when you assign a value, it shows up in multiple places:</p>\n<pre><code>&gt;&gt;&gt; A[0][0] = 5\n&gt;&gt;&gt; A\n[[5, None], [5, None], [5, None]]\n</code></pre>\n<p>The reason is that replicating a list with <code>*</code> doesn’t create copies, it only creates references to the existing objects. The 3 creates a list containing 3 references to the same list of length two. Changes to one row will show in all rows, which is almost certainly not what you want.</p>\n" }, { "answer_id": 65616429, "author": "wwii", "author_id": 2823755, "author_profile": "https://Stackoverflow.com/users/2823755", "pm_score": 0, "selected": false, "text": "<p>While the original question constructed the <em>sublists</em> with the multiplication operator, I'll add an example that uses the <strong>same</strong> list for the sublists. Adding this answer for completeness as this question is often used as a canonical for the issue</p>\n<pre><code>node_count = 4\ncolors = [0,1,2,3]\nsol_dict = {node:colors for node in range(0,node_count)}\n</code></pre>\n<p>The list in each dictionary value is the same object, trying to change one of the dictionaries values will be seen in all.</p>\n<pre><code>&gt;&gt;&gt; sol_dict\n{0: [0, 1, 2, 3], 1: [0, 1, 2, 3], 2: [0, 1, 2, 3], 3: [0, 1, 2, 3]}\n&gt;&gt;&gt; [v is colors for v in sol_dict.values()]\n[True, True, True, True]\n&gt;&gt;&gt; sol_dict[0].remove(1)\n&gt;&gt;&gt; sol_dict\n{0: [0, 2, 3], 1: [0, 2, 3], 2: [0, 2, 3], 3: [0, 2, 3]}\n</code></pre>\n<p>The correct way to construct the dictionary would be to use a copy of the list for each value.</p>\n<pre><code>&gt;&gt;&gt; colors = [0,1,2,3]\n&gt;&gt;&gt; sol_dict = {node:colors[:] for node in range(0,node_count)}\n&gt;&gt;&gt; sol_dict\n{0: [0, 1, 2, 3], 1: [0, 1, 2, 3], 2: [0, 1, 2, 3], 3: [0, 1, 2, 3]}\n&gt;&gt;&gt; sol_dict[0].remove(1)\n&gt;&gt;&gt; sol_dict\n{0: [0, 2, 3], 1: [0, 1, 2, 3], 2: [0, 1, 2, 3], 3: [0, 1, 2, 3]}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11677/" ]
I created a list of lists: ``` xs = [[1] * 4] * 3 # xs == [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]] ``` Then, I changed one of the innermost values: ``` xs[0][0] = 5 # xs == [[5, 1, 1, 1], [5, 1, 1, 1], [5, 1, 1, 1]] ``` Why did every first element of each sublist change to `5`?
When you write `[x]*3` you get, essentially, the list `[x, x, x]`. That is, a list with 3 references to the same `x`. When you then modify this single `x` it is visible via all three references to it: ``` x = [1] * 4 xs = [x] * 3 print(f"id(x): {id(x)}") # id(x): 140560897920048 print( f"id(xs[0]): {id(xs[0])}\n" f"id(xs[1]): {id(xs[1])}\n" f"id(xs[2]): {id(xs[2])}" ) # id(xs[0]): 140560897920048 # id(xs[1]): 140560897920048 # id(xs[2]): 140560897920048 x[0] = 42 print(f"x: {x}") # x: [42, 1, 1, 1] print(f"xs: {xs}") # xs: [[42, 1, 1, 1], [42, 1, 1, 1], [42, 1, 1, 1]] ``` To fix it, you need to make sure that you create a new list at each position. One way to do it is ``` [[1]*4 for _ in range(3)] ``` which will reevaluate `[1]*4` each time instead of evaluating it once and making 3 references to 1 list. --- You might wonder why `*` can't make independent objects the way the list comprehension does. That's because the multiplication operator `*` operates on objects, without seeing expressions. When you use `*` to multiply `[[1] * 4]` by 3, `*` only sees the 1-element list `[[1] * 4]` evaluates to, not the `[[1] * 4` expression text. `*` has no idea how to make copies of that element, no idea how to reevaluate `[[1] * 4]`, and no idea you even want copies, and in general, there might not even be a way to copy the element. The only option `*` has is to make new references to the existing sublist instead of trying to make new sublists. Anything else would be inconsistent or require major redesigning of fundamental language design decisions. In contrast, a list comprehension reevaluates the element expression on every iteration. `[[1] * 4 for n in range(3)]` reevaluates `[1] * 4` every time for the same reason `[x**2 for x in range(3)]` reevaluates `x**2` every time. Every evaluation of `[1] * 4` generates a new list, so the list comprehension does what you wanted. Incidentally, `[1] * 4` also doesn't copy the elements of `[1]`, but that doesn't matter, since integers are immutable. You can't do something like `1.value = 2` and turn a 1 into a 2.
240,182
<p>Why is Oracle's <code>to_char()</code> function adding spaces?</p> <pre><code>select length('012'), length(to_char('012')), length(to_char('12', '000')) from dual; </code></pre> <p><code>3, 3, 4</code></p>
[ { "answer_id": 240196, "author": "stjohnroe", "author_id": 2985, "author_profile": "https://Stackoverflow.com/users/2985", "pm_score": 6, "selected": true, "text": "<p>The format mask that you are using is fixed width and allows for a minus sign</p>\n" }, { "answer_id": 240206, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 7, "selected": false, "text": "<p>The extra leading space is for the potential minus sign. To remove the space you can use FM in the format:</p>\n\n<pre><code>SQL&gt; select to_char(12,'FM000') from dual;\n\nTO_C\n----\n012\n</code></pre>\n\n<p>By the way, note that to_char takes a NUMBER argument; to_char('012') is implicitly converted to to_char(to_number('012')) = to_char(12)</p>\n" }, { "answer_id": 240216, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 5, "selected": false, "text": "<p>To make the answers given more clear:</p>\n\n<pre><code>select '['||to_char(12, '000')||']', \n '['||to_char(-12, '000')||']', \n '['||to_char(12,'FM000')||']' \nfrom dual\n\n\n[ 012] [-012] [012] \n</code></pre>\n" }, { "answer_id": 48288153, "author": "Jay Neumann", "author_id": 9225980, "author_profile": "https://Stackoverflow.com/users/9225980", "pm_score": 2, "selected": false, "text": "<p>Be aware when using the 'fm' syntax it will not include any values after the decimal place unless specified using zeros. For example:</p>\n\n<pre><code>SELECT TO_CHAR(12345, 'fm99,999.00') FROM dual \n</code></pre>\n\n<p>returns: <strong>'12,345.00'</strong> </p>\n\n<pre><code>SELECT TO_CHAR(12345, 'fm99,999.99') FROM dual \n</code></pre>\n\n<p>returns: <strong>'12,345.'</strong> </p>\n\n<p>As you can see this would be an issue if you are expecting two zeros after the decimals place (maybe in fee reports for example).</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4235/" ]
Why is Oracle's `to_char()` function adding spaces? ``` select length('012'), length(to_char('012')), length(to_char('12', '000')) from dual; ``` `3, 3, 4`
The format mask that you are using is fixed width and allows for a minus sign
240,184
<p>I'm writing a CESetup.dll for a Windows Mobile app. It must be unmanaged, which I have little experience with. So I'm unsure of whether I should free the memory I allocate and how I do it.</p> <p>Here's the function I've written:</p> <pre><code> Uninstall_Init( HWND hwndParent, LPCTSTR pszInstallDir ) { LPTSTR folderPath = new TCHAR[256]; _stprintf(folderPath, _T("%s\\cache"), pszInstallDir); EmptyDirectory(folderPath); RemoveDirectory(folderPath); _stprintf(folderPath, _T("%s\\mobileadmin.dat"), pszInstallDir); DeleteFile(folderPath); // To continue uninstallation, return codeUNINSTALL_INIT_CONTINUE // If you want to cancel installation, // return codeUNINSTALL_INIT_CANCEL return codeUNINSTALL_INIT_CONTINUE; } </code></pre> <p>As I understand it, folderPath is allocated on the heap. EmptyDirectory() is my own function that removes all content in the directory. RemoveDirectory() and DeleteFile() are system calls.</p> <p>My question is should I deallocate <code>folderPath</code> before the function exits? If I should, how do I do it?</p>
[ { "answer_id": 240197, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 1, "selected": false, "text": "<p>Yes, you should. By calling </p>\n\n<pre><code> delete[] folderPath;\n</code></pre>\n\n<p>at the end of your function. All memory assigned with <code>new</code> must be freed with <code>delete</code>.</p>\n" }, { "answer_id": 240234, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 2, "selected": false, "text": "<p>There is a common misperception I have seen with people who are unused to C/C++ programming - when they see a function with a pointer parameter, they think the variable must be allocated with <i>new</i>. That is not the case, a local variable is suitable and preferred, since you don't have to worry about its lifetime.</p>\n\n<p>You could simplify your life tremendously by doing</p>\n\n<pre><code>TCHAR folderPath[256];\n</code></pre>\n\n<p>My preferred solution would be to use std::string, but I've put that in a separate answer.</p>\n" }, { "answer_id": 240235, "author": "rmeador", "author_id": 10861, "author_profile": "https://Stackoverflow.com/users/10861", "pm_score": 3, "selected": true, "text": "<p>I think you want to use this:</p>\n\n<pre><code>delete [] folderPath;\n</code></pre>\n\n<p>It looks like you're allocating an array of TCHARs, which makes sense since it's a string. When you allocate an array, you must delete using the array delete operator (which you get by including the brackets in the delete statement). I'm pretty sure you'll get a memory leak with Treb's solution.</p>\n" }, { "answer_id": 240238, "author": "Stu Mackellar", "author_id": 28591, "author_profile": "https://Stackoverflow.com/users/28591", "pm_score": 1, "selected": false, "text": "<p>Yes, you should free the memory. None of the functions you call will do it for you, and nor should they - it wouldn't make any sense. The memory was allocated with the vector new operator and so should be freed with the vector delete operator, i.e.:</p>\n\n<p>delete [] folderPath;</p>\n" }, { "answer_id": 240297, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 1, "selected": false, "text": "<p>It is generally better to use std::string, or in your case std::basic_string. In this case it eliminates a potential buffer overflow when your final path is greater than 256 characters.</p>\n\n<pre><code> Uninstall_Init(\n HWND hwndParent,\n LPCTSTR pszInstallDir\n)\n{\n std::basic_string&lt;TCHAR&gt; folderPath = pszInstallDir;\n folderPath.append(_T(\"\\\\cache\"));\n EmptyDirectory(folderPath.c_str());\n RemoveDirectory(folderPath.c_str());\n folderPath = pszInstallDir;\n folderPath.append(_T(\"\\\\mobileadmin.dat\"));\n DeleteFile(folderPath.c_str());\n// To continue uninstallation, return codeUNINSTALL_INIT_CONTINUE\n// If you want to cancel installation,\n// return codeUNINSTALL_INIT_CANCEL\nreturn codeUNINSTALL_INIT_CONTINUE;\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/631/" ]
I'm writing a CESetup.dll for a Windows Mobile app. It must be unmanaged, which I have little experience with. So I'm unsure of whether I should free the memory I allocate and how I do it. Here's the function I've written: ``` Uninstall_Init( HWND hwndParent, LPCTSTR pszInstallDir ) { LPTSTR folderPath = new TCHAR[256]; _stprintf(folderPath, _T("%s\\cache"), pszInstallDir); EmptyDirectory(folderPath); RemoveDirectory(folderPath); _stprintf(folderPath, _T("%s\\mobileadmin.dat"), pszInstallDir); DeleteFile(folderPath); // To continue uninstallation, return codeUNINSTALL_INIT_CONTINUE // If you want to cancel installation, // return codeUNINSTALL_INIT_CANCEL return codeUNINSTALL_INIT_CONTINUE; } ``` As I understand it, folderPath is allocated on the heap. EmptyDirectory() is my own function that removes all content in the directory. RemoveDirectory() and DeleteFile() are system calls. My question is should I deallocate `folderPath` before the function exits? If I should, how do I do it?
I think you want to use this: ``` delete [] folderPath; ``` It looks like you're allocating an array of TCHARs, which makes sense since it's a string. When you allocate an array, you must delete using the array delete operator (which you get by including the brackets in the delete statement). I'm pretty sure you'll get a memory leak with Treb's solution.
240,219
<p>I have an ASP .Net (3.5) website. I have the following code that uploads a file as a binary to a SQL Database:</p> <pre><code>Print(" protected void UploadButton_Click(object sender, EventArgs e) { //Get the posted file Stream fileDataStream = FileUpload.PostedFile.InputStream; //Get length of file int fileLength = FileUpload.PostedFile.ContentLength; //Create a byte array with file length byte[] fileData = new byte[fileLength]; //Read the stream into the byte array fileDataStream.Read(fileData, 0, fileLength); //get the file type string fileType = FileUpload.PostedFile.ContentType; //Open Connection WebSysDataContext db = new WebSysDataContext(Contexts.WEBSYS_CONN()); //Create New Record BinaryStore NewFile = new BinaryStore(); NewFile.BinaryID = "1"; NewFile.Type = fileType; NewFile.BinaryFile = fileData; //Save Record db.BinaryStores.InsertOnSubmit(NewFile); try { db.SubmitChanges(); } catch (Exception) { throw; } }"); </code></pre> <p>The files that will be uploaded are PDFs, Can you please help me in writing the code to get the PDF out of the SQL database and display it in the browser. (I am able to get the binary file using a linq query but not sure how to process the bytes)</p>
[ { "answer_id": 240243, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>So are you really just after how to serve a byte array in ASP.NET? It sounds like the database part is irrelevant, given that you've said you are able to get the binary file with a LINQ query.</p>\n\n<p>If so, look at <a href=\"http://msdn.microsoft.com/en-us/library/system.web.httpresponse.binarywrite.aspx\" rel=\"nofollow noreferrer\">HttpResponse.BinaryWrite</a>. You should also set the content type of the response appropriately, e.g. application/pdf.</p>\n" }, { "answer_id": 240252, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "<p>How big are the files? Huge buffers (i.e. byte[fileLength]) are usually a bad idea.</p>\n\n<p>Personally, I'd look at things like <a href=\"http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/msg/314e7e3782e59a93\" rel=\"nofollow noreferrer\">this</a> and <a href=\"http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/msg/fcd173f1db2951f1\" rel=\"nofollow noreferrer\">this</a>, which show reading/writing data as streams (the second shows pushing the stream as an http response). But updated to use varchar(max) ;-p</p>\n" }, { "answer_id": 240448, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>protected void Test_Click(object sender, EventArgs e)\n {</p>\n\n<pre><code> WebSysDataContext db = new WebSysDataContext(Contexts.WEBSYS_CONN());\n\n var GetFile = from x in db.BinaryStores\n where x.BinaryID == \"1\"\n select x.BinaryFile;\n\n FileStream MyFileStream;\n long FileSize;\n\n MyFileStream = new FileStream(GetFile, FileMode.Open);\n FileSize = MyFileStream.Length;\n\n byte[] Buffer = new byte[(int)FileSize];\n MyFileStream.Read(Buffer, 0, (int)FileSize);\n MyFileStream.Close();\n\n Response.Write(\"&lt;b&gt;File Contents: &lt;/b&gt;\");\n Response.BinaryWrite(Buffer);\n\n }\n</code></pre>\n\n<p>I tryed this and this did not work. I get a compile error on this line \"MyFileStream = new FileStream(GetFile, FileMode.Open);\"\nI not sure where i am going wrong, is it due to the way i have stored it?</p>\n" }, { "answer_id": 747553, "author": "this. __curious_geek", "author_id": 89556, "author_profile": "https://Stackoverflow.com/users/89556", "pm_score": 0, "selected": false, "text": "<p>When you store binary files in SQL Server it adds an OLE Header to the binary-data. So you must strip that header before actually reading the byte[] into file. Here's how you do this.</p>\n<pre><code>// First Strip-Out the OLE header\nconst int OleHeaderLength = 78;\n\nint strippedDataLength = datarow[&quot;Field&quot;].Length - OleHeaderLength;\n\nbyte[] strippedData = new byte[strippedDataLength];\n\nArray.Copy(datarow[&quot;Field&quot;], OleHeaderLength, \n strippedData , 0, strippedDataLength );\n</code></pre>\n<p>Once you run this code, strippedData will contain the actual file data. You can then use MemoryStream or FileStream to perform I/O on the byte[].</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have an ASP .Net (3.5) website. I have the following code that uploads a file as a binary to a SQL Database: ``` Print(" protected void UploadButton_Click(object sender, EventArgs e) { //Get the posted file Stream fileDataStream = FileUpload.PostedFile.InputStream; //Get length of file int fileLength = FileUpload.PostedFile.ContentLength; //Create a byte array with file length byte[] fileData = new byte[fileLength]; //Read the stream into the byte array fileDataStream.Read(fileData, 0, fileLength); //get the file type string fileType = FileUpload.PostedFile.ContentType; //Open Connection WebSysDataContext db = new WebSysDataContext(Contexts.WEBSYS_CONN()); //Create New Record BinaryStore NewFile = new BinaryStore(); NewFile.BinaryID = "1"; NewFile.Type = fileType; NewFile.BinaryFile = fileData; //Save Record db.BinaryStores.InsertOnSubmit(NewFile); try { db.SubmitChanges(); } catch (Exception) { throw; } }"); ``` The files that will be uploaded are PDFs, Can you please help me in writing the code to get the PDF out of the SQL database and display it in the browser. (I am able to get the binary file using a linq query but not sure how to process the bytes)
So are you really just after how to serve a byte array in ASP.NET? It sounds like the database part is irrelevant, given that you've said you are able to get the binary file with a LINQ query. If so, look at [HttpResponse.BinaryWrite](http://msdn.microsoft.com/en-us/library/system.web.httpresponse.binarywrite.aspx). You should also set the content type of the response appropriately, e.g. application/pdf.
240,224
<p>In my web app, my parameters can contain all sorts of crazy characters (russian chars, slashes, spaces etc) and can therefor not always be represented as-is in a URL.<br> Sending them on their merry way will work in about 50% of the cases. Some things like spaces are already encoded somewhere (I'm guessing in the Html.BuildUrlFromExpression does). Other things though (like "/" and "*") are not.</p> <p>Now I don't know what to do anymore because if I encode them myself, my encoding will get partially encoded again and end up wrong. If I don't encode them, some characters will not get through.</p> <p>What I did is manually .replace() the characters I had problems with.<br> This is off course not a good idea.</p> <p>Ideas?</p> <p><strong>--Edit--</strong><br> <strong>I know there are a multitude of encoding/decoding libraries at my disposal.</strong> It just looks like the mvc framework is already trying to do it for me, but not completely.</p> <pre><code>&lt;a href="&lt;%=Html.BuildUrlFromExpression&lt;SearchController&gt;(c=&gt;c.Search("", 1, "a \v/&amp;irdStr*ng"))%&gt;" title="my hat's awesome!"&gt; </code></pre> <p>will render me</p> <pre><code>&lt;a href="/Search.mvc/en/Search/1/a%20%5Cv/&amp;irdStr*ng" title="my hat's awesome!"&gt; </code></pre> <p>Notice how the forward slash, asterisk and ampersand are not escaped. Why are some escaped and others not? How can I now escape this properly?</p> <p>Am I doing something wrong or is it the framework?</p>
[ { "answer_id": 240245, "author": "Mitchel Sellers", "author_id": 13279, "author_profile": "https://Stackoverflow.com/users/13279", "pm_score": 0, "selected": false, "text": "<p>Have you tried using the <code>Server.UrlEncode()</code> method to do the encoding, and the <code>Server.UrlDecode()</code> method to decode?</p>\n\n<p>I have not had any issues with using it for passing items.</p>\n" }, { "answer_id": 240247, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/ms525738.aspx\" rel=\"nofollow noreferrer\">Server.URLEncode</a> or <a href=\"http://msdn.microsoft.com/en-us/library/zttxte6w.aspx\" rel=\"nofollow noreferrer\">HttpServerUtility.UrlEncode</a> </p>\n\n<p>I see what you're saying now - I didn't realize the question was specific to MVC. Looks like a limitation of that part of the MVC framework - particularly BuildUrlFromExpression is doing some URL encoding, but it knows that also needs some of those punctation as part of the framework URLs.</p>\n\n<p>And also unfortunately, URLEncoding doesn't produce an invariant, i.e.</p>\n\n<pre><code>URLEncode(x) != URLEncode(URLEncode(x))\n</code></pre>\n\n<p>Wouldn't that be nice. Then you could pre-encode your variables and they wouldn't be double encoded.</p>\n\n<p>There's probably an ASP.NET MVC framework best practice for this. I guess another thing you could do is encode into base64 or something that is URLEncode-invariant.</p>\n" }, { "answer_id": 240261, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>Parameters should be escaped using <code>Uri.EscapeDataString</code>:</p>\n\n<pre><code> string url = string.Format(\"http://www.foo.bar/page?name={0}&amp;address={1}\",\n Uri.EscapeDataString(\"adlknad /?? lkm#\"),\n Uri.EscapeDataString(\" qeio103 8182\"));\n\n Console.WriteLine(url);\n Uri uri = new Uri(url);\n string[] options = uri.Query.Split('?','&amp;');\n foreach (string option in options)\n {\n string[] parts = option.Split('=');\n if (parts.Length == 2)\n {\n Console.WriteLine(\"{0} = {1}\",parts[0],\n Uri.UnescapeDataString(parts[1]));\n }\n }\n</code></pre>\n" }, { "answer_id": 240271, "author": "Igal Tabachnik", "author_id": 8205, "author_profile": "https://Stackoverflow.com/users/8205", "pm_score": 0, "selected": false, "text": "<p>Try using the <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=EFB9C819-53FF-4F82-BFAF-E11625130C25&amp;displaylang=en\" rel=\"nofollow noreferrer\">Microsoft Anti-Cross Site Scripting library</a>. It contains several Encode methods, which encode all the characters (including #, and characters in other languages). As for decoding, the browser should handle the encoded Url just fine, however if you need to manually decode the Url, use <a href=\"https://stackoverflow.com/questions/239567/decode-escaped-url-without-using-httputilityurldecode\">Uri.UnescapeDataString</a></p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 258262, "author": "derigel", "author_id": 12045, "author_profile": "https://Stackoverflow.com/users/12045", "pm_score": 0, "selected": false, "text": "<p>Escaping of forward slahes and dots in path part of url is prohibited by security reason (althrough, it works in mono).</p>\n" }, { "answer_id": 380248, "author": "Tracker1", "author_id": 43906, "author_profile": "https://Stackoverflow.com/users/43906", "pm_score": 0, "selected": false, "text": "<p>Html.BuildUrlFromExpression needs to be fixed then, would submit this upstream to the MVC project... alternatively do the encoding to the string before passing to BuildUrlFromExpression, and decode it when it comes back out on the other side.</p>\n\n<p>It may not be readily fixable, as IIS may be handling the decoding of the url string beforehand... may need to do some more advanced encoding/decoding for alternative path characters in the utility methods, and decode on your behalf coming out. </p>\n" }, { "answer_id": 388463, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 1, "selected": false, "text": "<p>AS others have mentioned, if you encode your string first you aviod the issue. </p>\n\n<p>The MVC Framework is encoding characters that it knows it needs to encode, but leaving those that are valid URL characters (e.g. &amp; % ? * /). This is because these are valid URL characters, although they are special chracters in a URL that might not acheive the result you are after.</p>\n" }, { "answer_id": 392026, "author": "Frank Schwieterman", "author_id": 32203, "author_profile": "https://Stackoverflow.com/users/32203", "pm_score": 0, "selected": false, "text": "<p>I've seen similar posts on this. Too me, it looks like a flaw in MVC. The function would be more appropriately named \"BuildUrlFromEncodedExpression\". Whats worse, is that the called function needs to decode its input parameters. Yuk.</p>\n\n<p>If there is any overlap between the characters encoded BuildUrlFromExpression() and the characters encoded by the caller (who, I think might fairly just encode any non-alphanumeric for simplicities sake) then you have potential for nasty bugs.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
In my web app, my parameters can contain all sorts of crazy characters (russian chars, slashes, spaces etc) and can therefor not always be represented as-is in a URL. Sending them on their merry way will work in about 50% of the cases. Some things like spaces are already encoded somewhere (I'm guessing in the Html.BuildUrlFromExpression does). Other things though (like "/" and "\*") are not. Now I don't know what to do anymore because if I encode them myself, my encoding will get partially encoded again and end up wrong. If I don't encode them, some characters will not get through. What I did is manually .replace() the characters I had problems with. This is off course not a good idea. Ideas? **--Edit--** **I know there are a multitude of encoding/decoding libraries at my disposal.** It just looks like the mvc framework is already trying to do it for me, but not completely. ``` <a href="<%=Html.BuildUrlFromExpression<SearchController>(c=>c.Search("", 1, "a \v/&irdStr*ng"))%>" title="my hat's awesome!"> ``` will render me ``` <a href="/Search.mvc/en/Search/1/a%20%5Cv/&irdStr*ng" title="my hat's awesome!"> ``` Notice how the forward slash, asterisk and ampersand are not escaped. Why are some escaped and others not? How can I now escape this properly? Am I doing something wrong or is it the framework?
Parameters should be escaped using `Uri.EscapeDataString`: ``` string url = string.Format("http://www.foo.bar/page?name={0}&address={1}", Uri.EscapeDataString("adlknad /?? lkm#"), Uri.EscapeDataString(" qeio103 8182")); Console.WriteLine(url); Uri uri = new Uri(url); string[] options = uri.Query.Split('?','&'); foreach (string option in options) { string[] parts = option.Split('='); if (parts.Length == 2) { Console.WriteLine("{0} = {1}",parts[0], Uri.UnescapeDataString(parts[1])); } } ```
240,242
<p>I have a main window (#1) on my webpage from which I open a new browser window (#2) from which I open a new window (#3).</p> <p>Now if my user closes window#2 before window#3, I have the problem that window#3 no longer can call function in its window.opener since it has gone away.</p> <p>What I would like to do is to set window#3.opener to window#1 when window#2 closes.</p> <p>I've tried to do this i window#2 (by the way I use jquery):</p> <pre><code>var children = []; $(window).unload( function( ) { $.each( children, function( p, win ) { if ( win ) { win.opener = window.opener; } } ); } ); </code></pre> <p>When window#3 is loaded I add the window to the array children in window#2.</p> <p>But still when window#2 is closed before window#3, windows#3's window.opener doesn't point to window#1.</p> <p>How do I make sure that my grand child window (window#3), can still call the main window (window#1) after window#2 is closed?</p>
[ { "answer_id": 240266, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 0, "selected": false, "text": "<p>This may be tangential, but why do you need to open 3 separate windows? Can you use a jQuery dialog instead? I get very frustrated when apps open windows on me.</p>\n" }, { "answer_id": 240275, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 1, "selected": false, "text": "<p><code>window.opener</code> probably is read-only. I'd setup your own property to refer to the grandparent when grandchild is loaded.</p>\n\n<pre><code>function onLoad() {\n window.grandparent = window.opener.opener;\n}\n</code></pre>\n" }, { "answer_id": 240288, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 3, "selected": true, "text": "<p>In the third wndow you put in:</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n var grandMother = null;\n window.onload = function(){\n grandMother = window.opener.opener;\n }\n&lt;/script&gt;\n</code></pre>\n\n<p>Thus you have the handle to the grandmother-window, and you can then use it for anything directly:</p>\n\n<pre><code>if(grandMother)\n grandMother.document.getElementById(\"myDiv\").firstChild.nodeValue =\"Greetings from your grandchild !-\";\n</code></pre>\n" }, { "answer_id": 240302, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 1, "selected": false, "text": "<p>You should create a reference to the main window when the third opens:</p>\n\n<pre><code>parent = window.opener.opener\n</code></pre>\n\n<p>This will survive the second window closing.</p>\n" }, { "answer_id": 40490753, "author": "JayB", "author_id": 2022103, "author_profile": "https://Stackoverflow.com/users/2022103", "pm_score": 1, "selected": false, "text": "<pre><code>var main_window = get_main_window();\nfunction get_main_window(){\n var w = window;\n while(w.opener !== null){\n w = w.opener;\n }\n return w;\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/441556/" ]
I have a main window (#1) on my webpage from which I open a new browser window (#2) from which I open a new window (#3). Now if my user closes window#2 before window#3, I have the problem that window#3 no longer can call function in its window.opener since it has gone away. What I would like to do is to set window#3.opener to window#1 when window#2 closes. I've tried to do this i window#2 (by the way I use jquery): ``` var children = []; $(window).unload( function( ) { $.each( children, function( p, win ) { if ( win ) { win.opener = window.opener; } } ); } ); ``` When window#3 is loaded I add the window to the array children in window#2. But still when window#2 is closed before window#3, windows#3's window.opener doesn't point to window#1. How do I make sure that my grand child window (window#3), can still call the main window (window#1) after window#2 is closed?
In the third wndow you put in: ``` <script type="text/javascript"> var grandMother = null; window.onload = function(){ grandMother = window.opener.opener; } </script> ``` Thus you have the handle to the grandmother-window, and you can then use it for anything directly: ``` if(grandMother) grandMother.document.getElementById("myDiv").firstChild.nodeValue ="Greetings from your grandchild !-"; ```
240,244
<p>I want to read line n1->n2 from file foo.c into the current buffer.</p> <p>I tried: <code>147,227r /path/to/foo/foo.c</code></p> <p>But I get: "E16: Invalid range", though I am certain that foo.c contains more than 1000 lines.</p>
[ { "answer_id": 240262, "author": "Stewart Johnson", "author_id": 6408, "author_profile": "https://Stackoverflow.com/users/6408", "pm_score": 5, "selected": false, "text": "<p>The {range} refers to the destination in the current file, not the range of lines in the source file.</p>\n\n<p>After some experimentation, it seems</p>\n\n<pre><code>:147,227r /path/to/foo/foo.c\n</code></pre>\n\n<p>means <em>insert the contents of <code>/path/to/foo/foo.c</code> after line 227 in this file.</em> i.e.: it ignores the 147.</p>\n" }, { "answer_id": 240274, "author": "boxxar", "author_id": 15732, "author_profile": "https://Stackoverflow.com/users/15732", "pm_score": 8, "selected": true, "text": "<pre><code>:r! sed -n 147,227p /path/to/foo/foo.c\n</code></pre>\n" }, { "answer_id": 240286, "author": "PaulB", "author_id": 4460, "author_profile": "https://Stackoverflow.com/users/4460", "pm_score": 2, "selected": false, "text": "<p>You will need to:</p>\n\n<pre><code>:r /path/to/foo/foo.c\n:d 228,$\n:d 1,146\n</code></pre>\n\n<p>Three steps, but it will get it done...</p>\n" }, { "answer_id": 17165888, "author": "Justin", "author_id": 1749587, "author_profile": "https://Stackoverflow.com/users/1749587", "pm_score": 2, "selected": false, "text": "<blockquote>\n <p>A range permits a command to be applied to a group of lines in the current buffer.</p>\n</blockquote>\n\n<p>So, the range of read instruction means where to insert the content in the current file, but not the range of file that you want to read.</p>\n" }, { "answer_id": 21130304, "author": "DigitalAce69", "author_id": 3196849, "author_profile": "https://Stackoverflow.com/users/3196849", "pm_score": 2, "selected": false, "text": "<p>I just had to do this in a code project of mine and did it this way:</p>\n\n<p>In buffer with <code>/path/to/foo/foo.c</code> open:</p>\n\n<pre><code>:147,227w export.txt\n</code></pre>\n\n<p>In buffer I'm working with:</p>\n\n<pre><code>:r export.txt\n</code></pre>\n\n<p>Much easier in my book... It requires having both files open, but if I'm importing a set of lines, I usually have them both open anyway. This method is more general and easier to remember for me, especially if I'm trying to export/import a trickier set of lines using <code>g/&lt;search_criteria/:.w &gt;&gt; export.txt</code> or some other more complicated way of selecting lines.</p>\n" }, { "answer_id": 21277670, "author": "joeytwiddle", "author_id": 99777, "author_profile": "https://Stackoverflow.com/users/99777", "pm_score": 5, "selected": false, "text": "<p>You can do it in pure Vimscript, without having to use an external tool like sed:</p>\n\n<pre><code>:put =readfile('/path/to/foo/foo.c')[146:226]\n</code></pre>\n\n<p>Note that we must <strong>decrement one</strong> from the line numbers because arrays start from 0 while line numbers start from 1.</p>\n\n<p><em>Disadvantages</em>: This solution is 7 characters longer than the accepted answer. It will temporarily read the entire file into memory, which could be a concern if that file is huge.</p>\n" }, { "answer_id": 45011363, "author": "raj", "author_id": 8283538, "author_profile": "https://Stackoverflow.com/users/8283538", "pm_score": 4, "selected": false, "text": "<p>Other solutions posted are great for specific line numbers. It's often the case that you want to read from top or bottom of another file. In that case, reading the output of head or tail is very fast. For example - </p>\n\n<pre><code>:r !head -20 xyz.xml\n</code></pre>\n\n<p>Will read first 20 lines from xyz.xml into current buffer where the cursor is</p>\n\n<pre><code>:r !tail -10 xyz.xml \n</code></pre>\n\n<p>Will read last 10 lines from xyz.xml into current buffer where the cursor is</p>\n\n<p>The head and tail commands are extremely fast, therefore even combining them can be much faster than other approaches for very large files.</p>\n\n<pre><code>:r !head -700030 xyz.xml| tail -30\n</code></pre>\n\n<p>Will read line numbers from 700000 to 700030 from file xyz.xml into current buffer </p>\n\n<p>This operation should complete instantly even for fairly large files.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240244", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29405/" ]
I want to read line n1->n2 from file foo.c into the current buffer. I tried: `147,227r /path/to/foo/foo.c` But I get: "E16: Invalid range", though I am certain that foo.c contains more than 1000 lines.
``` :r! sed -n 147,227p /path/to/foo/foo.c ```
240,263
<p>I am putting together some ideas for our automated testing platform and have been looking at Selenium for the test runner.</p> <p>I am wrapping the recorded Selenium C# scripts in an MbUnit test, which is being triggered via the MbUnit NAnt task. The Selenium test client is created as follows:</p> <pre><code>selenium = new DefaultSelenium("host", 4444, "*iexplore", "http://[url]/"); </code></pre> <p>How can I pass the host, port and url settings into the test so their values can be controlled via the NAnt task?</p> <p>For example, I may have multiple Selenium RC servers listening and I want to use the same test code passing in each server address instead of embedding the settings within the tests themselves.</p> <p>I have an approach mocked up using a custom NAnt task I have written but it is not the most elegant solution at present and I wondered if there was an easier way to accomplish what I want to do.</p> <p>Many thanks if anyone can help.</p>
[ { "answer_id": 240295, "author": "Scott Saad", "author_id": 4916, "author_profile": "https://Stackoverflow.com/users/4916", "pm_score": 0, "selected": false, "text": "<p>Anytime I need to integrate with an external entity using NAnt I either end up using the <strong>exec task</strong> or writing a <strong>custom task</strong>. Given the information you posted it would seem that writing your own would indeed be a good solution, However you state you're not happy with it. Can you elaborate a bit on why you don't think you current solution is an <em>elegant</em> one?</p>\n<h2>Update</h2>\n<p>Not knowing <em>internal</em> details it seems like you've solved it pretty well with a custom task. From what I've heard, that's how I would have done it.</p>\n<p>Maybe a new solution will show itself in time, but for now be light on yourself!</p>\n" }, { "answer_id": 240300, "author": "Alex", "author_id": 26564, "author_profile": "https://Stackoverflow.com/users/26564", "pm_score": 0, "selected": false, "text": "<p>For MSBuild I use environment variables, I create those in my CC.NET config then they would be available in the script. I think this would work for you too.</p>\n" }, { "answer_id": 240326, "author": "Tim Peel", "author_id": 31412, "author_profile": "https://Stackoverflow.com/users/31412", "pm_score": 2, "selected": true, "text": "<p>Thanks for the responses so far.</p>\n\n<p>Environment variables could work, however, we could be running parallel tests via a single test assembly so I wouldn't want settings to be overwritten during execution, which could break another test. Interesting line of thought though, thanks, I reckon I could use that in other areas.</p>\n\n<p>My current solution involves a custom NAnt task build on top of the MbUnit task, which allows me to specify the additional host, port, url settings as attributes. These are then saved as a config file within the build directory and then read in by the test assemblies. This feels a bit \"clunky\" to me as my tests need to inherit from a specific class. Not too bad but I'd like to have less dependencies and concentrate on the testing.</p>\n\n<p>Maybe I am worrying too much!!</p>\n" }, { "answer_id": 446606, "author": "Igor Brejc", "author_id": 55408, "author_profile": "https://Stackoverflow.com/users/55408", "pm_score": 1, "selected": false, "text": "<p>I have a base class for all test fixtures which has the following setup code:</p>\n\n<pre><code> [FixtureSetUp]\n public virtual void TestFixtureSetup ()\n {\n BrowserType = (BrowserType) Enum.Parse (typeof (BrowserType),\n System.Configuration.ConfigurationManager.AppSettings[\"BrowserType\"],\n true);\n testMachine = System.Configuration.ConfigurationManager.AppSettings[\"TestMachine\"];\n seleniumPort = int.Parse (System.Configuration.ConfigurationManager.AppSettings[\"SeleniumPort\"],\n System.Globalization.CultureInfo.InvariantCulture);\n seleniumSpeed = System.Configuration.ConfigurationManager.AppSettings[\"SeleniumSpeed\"];\n browserUrl = System.Configuration.ConfigurationManager.AppSettings[\"BrowserUrl\"];\n targetUrl = new Uri (System.Configuration.ConfigurationManager.AppSettings[\"TargetUrl\"]);\n\n string browserExe;\n switch (BrowserType)\n {\n case BrowserType.InternetExplorer:\n browserExe = \"*iexplore\";\n break;\n case BrowserType.Firefox:\n browserExe = \"*firefox\";\n break;\n\n default:\n throw new NotSupportedException ();\n }\n\n selenium = new DefaultSelenium (testMachine, seleniumPort, browserExe, browserUrl);\n selenium.Start ();\n\n System.Console.WriteLine (\"Started Selenium session (browser type={0})\",\n browserType);\n\n // sets the speed of execution of GUI commands\n if (false == String.IsNullOrEmpty (seleniumSpeed))\n selenium.SetSpeed (seleniumSpeed);\n }\n</code></pre>\n\n<p>I then simply supply the test runner with a config. file:\n\n\n \n \n \n \n \n \n \n \n</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31412/" ]
I am putting together some ideas for our automated testing platform and have been looking at Selenium for the test runner. I am wrapping the recorded Selenium C# scripts in an MbUnit test, which is being triggered via the MbUnit NAnt task. The Selenium test client is created as follows: ``` selenium = new DefaultSelenium("host", 4444, "*iexplore", "http://[url]/"); ``` How can I pass the host, port and url settings into the test so their values can be controlled via the NAnt task? For example, I may have multiple Selenium RC servers listening and I want to use the same test code passing in each server address instead of embedding the settings within the tests themselves. I have an approach mocked up using a custom NAnt task I have written but it is not the most elegant solution at present and I wondered if there was an easier way to accomplish what I want to do. Many thanks if anyone can help.
Thanks for the responses so far. Environment variables could work, however, we could be running parallel tests via a single test assembly so I wouldn't want settings to be overwritten during execution, which could break another test. Interesting line of thought though, thanks, I reckon I could use that in other areas. My current solution involves a custom NAnt task build on top of the MbUnit task, which allows me to specify the additional host, port, url settings as attributes. These are then saved as a config file within the build directory and then read in by the test assemblies. This feels a bit "clunky" to me as my tests need to inherit from a specific class. Not too bad but I'd like to have less dependencies and concentrate on the testing. Maybe I am worrying too much!!
240,269
<p>I'm hitting this error and I'm not really sure why. I have a minified version of excanvas.js and something is breaking in IE, specifically on:</p> <p><code> var b=a.createStyleSheet(); </code></p> <p>I'm not sure why. Does anyone have any insight? I can provide more information, I'm just not sure what information will help.</p>
[ { "answer_id": 267947, "author": "Justin Love", "author_id": 30203, "author_profile": "https://Stackoverflow.com/users/30203", "pm_score": 0, "selected": false, "text": "<p>First thing I'd do is use the un-minified version. Looks like this coming from an init function called from onreadystatechange, trying to style canvas elements, although that isn't as enlightening as one might hope.</p>\n" }, { "answer_id": 652627, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>This is a slightly old thread, but I thought it would be useful to post. There seems to be a limitation on how much style information a page can contain, which causes this error in IE6. I am able to produce an invalid argument error using this simple test page:</p>\n\n<pre><code>&lt;html&gt;\n&lt;head&gt;\n&lt;title&gt;&lt;/title&gt;\n&lt;script&gt;\nfor(var i=0;i&lt;32;i++) {\ndocument.createStyleSheet();\n}\n&lt;/script&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>I think this is the source of the problem.\nHTH,\nRussell</p>\n" }, { "answer_id": 1258640, "author": "Mike Gardiner", "author_id": 126663, "author_profile": "https://Stackoverflow.com/users/126663", "pm_score": 0, "selected": false, "text": "<p>The newest version of excanvas fixes this for me. You can always get the newest version from <a href=\"http://code.google.com/p/explorercanvas/source/browse/#svn/trunk\" rel=\"nofollow noreferrer\">svn trunk</a>.</p>\n" }, { "answer_id": 7975820, "author": "bburrier", "author_id": 352311, "author_profile": "https://Stackoverflow.com/users/352311", "pm_score": 1, "selected": false, "text": "<p>The newest version of excanvas.js did not fix this issue for me in IE8 so I updated line 111 of excanvas.js to the code below and I no longer get the exception. The code for this solution is from <a href=\"http://dean.edwards.name/weblog/2010/02/bug85/\" rel=\"nofollow\">http://dean.edwards.name/weblog/2010/02/bug85/</a>.</p>\n\n<pre><code> var ss = null;\n var cssText = 'canvas{display:inline-block;overflow:hidden;' +\n // default size is 300x150 in Gecko and Opera\n 'text-align:left;width:300px;height:150px}';\n try{\n ss = doc.createStyleSheet();\n ss.owningElement.id = 'ex_canvas_';\n ss.cssText = cssText;\n } catch(e) {\n ss = document.styleSheets[document.styleSheets.length - 1];\n ss.cssText += \"\\r\\n\" + cssText;\n }\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2484/" ]
I'm hitting this error and I'm not really sure why. I have a minified version of excanvas.js and something is breaking in IE, specifically on: `var b=a.createStyleSheet();` I'm not sure why. Does anyone have any insight? I can provide more information, I'm just not sure what information will help.
This is a slightly old thread, but I thought it would be useful to post. There seems to be a limitation on how much style information a page can contain, which causes this error in IE6. I am able to produce an invalid argument error using this simple test page: ``` <html> <head> <title></title> <script> for(var i=0;i<32;i++) { document.createStyleSheet(); } </script> </head> <body> </body> </html> ``` I think this is the source of the problem. HTH, Russell
240,283
<p>I'm working on a REST service that has a few requirements:</p> <ol> <li>It has to be secure.</li> <li>Users should not be able to forge requests.</li> </ol> <p>My current proposed solution is to have a custom Authorization header that look like this (this is the same way that the amazon web services work):</p> <pre><code>Authorization: MYAPI username:signature </code></pre> <p>My question is how to form the signature. When the user logs into the service they are given a secret key which they should be able to use to sign requests. This will stop other users submitting requests on their behalf, but will not stop them forging requests.</p> <p>The application that will be using this service is an iPhone application, so I was thinking we could have a public key embedded in the application which we can do an additional signature with, but does this mean we'll have to have two signatures, one for the user key and one for the app key?</p> <p>Any advice would be greatly appreciated, I'd quite like to get this right the first time.</p>
[ { "answer_id": 240305, "author": "Steven Huwig", "author_id": 28604, "author_profile": "https://Stackoverflow.com/users/28604", "pm_score": 2, "selected": true, "text": "<p>I think the simplest way to do this right would be to use HTTPS client authentication. Apple's site has a <a href=\"http://discussions.apple.com/thread.jspa?threadID=1643618\" rel=\"nofollow noreferrer\">thread</a> on this very subject.</p>\n\n<p>Edit: to handle authorization, I would create a separate resource (URI) on the server for each user, and only permit that (authenticated) user to manipulate this resource.</p>\n\n<p>Edit (2014): Apple changed their forum software in the past six years; the thread is now at <a href=\"https://discussions.apple.com/thread/1643618\" rel=\"nofollow noreferrer\">https://discussions.apple.com/thread/1643618</a></p>\n" }, { "answer_id": 240311, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>What's wrong with <a href=\"http://en.wikipedia.org/wiki/Digest_access_authentication\" rel=\"nofollow noreferrer\">HTTP Digest Authentication</a>? </p>\n" }, { "answer_id": 254838, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 1, "selected": false, "text": "<p>There is a better discussion of this here:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/7551/best-practices-for-securing-a-rest-api-web-service\">Best Practices for securing a REST API / web service</a></p>\n" }, { "answer_id": 810721, "author": "Johan Öbrink", "author_id": 99242, "author_profile": "https://Stackoverflow.com/users/99242", "pm_score": 3, "selected": false, "text": "<p>The answer is simple: It cannot be done. As soon as you ship any solution to the end user, he or she can allways attack the server it is communicating with. The most common version of this problem is cheating with hi-score lists in Flash games. You can make it <em>harder</em> by embedding some sort of encryption in the client and obfuscating the code... But all compiled and obfuscated code can allways be decompiled and unobfuscated. It is just a matter of how much time and money you are willing to spend and likewise for the potential attacker.</p>\n\n<p>So your concern is <em>not</em> how to try to prevent the user from sending faulty data to your system. It is how to prevent the user from <em>damaging</em> your system. You have to design your interfaces so that all damage done by faulty data only affects the user sending it.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4590/" ]
I'm working on a REST service that has a few requirements: 1. It has to be secure. 2. Users should not be able to forge requests. My current proposed solution is to have a custom Authorization header that look like this (this is the same way that the amazon web services work): ``` Authorization: MYAPI username:signature ``` My question is how to form the signature. When the user logs into the service they are given a secret key which they should be able to use to sign requests. This will stop other users submitting requests on their behalf, but will not stop them forging requests. The application that will be using this service is an iPhone application, so I was thinking we could have a public key embedded in the application which we can do an additional signature with, but does this mean we'll have to have two signatures, one for the user key and one for the app key? Any advice would be greatly appreciated, I'd quite like to get this right the first time.
I think the simplest way to do this right would be to use HTTPS client authentication. Apple's site has a [thread](http://discussions.apple.com/thread.jspa?threadID=1643618) on this very subject. Edit: to handle authorization, I would create a separate resource (URI) on the server for each user, and only permit that (authenticated) user to manipulate this resource. Edit (2014): Apple changed their forum software in the past six years; the thread is now at <https://discussions.apple.com/thread/1643618>
240,293
<p>How would I achieve the pseudo-code below in JavaScript? I want to include the date check in the second code excerpt, where txtDate is for the BilledDate.</p> <pre><code>If ABS(billeddate – getdate) &gt; 31 then yesno “The date you have entered is more than a month from today, Are you sure the date is correct,”. if (txtDate &amp;&amp; txtDate.value == "") { txtDate.focus(); alert("Please enter a date in the 'Date' field.") return false; } </code></pre>
[ { "answer_id": 240318, "author": "yeradis", "author_id": 30715, "author_profile": "https://Stackoverflow.com/users/30715", "pm_score": -1, "selected": false, "text": "<p>Hello and good day for everyone</p>\n\n<p>You can try Refular Expressions to parse and validate a date format</p>\n\n<p>here is an URL yoy can watch some samples and how to use</p>\n\n<p><a href=\"http://www.javascriptkit.com/jsref/regexp.shtml\" rel=\"nofollow noreferrer\">http://www.javascriptkit.com/jsref/regexp.shtml</a></p>\n\n<p>A very very simple pattern would be: \\d{2}/\\d{2}/\\d{4}</p>\n\n<p>for MM/dd/yyyy or dd/MM/yyyy</p>\n\n<p>With no more....\nbye bye</p>\n" }, { "answer_id": 240337, "author": "roenving", "author_id": 23142, "author_profile": "https://Stackoverflow.com/users/23142", "pm_score": 3, "selected": true, "text": "<p>Generally speaking you work with Date-objects in javascript, and these should be constructed with the following syntax:</p>\n\n<pre><code> var myDate = new Date(yearno, monthno-1, dayno);\n //you could put hour, minute, second and milliseconds in this too\n</code></pre>\n\n<p>Beware, the month-part is an index, so january is 0, february is 1 and december is 11 !-)</p>\n\n<p>Then you can pull out anything you want, the .getTime() thing returns number of milliseconds since start of Unix-age, 1/1 1970 00:00, så this value you could subtract and then look if that value is greater than what you want:</p>\n\n<pre><code>//today (right now !-) can be constructed by an empty constructor\nvar today = new Date();\nvar olddate = new Date(2008,9,2);\nvar diff = today.getTime() - olddate.getTime();\nvar diffInDays = diff/(1000*60*60*24);//24 hours of 60 minutes of 60 second of 1000 milliseconds\n\nalert(diffInDays);\n</code></pre>\n\n<p>This will return a decimal number, so probably you'll want to look at the integer-value:</p>\n\n<pre><code>alert(Math.floor(diffInDays));\n</code></pre>\n" }, { "answer_id": 240350, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 1, "selected": false, "text": "<p>To get the date difference in days in plain JavaScript, you can do it like this:</p>\n\n<pre><code>var billeddate = Date.parse(\"2008/10/27\");\nvar getdate = Date.parse(\"2008/09/25\");\n\nvar differenceInDays = (billeddate - getdate)/(1000*60*60*24)\n</code></pre>\n\n<p>However if you want to get more control in your date manipulation I suggest you to use a date library, I like <a href=\"http://www.datejs.com/\" rel=\"nofollow noreferrer\">DateJS</a>, it's really good to parse and manipulate dates in many formats, and it's really syntactic sugar:</p>\n\n<pre><code>// What date is next thrusday?\nDate.today().next().thursday();\n//or\nDate.parse('next thursday');\n\n// Add 3 days to Today\nDate.today().add(3).days();\n\n// Is today Friday?\nDate.today().is().friday();\n\n// Number fun\n(3).days().ago();\n</code></pre>\n" }, { "answer_id": 240358, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 0, "selected": false, "text": "<p>You can use this to check for valid date</p>\n\n<pre><code>function IsDate(testValue) {\n\n var returnValue = false;\n var testDate;\n try {\n testDate = new Date(testValue);\n if (!isNaN(testDate)) {\n returnValue = true; \n }\n else {\n returnValue = false;\n }\n }\n catch (e) {\n returnValue = false;\n }\n return returnValue;\n }\n</code></pre>\n\n<p>And this is how you can manipulate JS dates. You basically create a date object of now (getDate), add 31 days and compare it to the date entered</p>\n\n<pre><code>function IsMoreThan31Days(dateToTest) {\n\n if(IsDate(futureDate)) {\n var futureDateObj = new Date();\n var enteredDateObj = new Date(dateToTest);\n\n futureDateObj.setDate(futureDateObj.getDate() + 31); //sets to 31 days from now.\n //adds hours and minutes to dateToTest so that the test for 31 days is more accurate.\n enteredDateObj.setHours(futureDateObj.getHours()); \n enteredDateObj.setMinutes(futureDateObj.getMinutes() + 1);\n\n if(enteredDateObj &gt;= futureDateObj) {\n return true;\n }\n else {\n return false;\n }\n }\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
How would I achieve the pseudo-code below in JavaScript? I want to include the date check in the second code excerpt, where txtDate is for the BilledDate. ``` If ABS(billeddate – getdate) > 31 then yesno “The date you have entered is more than a month from today, Are you sure the date is correct,”. if (txtDate && txtDate.value == "") { txtDate.focus(); alert("Please enter a date in the 'Date' field.") return false; } ```
Generally speaking you work with Date-objects in javascript, and these should be constructed with the following syntax: ``` var myDate = new Date(yearno, monthno-1, dayno); //you could put hour, minute, second and milliseconds in this too ``` Beware, the month-part is an index, so january is 0, february is 1 and december is 11 !-) Then you can pull out anything you want, the .getTime() thing returns number of milliseconds since start of Unix-age, 1/1 1970 00:00, så this value you could subtract and then look if that value is greater than what you want: ``` //today (right now !-) can be constructed by an empty constructor var today = new Date(); var olddate = new Date(2008,9,2); var diff = today.getTime() - olddate.getTime(); var diffInDays = diff/(1000*60*60*24);//24 hours of 60 minutes of 60 second of 1000 milliseconds alert(diffInDays); ``` This will return a decimal number, so probably you'll want to look at the integer-value: ``` alert(Math.floor(diffInDays)); ```
240,314
<p>I use Struts v1.3 and have following input form:</p> <p>In struts-config.xml:</p> <pre><code> &lt;form-bean name="testForm" type="org.apache.struts.validator.DynaValidatorForm"&gt; &lt;form-property name="displayName" type="java.lang.String" /&gt; &lt;/form-bean&gt; </code></pre> <p>In validation.xml:</p> <pre><code> &lt;form name="testForm"&gt; &lt;field property="displayName" depends="required"&gt; &lt;arg key="input.displayName" /&gt; &lt;/field&gt; &lt;/form&gt; </code></pre> <p>How do I trim value of "displayName"? How do I trim values of all "java.lang.String" input fields of the form?</p>
[ { "answer_id": 263444, "author": "mana", "author_id": 12016, "author_profile": "https://Stackoverflow.com/users/12016", "pm_score": 2, "selected": false, "text": "<p>You may have a chance to trim the string right at the moment, the request processor updates the data from the input fields to the form. This was not tested, but what happens when you modify the setter setDisplayName(String displayName) to something like </p>\n\n<pre><code>public void setDisplayName(String displayName) {\n this.displayName = displayName.trim();\n}\n</code></pre>\n\n<p>This is not a very good solution, because it migrates logic into a setter.</p>\n\n<p>regards</p>\n" }, { "answer_id": 734994, "author": "Krishna", "author_id": 89154, "author_profile": "https://Stackoverflow.com/users/89154", "pm_score": -1, "selected": false, "text": "<p>Alternatively try using javascript regexp in the jsp that will trim onfocus or onblur</p>\n\n<blockquote>\n <p>&lt; html:text name=\"testForm\" property=\"displayName\" onfocus=\"javascript:this.value=this.value.replace(/^\\s+|\\s+$/g,'')\" onblur=\"javascript:this.value=this.value.replace(/^\\s+|\\s+$/g,'')\" /></p>\n</blockquote>\n" }, { "answer_id": 735086, "author": "JohnRegner", "author_id": 86726, "author_profile": "https://Stackoverflow.com/users/86726", "pm_score": 0, "selected": false, "text": "<p>If you don't mind having String manipulation logic in your Form class, you can try the StringUtils methods in Apache's Commons Lang JAR:</p>\n\n<p><a href=\"http://commons.apache.org/lang/api/org/apache/commons/lang/StringUtils.html\" rel=\"nofollow noreferrer\">StringUtils JavaDoc</a></p>\n\n<p>This will let you trim your Strings in a number of specific ways, whether you want to trimToEmpty, trimToNull, etc. This means you have access to null-safe methods, which can be useful with some values.</p>\n" }, { "answer_id": 6314760, "author": "Nicolae Albu", "author_id": 792272, "author_profile": "https://Stackoverflow.com/users/792272", "pm_score": 1, "selected": false, "text": "<p>If you want to use trim for <strong>validation</strong> purposes, I think the proper way is to create and use your own (or extend an existing) validator for required fields that takes trim into consideration.\nFor an example, you can use this page: <a href=\"http://struts.apache.org/1.2.4/userGuide/dev_validator.html\" rel=\"nofollow\">http://struts.apache.org/1.2.4/userGuide/dev_validator.html</a>, the section \"Pluggable Validators\".</p>\n\n<p>If you want to use trim for trimming the String values before <strong>using them in your business logic</strong>, you can extend <em>org.apache.struts.validator.DynaValidatorForm</em> and overwrite the methods that retrieve values, like <em>get(String name)</em>, <em>getString(String name)</em> and so on. After that, you use your class in the <em>form-bean</em> declarations.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240314", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11662/" ]
I use Struts v1.3 and have following input form: In struts-config.xml: ``` <form-bean name="testForm" type="org.apache.struts.validator.DynaValidatorForm"> <form-property name="displayName" type="java.lang.String" /> </form-bean> ``` In validation.xml: ``` <form name="testForm"> <field property="displayName" depends="required"> <arg key="input.displayName" /> </field> </form> ``` How do I trim value of "displayName"? How do I trim values of all "java.lang.String" input fields of the form?
You may have a chance to trim the string right at the moment, the request processor updates the data from the input fields to the form. This was not tested, but what happens when you modify the setter setDisplayName(String displayName) to something like ``` public void setDisplayName(String displayName) { this.displayName = displayName.trim(); } ``` This is not a very good solution, because it migrates logic into a setter. regards
240,320
<p>I have a method that I would like to call. However, I'm looking for a clean, simple way to kill it or force it to return if it is taking too long to execute.</p> <p>I'm using Java.</p> <p>to illustrate:</p> <pre><code>logger.info("sequentially executing all batches..."); for (TestExecutor executor : builder.getExecutors()) { logger.info("executing batch..."); executor.execute(); } </code></pre> <p>I figure the <code>TestExecutor</code> class should <code>implement Callable</code> and continue in that direction.</p> <p>But all i want to be able to do is stop <code>executor.execute()</code> if it's taking too long.</p> <p>Suggestions...?</p> <p><strong>EDIT</strong></p> <p>Many of the suggestions received assume that the method being executed that takes a long time contains some kind of loop and that a variable could periodically be checked. However, this is not the case. So something that won't necessarily be clean and that will just stop the execution whereever it is is acceptable.</p>
[ { "answer_id": 240343, "author": "Tim Stewart", "author_id": 26002, "author_profile": "https://Stackoverflow.com/users/26002", "pm_score": 3, "selected": false, "text": "<p>I'm assuming the use of multiple threads in the following statements.</p>\n\n<p>I've done some reading in this area and most authors say that it's a bad idea to kill another thread. </p>\n\n<p>If the function that you want to kill can be designed to periodically check a variable or synchronization primitive, and then terminate cleanly if that variable or synchronization primitive is set, that would be pretty clean. Then some sort of monitor thread can sleep for a number of milliseconds and then set the variable or synchronization primitive.</p>\n" }, { "answer_id": 240396, "author": "krakatoa", "author_id": 12223, "author_profile": "https://Stackoverflow.com/users/12223", "pm_score": 2, "selected": false, "text": "<p>Really, you can't... The only way to do it is to either use thread.stop, agree on a 'cooperative' method (e.g. occassionally check for Thread.isInterrupted or call a method which throws an InterruptedException, e.g. Thread.sleep()), or somehow invoke the method in another JVM entirely. </p>\n\n<p>For certain kinds of tests, calling stop() is okay, but it will probably damage the state of your test suite, so you'll have to relaunch the JVM after each call to stop() if you want to avoid interaction effects.</p>\n\n<p>For a good description of how to implement the cooperative approach, check out <a href=\"http://java.sun.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html\" rel=\"nofollow noreferrer\">Sun's FAQ on the deprecated Thread methods</a>.</p>\n\n<p>For an example of this approach in real life, <a href=\"http://www.eclipse.org/articles/Article-Concurrency/jobs-api.html\" rel=\"nofollow noreferrer\">Eclipse RCP's Job API's</a> 'IProgressMonitor' object allows some management service to signal sub-processes (via the 'cancel' method) that they should stop. Of course, that relies on the methods to actually check the isCancelled method regularly, which they often fail to do. </p>\n\n<p>A hybrid approach might be to ask the thread nicely with interrupt, then insist a couple of seconds later with stop. Again, you shouldn't use stop in production code, but it might be fine in this case, esp. if you exit the JVM soon after.</p>\n\n<p>To test this approach, I wrote a simple harness, which takes a runnable and tries to execute it. Feel free to comment/edit.</p>\n\n<pre><code>public void testStop(Runnable r) {\n Thread t = new Thread(r);\n t.start();\n try {\n t.join(2000);\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n\n if (!t.isAlive()) {\n System.err.println(\"Finished on time.\");\n return;\n }\n\n try {\n t.interrupt();\n t.join(2000);\n if (!t.isAlive()) {\n System.err.println(\"cooperative stop\");\n return;\n }\n } catch (InterruptedException e) {\n throw new RuntimeException(e);\n }\n System.err.println(\"non-cooperative stop\");\n StackTraceElement[] trace = Thread.getAllStackTraces().get(t);\n if (null != trace) {\n Throwable temp = new Throwable();\n temp.setStackTrace(trace);\n temp.printStackTrace();\n }\n t.stop();\n System.err.println(\"stopped non-cooperative thread\");\n}\n</code></pre>\n\n<p>To test it, I wrote two competing infinite loops, one cooperative, and one that never checks its thread's interrupted bit.</p>\n\n<pre><code>public void cooperative() {\n try {\n for (;;) {\n Thread.sleep(500);\n }\n } catch (InterruptedException e) {\n System.err.println(\"cooperative() interrupted\");\n } finally {\n System.err.println(\"cooperative() finally\");\n }\n}\n\npublic void noncooperative() {\n try {\n for (;;) {\n Thread.yield();\n }\n } finally {\n System.err.println(\"noncooperative() finally\");\n }\n}\n</code></pre>\n\n<p>Finally, I wrote the tests (JUnit 4) to exercise them:</p>\n\n<pre><code>@Test\npublic void testStopCooperative() {\n testStop(new Runnable() {\n @Override\n public void run() {\n cooperative();\n }\n });\n}\n\n@Test\npublic void testStopNoncooperative() {\n testStop(new Runnable() {\n @Override\n public void run() {\n noncooperative();\n }\n });\n}\n</code></pre>\n\n<p>I had never used Thread.stop() before, so I was unaware of its operation. It works by throwing a ThreadDeath object from whereever the target thread is currently running. This extends Error. So, while it doesn't always work cleanly, it will usually leave simple programs with a fairly reasonable program state. For example, any finally blocks are called. If you wanted to be a real jerk, you could <em>catch</em> ThreadDeath (or Error), and keep running, anyway!</p>\n\n<p>If nothing else, this really makes me wish more code followed the IProgressMonitor approach - adding another parameter to methods that <em>might</em> take a while, and encouraging the implementor of the method to occasionally poll the Monitor object to see if the user wants the system to give up. I'll try to follow this pattern in the future, especially methods that might be interactive. Of course, you don't necessarily know in advance which methods will be used this way, but that is what Profilers are for, I guess.</p>\n\n<p>As for the 'start another JVM entirely' method, that will take more work. I don't know if anyone has written a delegating class loader, or if one is included in the JVM, but that would be required for this approach.</p>\n" }, { "answer_id": 240405, "author": "Dan Dyer", "author_id": 5171, "author_profile": "https://Stackoverflow.com/users/5171", "pm_score": 3, "selected": false, "text": "<p>Java's <a href=\"http://www.ibm.com/developerworks/java/library/j-jtp05236.html\" rel=\"noreferrer\">interruption mechanism</a> is intended for this kind of scenario. If the method that you wish to abort is executing a loop, just have it check the thread's <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#isInterrupted()\" rel=\"noreferrer\">interrupted status</a> on every iteration. If it's interrupted, throw an InterruptedException.</p>\n\n<p>Then, when you want to abort, you just have to invoke <a href=\"http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#interrupt()\" rel=\"noreferrer\">interrupt</a> on the appropriate thread.</p>\n\n<p>Alternatively, you can use the <a href=\"http://java.sun.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html\" rel=\"noreferrer\">approach</a> Sun suggest as an alternative to the deprecated stop method. This doesn't involve throwing any exceptions, the method would just return normally.</p>\n" }, { "answer_id": 240689, "author": "John Gardner", "author_id": 13687, "author_profile": "https://Stackoverflow.com/users/13687", "pm_score": 1, "selected": false, "text": "<p>Nobody answered it directly, so here's the closest thing i can give you in a short amount of psuedo code:</p>\n\n<p>wrap the method in a runnable/callable. The method itself is going to have to check for interrupted status if you want it to stop (for example, if this method is a loop, inside the loop check for Thread.currentThread().isInterrupted and if so, stop the loop (don't check on every iteration though, or you'll just slow stuff down.\nin the wrapping method, use thread.join(timeout) to wait the time you want to let the method run. or, inside a loop there, call join repeatedly with a smaller timeout if you need to do other things while waiting. if the method doesn't finish, after joining, use the above recommendations for aborting fast/clean.</p>\n\n<p>so code wise, old code:</p>\n\n<pre><code>void myMethod()\n{\n methodTakingAllTheTime();\n}\n</code></pre>\n\n<p>new code:</p>\n\n<pre><code>void myMethod()\n{\n Thread t = new Thread(new Runnable()\n {\n public void run()\n {\n methodTakingAllTheTime(); // modify the internals of this method to check for interruption\n }\n });\n t.join(5000); // 5 seconds\n t.interrupt();\n}\n</code></pre>\n\n<p>but again, for this to work well, you'll still have to modify methodTakingAllTheTime or that thread will just continue to run after you've called interrupt.</p>\n" }, { "answer_id": 241534, "author": "Alex", "author_id": 20634, "author_profile": "https://Stackoverflow.com/users/20634", "pm_score": 4, "selected": false, "text": "<p>You should take a look at these classes : \n<a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/FutureTask.html\" rel=\"noreferrer\">FutureTask</a>, <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Callable.html\" rel=\"noreferrer\">Callable</a>, <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executors.html\" rel=\"noreferrer\">Executors</a></p>\n\n<p>Here is an example :</p>\n\n<pre><code>public class TimeoutExample {\n public static Object myMethod() {\n // does your thing and taking a long time to execute\n return someResult;\n }\n\n public static void main(final String[] args) {\n Callable&lt;Object&gt; callable = new Callable&lt;Object&gt;() {\n public Object call() throws Exception {\n return myMethod();\n }\n };\n ExecutorService executorService = Executors.newCachedThreadPool();\n\n Future&lt;Object&gt; task = executorService.submit(callable);\n try {\n // ok, wait for 30 seconds max\n Object result = task.get(30, TimeUnit.SECONDS);\n System.out.println(\"Finished with result: \" + result);\n } catch (ExecutionException e) {\n throw new RuntimeException(e);\n } catch (TimeoutException e) {\n System.out.println(\"timeout...\");\n } catch (InterruptedException e) {\n System.out.println(\"interrupted\");\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 16096955, "author": "davidswelt", "author_id": 2297678, "author_profile": "https://Stackoverflow.com/users/2297678", "pm_score": 0, "selected": false, "text": "<p>The correct answer is, I believe, to create a Runnable to execute the sub-program, and run this in a separate Thread. THe Runnable may be a FutureTask, which you can run with a timeout (\"get\" method). If it times out, you'll get a TimeoutException, in which I suggest you</p>\n\n<ul>\n<li>call thread.interrupt() to attempt to end it in a semi-cooperative manner (many library calls seem to be sensitive to this, so it will probably work)</li>\n<li>wait a little (Thread.sleep(300))</li>\n<li>and then, if the thread is still active (thread.isActive()), call thread.stop(). This is a deprecated method, but apparently the only game in town short of running a separate process with all that this entails.</li>\n</ul>\n\n<p>In my application, where I run untrusted, uncooperative code written by my beginner students, I do the above, ensuring that the killed thread never has (write) access to any objects that survive its death. This includes the object that houses the called method, which is discarded if a timeout occurs. (I tell my students to avoid timeouts, because their agent will be disqualified.) I am unsure about memory leaks...</p>\n\n<p>I distinguish between long runtimes (method terminates) and hard timeouts - the hard timeouts are longer and meant to catch the case when code does not terminate at all, as opposed to being slow.</p>\n\n<p>From my research, Java does not seem to have a non-deprecated provision for running non-cooperative code, which, in a way, is a gaping hole in the security model. Either I can run foreign code and control the permissions it has (SecurityManager), or I cannot run foreign code, because it might end up taking up a whole CPU with no non-deprecated means to stop it.</p>\n\n<pre><code>double x = 2.0; \nwhile(true) {x = x*x}; // do not terminate\nSystem.out.print(x); // prevent optimization\n</code></pre>\n" }, { "answer_id": 23493730, "author": "WVrock", "author_id": 3009607, "author_profile": "https://Stackoverflow.com/users/3009607", "pm_score": 0, "selected": false, "text": "<p>I can think of a not so great way to do this. If you can detect when it is taking too much time, you can have the method check for a boolean in every step. Have the program change the value of the boolean tooMuchTime to true if it is taking too much time (I can't help with this). Then use something like this: </p>\n\n<pre><code> Method(){\n //task1\nif (tooMuchTime == true) return;\n //task2\nif (tooMuchTime == true) return;\n //task3\nif (tooMuchTime == true) return;\n//task4\nif (tooMuchTime == true) return;\n//task5\nif (tooMuchTime == true) return;\n//final task\n }\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20498/" ]
I have a method that I would like to call. However, I'm looking for a clean, simple way to kill it or force it to return if it is taking too long to execute. I'm using Java. to illustrate: ``` logger.info("sequentially executing all batches..."); for (TestExecutor executor : builder.getExecutors()) { logger.info("executing batch..."); executor.execute(); } ``` I figure the `TestExecutor` class should `implement Callable` and continue in that direction. But all i want to be able to do is stop `executor.execute()` if it's taking too long. Suggestions...? **EDIT** Many of the suggestions received assume that the method being executed that takes a long time contains some kind of loop and that a variable could periodically be checked. However, this is not the case. So something that won't necessarily be clean and that will just stop the execution whereever it is is acceptable.
You should take a look at these classes : [FutureTask](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/FutureTask.html), [Callable](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Callable.html), [Executors](http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/Executors.html) Here is an example : ``` public class TimeoutExample { public static Object myMethod() { // does your thing and taking a long time to execute return someResult; } public static void main(final String[] args) { Callable<Object> callable = new Callable<Object>() { public Object call() throws Exception { return myMethod(); } }; ExecutorService executorService = Executors.newCachedThreadPool(); Future<Object> task = executorService.submit(callable); try { // ok, wait for 30 seconds max Object result = task.get(30, TimeUnit.SECONDS); System.out.println("Finished with result: " + result); } catch (ExecutionException e) { throw new RuntimeException(e); } catch (TimeoutException e) { System.out.println("timeout..."); } catch (InterruptedException e) { System.out.println("interrupted"); } } } ```
240,341
<p>I need a date formula in Oracle SQL or T-SQL that will return a date of the previous week (eg Last Monday's date).</p> <p>I have reports with parameters that are run each week usually with parameter dates mon-friday or sunday-saturday of the previous week. I'd like to not have to type in the dates when i run the reports each week. </p> <p>The data is in Oracle and I am using SQL Server 2005 Reporting Services (SSRS) for the reports.</p>
[ { "answer_id": 240368, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "<p>T-SQL:</p>\n\n<pre><code>SELECT \n DateColumn,\n DateColumn - CASE DATEPART(dw, DateColumn) \n WHEN 1 THEN 6\n ELSE DATEPART(dw, DateColumn) - 2\n END MondayOfDateColumn\nFROM \n TheTable\n</code></pre>\n\n<p>Do you need the time part to be \"00:00:00\", too?</p>\n\n<p>If so, add this expression to the calculation:</p>\n\n<pre><code>DATEADD(dd, 0, DATEDIFF(dd, 0, DateColumn)) - CASE DATEPART(dw, /* etc. etc. */\n</code></pre>\n" }, { "answer_id": 240372, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 1, "selected": false, "text": "<p>Check out the list of date functions in <a href=\"https://stackoverflow.com/questions/202243/custom-datetime-formatting-in-sql-server#202288\">this post</a>. You want this one. </p>\n\n<pre><code>SELECT (DATEADD(wk,DATEDIFF(wk,0,GETDATE()) -1 ,0))\n</code></pre>\n\n<p>They are almost always math and not string oriented so they will work faster than casing or casted operations</p>\n" }, { "answer_id": 240392, "author": "Tom H", "author_id": 5696608, "author_profile": "https://Stackoverflow.com/users/5696608", "pm_score": -1, "selected": false, "text": "<p>A T-SQL solution:</p>\n\n<p>Assuming that SET DATEFIRST is at the default (Sunday = 7), last Monday's date:</p>\n\n<pre><code>SELECT\nDATEADD(dy, DATEPART(dw, GETDATE()) - 9, GETDATE())\n</code></pre>\n\n<p>The \"-9' is to go back one week (-7) and then since Monday is 2 we are subtracting 2 more and adding the day of the week for the current day.</p>\n" }, { "answer_id": 240407, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 1, "selected": false, "text": "<p>Here's my solution, tested against 8 days.</p>\n\n<pre><code>SET DateFirst 7\n\nDECLARE @Today datetime\n\nSET @Today = '2008-10-22'\nSELECT DateAdd(wk, DateDiff(wk, 0, DateAdd(dd, -1, @Today)) - 1, 0) as PreviousMonday, @Today as Today\nSET @Today = '2008-10-23'\nSELECT DateAdd(wk, DateDiff(wk, 0, DateAdd(dd, -1, @Today)) - 1, 0) as PreviousMonday, @Today as Today\nSET @Today = '2008-10-24'\nSELECT DateAdd(wk, DateDiff(wk, 0, DateAdd(dd, -1, @Today)) - 1, 0) as PreviousMonday, @Today as Today\nSET @Today = '2008-10-25'\nSELECT DateAdd(wk, DateDiff(wk, 0, DateAdd(dd, -1, @Today)) - 1, 0) as PreviousMonday, @Today as Today\n\nSET @Today = '2008-10-26'\nSELECT DateAdd(wk, DateDiff(wk, 0, DateAdd(dd, -1, @Today)) - 1, 0) as PreviousMonday, @Today as Today\nSET @Today = '2008-10-27'\nSELECT DateAdd(wk, DateDiff(wk, 0, DateAdd(dd, -1, @Today)) - 1, 0) as PreviousMonday, @Today as Today\nSET @Today = '2008-10-28'\nSELECT DateAdd(wk, DateDiff(wk, 0, DateAdd(dd, -1, @Today)) - 1, 0) as PreviousMonday, @Today as Today\nSET @Today = '2008-10-29'\nSELECT DateAdd(wk, DateDiff(wk, 0, DateAdd(dd, -1, @Today)) - 1, 0) as PreviousMonday, @Today as Today\n</code></pre>\n\n<p>Here's the trouble with Sunday:</p>\n\n<pre><code>SELECT\n DateDiff(wk, 0, '2008-10-25') as SatWeek, --5677\n DateDiff(wk, 0, '2008-10-26') as SunWeek, --5688\n DateDiff(wk, 0, '2008-10-27') as MonWeek --5688\n\nSELECT\n DatePart(dw, '2008-10-25') as SatPart, --7\n DatePart(dw, '2008-10-26') as SunPart, --1\n DatePart(dw, '2008-10-27') as MonPart, --2\n convert(datetime,'2008-10-25') - (DatePart(dw, '2008-10-25') - 2) as SatMonday,\n --'2008-10-20'\n convert(datetime,'2008-10-26') - (-1) as SunMonday,\n --'2008-10-27'\n convert(datetime,'2008-10-27') - (DatePart(dw, '2008-10-27') - 2) as MonMonday\n --'2008-10-27'\n</code></pre>\n\n<p>Many of these solutions Provide the same answer for Sunday and Monday in the same week. The old Monday should not be resigned until another Monday has occurred.</p>\n" }, { "answer_id": 240542, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 0, "selected": false, "text": "<p>In Oracle:</p>\n\n<p><em>Edit: Made it a bit more concise</em></p>\n\n<p><em>Edit: Leigh Riffel has posted a much better solution than mine.</em></p>\n\n<pre><code>select\n case when 2 = to_char(sysdate-1,'D') then sysdate - 1\n when 2 = to_char(sysdate-2,'D') then sysdate - 2\n when 2 = to_char(sysdate-3,'D') then sysdate - 3\n when 2 = to_char(sysdate-4,'D') then sysdate - 4\n when 2 = to_char(sysdate-5,'D') then sysdate - 5\n when 2 = to_char(sysdate-6,'D') then sysdate - 6\n when 2 = to_char(sysdate-7,'D') then sysdate - 7\n end as last_monday\nfrom dual\n</code></pre>\n" }, { "answer_id": 240747, "author": "Leigh Riffel", "author_id": 27010, "author_profile": "https://Stackoverflow.com/users/27010", "pm_score": 2, "selected": false, "text": "<p>Here is an Oracle solution for Monday.</p>\n\n<pre><code>select sysdate - 5 - to_number(to_char(sysdate,'D')) from dual\n</code></pre>\n\n<p>Here are examples that retrieve any particular day from the previous week.</p>\n\n<pre><code>SELECT sysdate - 6 - to_number(to_char(sysdate,'D')) LastSunday FROM dual;\nSELECT sysdate - 5 - to_number(to_char(sysdate,'D')) LastMonday FROM dual;\nSELECT sysdate - 4 - to_number(to_char(sysdate,'D')) LastTuesday FROM dual;\nSELECT sysdate - 3 - to_number(to_char(sysdate,'D')) LastWednesday FROM dual;\nSELECT sysdate - 2 - to_number(to_char(sysdate,'D')) LastThursday FROM dual;\nSELECT sysdate - 1 - to_number(to_char(sysdate,'D')) LastFriday FROM dual;\nSELECT sysdate - 0 - to_number(to_char(sysdate,'D')) LastSaturday FROM dual;\n</code></pre>\n\n<p>If you need the time part to be 00:00:00 wrap the statment in TRUNC(...).</p>\n" }, { "answer_id": 240995, "author": "Noah Yetter", "author_id": 30080, "author_profile": "https://Stackoverflow.com/users/30080", "pm_score": 1, "selected": false, "text": "<p>(Oracle)</p>\n\n<p>trunc(sysdate,'IW') --gives this week's monday</p>\n\n<p>trunc(sysdate,'IW')-7 --gives last week's monday</p>\n\n<p>This assumes you consider monday to be the first day of the week, which is what 'IW' (ISO Week) signifies. If you consider sunday to be the first day of the week...</p>\n\n<p>trunc(sysdate,'W')+1 --gives this week's monday, on sunday this will be in the future</p>\n\n<p>trunc(sysdate,'W')+1-7 --gives last week's monday</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I need a date formula in Oracle SQL or T-SQL that will return a date of the previous week (eg Last Monday's date). I have reports with parameters that are run each week usually with parameter dates mon-friday or sunday-saturday of the previous week. I'd like to not have to type in the dates when i run the reports each week. The data is in Oracle and I am using SQL Server 2005 Reporting Services (SSRS) for the reports.
T-SQL: ``` SELECT DateColumn, DateColumn - CASE DATEPART(dw, DateColumn) WHEN 1 THEN 6 ELSE DATEPART(dw, DateColumn) - 2 END MondayOfDateColumn FROM TheTable ``` Do you need the time part to be "00:00:00", too? If so, add this expression to the calculation: ``` DATEADD(dd, 0, DATEDIFF(dd, 0, DateColumn)) - CASE DATEPART(dw, /* etc. etc. */ ```
240,345
<p>I have a ClickOnce deployed application I want to launch from VBScript, similar to launching Microsoft Word in the following example:</p> <pre><code>Dim word Set word = CreateObject("Word.Application") word.Visible = True </code></pre> <p>The problem is I don't know what parameter to pass into the <code>CreateObject</code> function to launch my application. Where would I find the master list of applications installed on my PC/the shortcut to call to launch them?</p>
[ { "answer_id": 240366, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "<p>ClickOnce simply isn't installed that way. They don't typically have COM hooks (for CreateObject), and are installed in an isolated part of the user's profile (not that machine's profile). And don't forget you can also get multiple copies/versions of the same app at once via ClickOnce (from different locations).</p>\n\n<p>One option (in 3.5/VS2008) might be to use the new file associations stuff... associate your app with \".foo\" files, create an empty \".foo\" file and start it. That might work. Look on the Publish=>Options dialog in VS2008.</p>\n\n<p>Otherwise - basically, if you want this type of usage, I suspect you will need to use msi (i.e. a regular installer; not ClickOnce) to register your app as a COM library (dll). Note that .NET doesn't make a good COM server (exe) - so doesn't compare directly to Word. If you want a .NET COM server, then \"serviced components\" are your best bet - but these don't tend to be big on UI.</p>\n\n<p>For info, the isolated area is somewhere around \"%userprofile%\\Local Settings\\Apps\\2.0\", but this is just for interest so you can see it.. don't try running it from there.</p>\n" }, { "answer_id": 265911, "author": "Jeff", "author_id": 13338, "author_profile": "https://Stackoverflow.com/users/13338", "pm_score": 1, "selected": false, "text": "<p>Thanks for the info. That made me realize that I could use a .Net executable instead of a vbscript to launch my application.</p>\n\n<pre><code> Dim program As New Process\n\n 'Try to run a .Net click-once application\n Try\n Dim shortcut As String = Environment.GetFolderPath(Environment.SpecialFolder.StartMenu)\n shortcut = shortcut + \"specific\\shorctut\\path\\shortcut.appref-ms\"\n program .StartInfo.FileName = lpsShortcut\n program .Start()\n Catch\n 'If not go to the web site for a fresh install\n Try\n .Diagnostics.Process.Start(\"IExplore.exe\", \"http://url/program.application\")\n Catch ex As Exception\n 'Log or Email alert here...\n End Try\n End Try\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13338/" ]
I have a ClickOnce deployed application I want to launch from VBScript, similar to launching Microsoft Word in the following example: ``` Dim word Set word = CreateObject("Word.Application") word.Visible = True ``` The problem is I don't know what parameter to pass into the `CreateObject` function to launch my application. Where would I find the master list of applications installed on my PC/the shortcut to call to launch them?
ClickOnce simply isn't installed that way. They don't typically have COM hooks (for CreateObject), and are installed in an isolated part of the user's profile (not that machine's profile). And don't forget you can also get multiple copies/versions of the same app at once via ClickOnce (from different locations). One option (in 3.5/VS2008) might be to use the new file associations stuff... associate your app with ".foo" files, create an empty ".foo" file and start it. That might work. Look on the Publish=>Options dialog in VS2008. Otherwise - basically, if you want this type of usage, I suspect you will need to use msi (i.e. a regular installer; not ClickOnce) to register your app as a COM library (dll). Note that .NET doesn't make a good COM server (exe) - so doesn't compare directly to Word. If you want a .NET COM server, then "serviced components" are your best bet - but these don't tend to be big on UI. For info, the isolated area is somewhere around "%userprofile%\Local Settings\Apps\2.0", but this is just for interest so you can see it.. don't try running it from there.
240,353
<p>I'm looking for a way to convert a preprocessor token to a string.</p> <p>Specifically, I've somewhere got:</p> <pre><code>#define MAX_LEN 16 </code></pre> <p>and I want to use it to prevent buffer overrun:</p> <pre><code>char val[MAX_LEN+1]; // room for \0 sscanf(buf, "%"MAX_LEN"s", val); </code></pre> <p>I'm open to other ways to accomplish the same thing, but standard library only.</p>
[ { "answer_id": 240361, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 5, "selected": false, "text": "<p>I found an answer online.</p>\n\n<blockquote>\n <blockquote>\n<pre><code>#define VERSION_MAJOR 4\n#define VERSION_MINOR 47\n\n#define VERSION_STRING \"v\" #VERSION_MAJOR \".\" #VERSION_MINOR\n</code></pre>\n \n <p>The above does not work but hopefully\n illustrates what I would like to do,\n i.e. make VERSION_STRING end up as\n \"v4.47\".</p>\n </blockquote>\n \n <p>To generate the proper numeric form\n use something like</p>\n\n<pre><code>#define VERSION_MAJOR 4\n#define VERSION_MINOR 47\n\n#define STRINGIZE2(s) #s\n#define STRINGIZE(s) STRINGIZE2(s)\n#define VERSION_STRING \"v\" STRINGIZE(VERSION_MAJOR) \\\n\".\" STRINGIZE(VERSION_MINOR)\n\n#include &lt;stdio.h&gt;\nint main() {\n printf (\"%s\\n\", VERSION_STRING);\n return 0;\n}\n</code></pre>\n</blockquote>\n" }, { "answer_id": 240365, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<p>It's been a while, but this should work:</p>\n\n<pre><code> sscanf(buf, \"%\" #MAX_LEN \"s\", val);\n</code></pre>\n\n<p>If not, it'll need to \"double expansion\" trick:</p>\n\n<pre><code> #define STR1(x) #x\n #define STR(x) STR1(x)\n sscanf(buf, \"%\" STR(MAX_LEN) \"s\", val);\n</code></pre>\n" }, { "answer_id": 240370, "author": "Dan", "author_id": 27816, "author_profile": "https://Stackoverflow.com/users/27816", "pm_score": 8, "selected": true, "text": "<p>see <a href=\"http://www.decompile.com/cpp/faq/file_and_line_error_string.htm\" rel=\"noreferrer\">http://www.decompile.com/cpp/faq/file_and_line_error_string.htm</a>\nspecifically:</p>\n\n<pre><code>#define STRINGIFY(x) #x\n#define TOSTRING(x) STRINGIFY(x)\n#define AT __FILE__ \":\" TOSTRING(__LINE__)\n</code></pre>\n\n<p>so your problem can be solved by doing \n<code>sscanf(buf, \"%\" TOSTRING(MAX_LEN) \"s\", val);</code></p>\n" }, { "answer_id": 241286, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "<p>You should use the double-expansion stringification macro trick. Or just have a</p>\n\n<pre><code>#define MAX_LEN 16\n#define MAX_LEN_S \"16\"\n\nchar val[MAX_LEN+1];\nsscanf(buf, \"%\"MAX_LEN_S\"s\", val);\n</code></pre>\n\n<p>and keep it in sync. (That's a bit of a bother, but as long as the definitions are right next to each other, you'll probably remember.)</p>\n\n<p>Actually, in this particular case, wouldn't <code>strncpy</code> suffice?</p>\n\n<pre><code>strncpy(val, buf, MAX_LEN);\nval[MAX_LEN] = '\\0';\n</code></pre>\n\n<p>If it were <code>printf</code>, though, this would be easier:</p>\n\n<pre><code>sprintf(buf, \"%.*s\", MAX_LEN, val);\n</code></pre>\n" }, { "answer_id": 243630, "author": "James Antill", "author_id": 10314, "author_profile": "https://Stackoverflow.com/users/10314", "pm_score": 1, "selected": false, "text": "<p>While some of the above \"work\", personally I'd recommend just using a simple string API instead of the dreck that comes in libc. There are a number of portable APIs, some of which are also optimized for ease of inclusion in your project ... and some like <a href=\"http://www.and.org/ustr/\" rel=\"nofollow noreferrer\">ustr</a> have tiny space overhead and support for stack variables.</p>\n" }, { "answer_id": 61806583, "author": "Joma", "author_id": 3158594, "author_profile": "https://Stackoverflow.com/users/3158594", "pm_score": 1, "selected": false, "text": "<p>My two cents. In my example the format to generate is <code>%16s%16s%d</code></p>\n<pre><code>#include &lt;iostream&gt;\n\n#define MAX_LEN 16\n\n#define AUX(x) #x\n#define STRINGIFY(x) AUX(x)\n\nint main() {\n char buffer[] = &quot;Hello World 25&quot;;\n char val[MAX_LEN+1]; \n char val2[MAX_LEN+1];\n int val3;\n\n char format[] = &quot;%&quot; STRINGIFY(MAX_LEN) &quot;s&quot; &quot;%&quot; STRINGIFY(MAX_LEN) &quot;s&quot; &quot;%d&quot;;\n int result = sscanf(buffer, format, val, val2, &amp;val3);\n std::cout&lt;&lt; val &lt;&lt; std::endl;\n std::cout&lt;&lt; val2 &lt;&lt; std::endl;\n std::cout&lt;&lt; val3 &lt;&lt; std::endl;\n std::cout&lt;&lt;&quot;Filled: &quot; &lt;&lt; result &lt;&lt; &quot; variables&quot; &lt;&lt; std::endl;\n std::cout &lt;&lt; &quot;Format: &quot; &lt;&lt; format &lt;&lt; std::endl;\n}\n</code></pre>\n<p><strong>Output</strong><br />\n<a href=\"https://i.stack.imgur.com/ETlfv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ETlfv.png\" alt=\"output\" /></a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4777/" ]
I'm looking for a way to convert a preprocessor token to a string. Specifically, I've somewhere got: ``` #define MAX_LEN 16 ``` and I want to use it to prevent buffer overrun: ``` char val[MAX_LEN+1]; // room for \0 sscanf(buf, "%"MAX_LEN"s", val); ``` I'm open to other ways to accomplish the same thing, but standard library only.
see <http://www.decompile.com/cpp/faq/file_and_line_error_string.htm> specifically: ``` #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define AT __FILE__ ":" TOSTRING(__LINE__) ``` so your problem can be solved by doing `sscanf(buf, "%" TOSTRING(MAX_LEN) "s", val);`
240,354
<p>We have a POST to a PL/SQL database procedure that (a) does some database operations based on the POST parameters and (b) redirects the user to a page showing the results.</p> <p>The problem is, when the user does a browser "refresh" of the results page, that still has the original request, so it calls the database procedure and resends the parameters. </p> <p>There are things we can do with saving state so bad things don't happen if the request gets sent in again. But that got me wondering. </p> <p>Is there a way to tell the browser to set the url to the redirect call, not the original user request? This would probably be in either the redirect itself, or in Javascript on the target page. </p>
[ { "answer_id": 240361, "author": "davenpcj", "author_id": 4777, "author_profile": "https://Stackoverflow.com/users/4777", "pm_score": 5, "selected": false, "text": "<p>I found an answer online.</p>\n\n<blockquote>\n <blockquote>\n<pre><code>#define VERSION_MAJOR 4\n#define VERSION_MINOR 47\n\n#define VERSION_STRING \"v\" #VERSION_MAJOR \".\" #VERSION_MINOR\n</code></pre>\n \n <p>The above does not work but hopefully\n illustrates what I would like to do,\n i.e. make VERSION_STRING end up as\n \"v4.47\".</p>\n </blockquote>\n \n <p>To generate the proper numeric form\n use something like</p>\n\n<pre><code>#define VERSION_MAJOR 4\n#define VERSION_MINOR 47\n\n#define STRINGIZE2(s) #s\n#define STRINGIZE(s) STRINGIZE2(s)\n#define VERSION_STRING \"v\" STRINGIZE(VERSION_MAJOR) \\\n\".\" STRINGIZE(VERSION_MINOR)\n\n#include &lt;stdio.h&gt;\nint main() {\n printf (\"%s\\n\", VERSION_STRING);\n return 0;\n}\n</code></pre>\n</blockquote>\n" }, { "answer_id": 240365, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "<p>It's been a while, but this should work:</p>\n\n<pre><code> sscanf(buf, \"%\" #MAX_LEN \"s\", val);\n</code></pre>\n\n<p>If not, it'll need to \"double expansion\" trick:</p>\n\n<pre><code> #define STR1(x) #x\n #define STR(x) STR1(x)\n sscanf(buf, \"%\" STR(MAX_LEN) \"s\", val);\n</code></pre>\n" }, { "answer_id": 240370, "author": "Dan", "author_id": 27816, "author_profile": "https://Stackoverflow.com/users/27816", "pm_score": 8, "selected": true, "text": "<p>see <a href=\"http://www.decompile.com/cpp/faq/file_and_line_error_string.htm\" rel=\"noreferrer\">http://www.decompile.com/cpp/faq/file_and_line_error_string.htm</a>\nspecifically:</p>\n\n<pre><code>#define STRINGIFY(x) #x\n#define TOSTRING(x) STRINGIFY(x)\n#define AT __FILE__ \":\" TOSTRING(__LINE__)\n</code></pre>\n\n<p>so your problem can be solved by doing \n<code>sscanf(buf, \"%\" TOSTRING(MAX_LEN) \"s\", val);</code></p>\n" }, { "answer_id": 241286, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "<p>You should use the double-expansion stringification macro trick. Or just have a</p>\n\n<pre><code>#define MAX_LEN 16\n#define MAX_LEN_S \"16\"\n\nchar val[MAX_LEN+1];\nsscanf(buf, \"%\"MAX_LEN_S\"s\", val);\n</code></pre>\n\n<p>and keep it in sync. (That's a bit of a bother, but as long as the definitions are right next to each other, you'll probably remember.)</p>\n\n<p>Actually, in this particular case, wouldn't <code>strncpy</code> suffice?</p>\n\n<pre><code>strncpy(val, buf, MAX_LEN);\nval[MAX_LEN] = '\\0';\n</code></pre>\n\n<p>If it were <code>printf</code>, though, this would be easier:</p>\n\n<pre><code>sprintf(buf, \"%.*s\", MAX_LEN, val);\n</code></pre>\n" }, { "answer_id": 243630, "author": "James Antill", "author_id": 10314, "author_profile": "https://Stackoverflow.com/users/10314", "pm_score": 1, "selected": false, "text": "<p>While some of the above \"work\", personally I'd recommend just using a simple string API instead of the dreck that comes in libc. There are a number of portable APIs, some of which are also optimized for ease of inclusion in your project ... and some like <a href=\"http://www.and.org/ustr/\" rel=\"nofollow noreferrer\">ustr</a> have tiny space overhead and support for stack variables.</p>\n" }, { "answer_id": 61806583, "author": "Joma", "author_id": 3158594, "author_profile": "https://Stackoverflow.com/users/3158594", "pm_score": 1, "selected": false, "text": "<p>My two cents. In my example the format to generate is <code>%16s%16s%d</code></p>\n<pre><code>#include &lt;iostream&gt;\n\n#define MAX_LEN 16\n\n#define AUX(x) #x\n#define STRINGIFY(x) AUX(x)\n\nint main() {\n char buffer[] = &quot;Hello World 25&quot;;\n char val[MAX_LEN+1]; \n char val2[MAX_LEN+1];\n int val3;\n\n char format[] = &quot;%&quot; STRINGIFY(MAX_LEN) &quot;s&quot; &quot;%&quot; STRINGIFY(MAX_LEN) &quot;s&quot; &quot;%d&quot;;\n int result = sscanf(buffer, format, val, val2, &amp;val3);\n std::cout&lt;&lt; val &lt;&lt; std::endl;\n std::cout&lt;&lt; val2 &lt;&lt; std::endl;\n std::cout&lt;&lt; val3 &lt;&lt; std::endl;\n std::cout&lt;&lt;&quot;Filled: &quot; &lt;&lt; result &lt;&lt; &quot; variables&quot; &lt;&lt; std::endl;\n std::cout &lt;&lt; &quot;Format: &quot; &lt;&lt; format &lt;&lt; std::endl;\n}\n</code></pre>\n<p><strong>Output</strong><br />\n<a href=\"https://i.stack.imgur.com/ETlfv.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ETlfv.png\" alt=\"output\" /></a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240354", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8051/" ]
We have a POST to a PL/SQL database procedure that (a) does some database operations based on the POST parameters and (b) redirects the user to a page showing the results. The problem is, when the user does a browser "refresh" of the results page, that still has the original request, so it calls the database procedure and resends the parameters. There are things we can do with saving state so bad things don't happen if the request gets sent in again. But that got me wondering. Is there a way to tell the browser to set the url to the redirect call, not the original user request? This would probably be in either the redirect itself, or in Javascript on the target page.
see <http://www.decompile.com/cpp/faq/file_and_line_error_string.htm> specifically: ``` #define STRINGIFY(x) #x #define TOSTRING(x) STRINGIFY(x) #define AT __FILE__ ":" TOSTRING(__LINE__) ``` so your problem can be solved by doing `sscanf(buf, "%" TOSTRING(MAX_LEN) "s", val);`
240,382
<p>I need my .net application to use the .html extension instead of .aspx </p> <p>I'm converting a php app and there are external applications which depend on that extension to function.</p> <p>What is the best way to do this?</p> <p>Thanks</p>
[ { "answer_id": 240385, "author": "dove", "author_id": 30913, "author_profile": "https://Stackoverflow.com/users/30913", "pm_score": 1, "selected": false, "text": "<p>You want to use <a href=\"http://msdn.microsoft.com/en-us/library/ms972953.aspx\" rel=\"nofollow noreferrer\">httpHandlers</a></p>\n" }, { "answer_id": 240423, "author": "Luk", "author_id": 5789, "author_profile": "https://Stackoverflow.com/users/5789", "pm_score": 0, "selected": false, "text": "<p>Note that I am not 100% sure this will work with the PHP extension, we are using this procedure for a custom extension here.</p>\n\n<p>You can change the IIS configuration:\nOpen the IIS Console (right click on My Computer > Manage... > Services and applications)</p>\n\n<ul>\n<li>If you are in a website, open the websites properties and the \"Home directory\" tab.</li>\n<li>If you are in a virtual directory, the properties then the \"Virtual Directory\" tab.</li>\n</ul>\n\n<p>Click The \"Configuration Button\", look up the .aspx extension and use the same configuration for the \".php\" extension (tip: you can copy paste the executable dll name between both dialogs)</p>\n" }, { "answer_id": 240441, "author": "Sunny Milenov", "author_id": 8220, "author_profile": "https://Stackoverflow.com/users/8220", "pm_score": 5, "selected": true, "text": "<p>In IIS, when you create the application for the virtual directory, click on \"Configuration\" for the application, and edit \"App mappings\", i.e. add a new mapping for html.</p>\n\n<p>Or, in your web.config, in add this sections:</p>\n\n<pre><code>&lt;httpHandlers&gt;\n &lt;remove verb=\"*\" path=\"*.html\" /&gt;\n &lt;add verb=\"*\" path=\"*.html\" type=\"System.Web.UI.PageHandlerFactory\" /&gt;\n&lt;/httpHandlers&gt;\n&lt;compilation&gt;\n &lt;buildProviders&gt;\n &lt;buildProvider \n extension=\".html\" \n type=\"System.Web.Compilation.PageBuildProvider\" /&gt;\n &lt;/buildProviders&gt;\n&lt;/compilation&gt;\n</code></pre>\n\n<p>EDIT: Added the section, according to the comment. Thanks Chris.</p>\n" }, { "answer_id": 240447, "author": "Simon", "author_id": 15371, "author_profile": "https://Stackoverflow.com/users/15371", "pm_score": 0, "selected": false, "text": "<p>Some time ago, we migrated a web application from coldfusion to PHP, and had to preserve the old URLs. The way we did it was to use mod_rewrite to rewrite .cfm URLs to .php ones. Perhaps you can do something similar?</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2424/" ]
I need my .net application to use the .html extension instead of .aspx I'm converting a php app and there are external applications which depend on that extension to function. What is the best way to do this? Thanks
In IIS, when you create the application for the virtual directory, click on "Configuration" for the application, and edit "App mappings", i.e. add a new mapping for html. Or, in your web.config, in add this sections: ``` <httpHandlers> <remove verb="*" path="*.html" /> <add verb="*" path="*.html" type="System.Web.UI.PageHandlerFactory" /> </httpHandlers> <compilation> <buildProviders> <buildProvider extension=".html" type="System.Web.Compilation.PageBuildProvider" /> </buildProviders> </compilation> ``` EDIT: Added the section, according to the comment. Thanks Chris.
240,393
<p>I have the following SQL-statement:</p> <pre><code>SELECT DISTINCT name FROM log WHERE NOT name = '' AND name LIKE '%.EDIT%'; </code></pre> <p>It works fine on Postgres (returns all different names from log, which aren't empty and contain the string '.EDIT'). But on Oracle this statement doesn't work. Any idea why?</p>
[ { "answer_id": 240417, "author": "Erick B", "author_id": 1373, "author_profile": "https://Stackoverflow.com/users/1373", "pm_score": 2, "selected": false, "text": "<p>The empty string in Oracle is equivalent to NULL, causing the comparison to fail.\nChange that part of the query to NAME IS NOT NULL</p>\n" }, { "answer_id": 240418, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 2, "selected": false, "text": "<p>You can rewrite that query without the \"NOT NAME=''\" clause.</p>\n\n<pre><code> SELECT DISTINCT name \n FROM log\n WHERE name LIKE '%.EDIT%';\n</code></pre>\n\n<p>Does that work for you?</p>\n\n<p>If not, in what way does it not work? Does it cause an error? Are the wrong results returned?</p>\n\n<p>Please expand your question with this info :-)</p>\n" }, { "answer_id": 240430, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 5, "selected": true, "text": "<pre><code>SELECT DISTINCT name FROM log WHERE NOT name = '' AND name LIKE '%.EDIT%';\n</code></pre>\n\n<p>1) Oracle treats '' as NULL, which means the comparison \"NOT name = ''\" is never true or false; use \"IS NOT NULL\" instead. But...</p>\n\n<p>2) The second condition \"name LIKE '%.EDIT%' will not match an empty string anyway, making the first condition redundant.</p>\n\n<p>So re-write as:</p>\n\n<pre><code>SELECT DISTINCT name FROM log WHERE name LIKE '%.EDIT%';\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240393", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21005/" ]
I have the following SQL-statement: ``` SELECT DISTINCT name FROM log WHERE NOT name = '' AND name LIKE '%.EDIT%'; ``` It works fine on Postgres (returns all different names from log, which aren't empty and contain the string '.EDIT'). But on Oracle this statement doesn't work. Any idea why?
``` SELECT DISTINCT name FROM log WHERE NOT name = '' AND name LIKE '%.EDIT%'; ``` 1) Oracle treats '' as NULL, which means the comparison "NOT name = ''" is never true or false; use "IS NOT NULL" instead. But... 2) The second condition "name LIKE '%.EDIT%' will not match an empty string anyway, making the first condition redundant. So re-write as: ``` SELECT DISTINCT name FROM log WHERE name LIKE '%.EDIT%'; ```
240,394
<p>In normal WebForms scenario, any root-relative URLs (e.g. ~/folder/file.txt) <strong>inside</strong> CSS files such as:</p> <pre><code>.form { background-image: url(~/Content/Images/form_bg.gif); } </code></pre> <p>will automatically get resolved during runtime if I specify</p> <pre><code>&lt;head runat="server"&gt; </code></pre> <p>In the referencing page.</p> <p>However, that is no longer happening on an ASP.NET MVC Beta1 website.</p> <p>Is there a way I could enable this functionality without resorting to hacks or CSS-loader file? Like maybe HttpModules or something?</p> <p>Or am I not desigining my website correctly? What is supposed to be a good design?</p> <p>Since original ASP.NET WebForms already has this feature, I'd prefer to utilize any existing functionality if possible. But I don't have much clue.</p> <p>This web application will be deployed in several environments where the ~ root folder might not be obvious.</p> <hr> <p><strong>EDIT:</strong> I mean the url in the file's CONTENT not the file's url itself.</p>
[ { "answer_id": 240637, "author": "David Alpert", "author_id": 8997, "author_profile": "https://Stackoverflow.com/users/8997", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/aa719858(VS.71).aspx\" rel=\"nofollow noreferrer\">Here</a> <a href=\"http://www.15seconds.com/issue/020417.htm\" rel=\"nofollow noreferrer\">are</a> <a href=\"http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=268\" rel=\"nofollow noreferrer\">some</a> <a href=\"http://support.microsoft.com/kb/307996\" rel=\"nofollow noreferrer\">resources</a> on implementing IHttpModule to intercept web requests to your app...</p>\n\n<p>Write/adapt one to check for filetype (e.g. pseudocode: if (request ends with \".css\") ...)</p>\n\n<p>then use a regular expression to replace all instances of \"~/\" with System.Web.VirtualPathUtility.ToAbsolute(\"~/\")</p>\n\n<p>I don't know what this will do to performance, running every request through this kind of a filter, but you can probably fiddle with your web.config file and/or your MVC URL routes to funnel all .css requests through this kind of a filter while skipping past it for other files. </p>\n\n<p>Come to think of it, you can probably achieve the same effect inside an ASP.NET MVC app by pointing all your CSS refrences at a special controller.action that performs this kind of preprocessing for you. i doubt that would be as performant as an IHttpModule though.</p>\n" }, { "answer_id": 240712, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 0, "selected": false, "text": "<p>You could use an <a href=\"http://www.helicontech.com/isapi_rewrite/\" rel=\"nofollow noreferrer\">URL Rewriter</a> to fix the URL as the request comes in, though I am not so sure it is so much elegant as a hack in this case.</p>\n" }, { "answer_id": 243765, "author": "Boris Callens", "author_id": 11333, "author_profile": "https://Stackoverflow.com/users/11333", "pm_score": 0, "selected": false, "text": "<p>I created a PathHelper util class that gives me all the paths I need.\nFor example</p>\n\n<pre><code>&lt;link href=\"&lt;%=PathHelper.CssUrl(\"FormulaIndex.css\")%&gt;\" rel=\"Stylesheet\" type=\"text/css\"/&gt;\n</code></pre>\n\n<p>Gives me the correct full url with the help of System.Web.VirtualPathUtility.ToAbsolute() and my own convention (content/css/yourFile.css).</p>\n\n<p>I did the same for js, xml, t9n, pics...\nIts central, reusable and now I only had to change one line to catch the move of the scripts folder from content/js to Scripts in all my websites and pages.</p>\n\n<p><em>A moronic move if you ask me, but it's reality in the current beta :(</em></p>\n" }, { "answer_id": 269977, "author": "hugoware", "author_id": 17091, "author_profile": "https://Stackoverflow.com/users/17091", "pm_score": 1, "selected": false, "text": "<p>If you're trying to parse the <strong>~/</strong> out of any file, including text files, javascript, etc, you can write a handler that assigns a filter to it and you can use that to search for those paths... for example...</p>\n\n<pre><code>public class StringParsingFilter : MemoryStream {\n\n public Stream OriginalStream {\n get { return this.m_OriginalStream; }\n set { this.m_OriginalStream = value; }\n }\n private System.IO.Stream m_OriginalStream;\n\n public StringParsingFilter() : base() {\n this.m_OriginalStream = null;\n }\n\n public override void Flush() {\n this.m_OriginalStream.Flush();\n }\n\n public override void Write(byte[] buffer, int offset, int count) {\n\n //otherwise, parse for the correct content\n string value = System.Text.Encoding.Default.GetString(buffer);\n string contentType = HttpContext.Current.Response.ContentType;\n\n //Do any parsing here\n ...\n\n //write the new bytes to the stream\n byte[] bytes = System.Text.Encoding.Default.GetBytes(value);\n this.m_OriginalStream.Write(bytes, offset, count + (bytes.Length - buffer.Length));\n\n }\n\n}\n</code></pre>\n\n<p>And you'll write a custom handler to know when to assign this filter... like the following...</p>\n\n<pre><code> public class FilterControlModule : IHttpModule {\n\n public void Init(HttpApplication context) {\n HttpApplication oAppContext = context;\n oAppContext.BeginRequest += new EventHandler(_HandleSettingFilter); \n }\n\n private void _HandleSettingFilter(object sender, EventArgs e) {\n\n //You might check the file at this part to make sure\n //it is a file type you want to parse\n //if (!CurrentFile.isStyleSheet()) { return; }\n ...\n\n //assign the new filter\n StringParsingFilter filter = new StringParsingFilter();\n filter.OriginalStream = HttpContext.Current.Response.Filter;\n HttpContext.Current.Response.Filter = (Stream)filter;\n\n }\n\n}\n</code></pre>\n\n<p>It may have actually been easier just to say \"look up IHttpModules\" but this is some code that I've used to parse files for paths other than ASP.net files.</p>\n\n<p>You'll also have to change some things in your IIS settings to allow the files to be parsed by setting the ASP.net ISAPI to be a wildcard for all of the files that get handled. You can see more <a href=\"http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5c5ae5e0-f4f9-44b0-a743-f4c3a5ff68ec.mspx?mfr=true\" rel=\"nofollow noreferrer\">at this website</a>, if you're using IIS6 that is...</p>\n\n<p>You can also use this to modify any file types so you could assign some filters for images, some for javascript or stylesheets or ... really anything...</p>\n" }, { "answer_id": 269985, "author": "David Kolar", "author_id": 3283, "author_profile": "https://Stackoverflow.com/users/3283", "pm_score": 7, "selected": true, "text": "<p>I would not bother with the auto-root-finding <code>~</code> character. I understand that you want the same solution to work where the root directory differs between deployments, but within the CSS document you shouldn't have any problems using relative paths. The paths in the CSS document (to the image URL in your example) will always be relative to the location of the CSS file regardless of the path of any page that loads that CSS file. So if your images are in <code>~/Content/Images</code> and your stylesheets are in <code>~/Content/Stylesheets</code>, you'll always be able to use <code>background-image: url(../Images/form_bg.gif);</code> and it will work regardless of the location of the page that loads the stylesheet.</p>\n\n<p>Is there a reason this wouldn't work?</p>\n" }, { "answer_id": 274425, "author": "David P", "author_id": 13145, "author_profile": "https://Stackoverflow.com/users/13145", "pm_score": 3, "selected": false, "text": "<p>One trick I have used in the past, was to actually make my CSS file have a .ASPX extension, and set the ContentType property in the page signature:</p>\n\n<pre><code>&lt;%@ Page Language=\"C#\" ContentType=\"text/css\" %&gt;\n\nbody {\n margin: 0;\n padding: 0;\n background: #C32605 url(&lt;%= ResolveUrl(\"~/Content/themes/base/images/BodyBackground.png\") %&gt;) repeat-x;\n font-family: Verdana, Arial, sans-serif;\n font-size: small;\n color: #d7f9ff;\n}\n</code></pre>\n\n<p>This will ensure that the CSS file goes through the ASP.NET framework, and replaces the server side code with your relative path.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3055/" ]
In normal WebForms scenario, any root-relative URLs (e.g. ~/folder/file.txt) **inside** CSS files such as: ``` .form { background-image: url(~/Content/Images/form_bg.gif); } ``` will automatically get resolved during runtime if I specify ``` <head runat="server"> ``` In the referencing page. However, that is no longer happening on an ASP.NET MVC Beta1 website. Is there a way I could enable this functionality without resorting to hacks or CSS-loader file? Like maybe HttpModules or something? Or am I not desigining my website correctly? What is supposed to be a good design? Since original ASP.NET WebForms already has this feature, I'd prefer to utilize any existing functionality if possible. But I don't have much clue. This web application will be deployed in several environments where the ~ root folder might not be obvious. --- **EDIT:** I mean the url in the file's CONTENT not the file's url itself.
I would not bother with the auto-root-finding `~` character. I understand that you want the same solution to work where the root directory differs between deployments, but within the CSS document you shouldn't have any problems using relative paths. The paths in the CSS document (to the image URL in your example) will always be relative to the location of the CSS file regardless of the path of any page that loads that CSS file. So if your images are in `~/Content/Images` and your stylesheets are in `~/Content/Stylesheets`, you'll always be able to use `background-image: url(../Images/form_bg.gif);` and it will work regardless of the location of the page that loads the stylesheet. Is there a reason this wouldn't work?
240,419
<p>I've got a VB.NET class that is invoked with a context menu extension in Internet Explorer. </p> <p>The code has access to the object model of the page, and reading data is not a problem. This is the code of a test function...it changes the status bar text (OK), prints the page HTML (OK), changes the HTML by adding a text and prints again the page HTML (OK, in the second pop-up my added text is in the HTML)</p> <p>But the Internet Explorer window doesn't show it. Where am I doing wrong?</p> <pre><code>Public Sub CallingTest(ByRef Source As Object) Dim D As mshtml.HTMLDocument = Source.document Source.status = "Working..." Dim H As String = D.documentElement.innerHTML() MsgBox(H) D.documentElement.insertAdjacentText("beforeEnd", "ThisIsATest") H = D.documentElement.outerHTML() MsgBox(H) Source.status = "" End Sub </code></pre> <p>The function is called like this from JavaScript: </p> <pre><code>&lt;script&gt; var EB = new ActiveXObject("MyObject.MyClass"); EB.CallingTest(external.menuArguments); &lt;/script&gt; </code></pre>
[ { "answer_id": 240435, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "<p>For this kind of thing you have separate Diagrams showing the internal structure or processing of a class.</p>\n\n<p>usually, those extra diagrams are activity diagrams to show processing. Sometimes one per method. You might also have an internal sequence diagram showing the API interactions.</p>\n\n<p>No reason you can't have an additional class diagram to show internal structure of a class.</p>\n" }, { "answer_id": 240460, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 3, "selected": false, "text": "<p>Since UML isn't supposed to be directly implementation specific, I'd use a naming convention, such as:</p>\n\n<pre><code>OuterClass vs OuterClass::InnerClass\n</code></pre>\n\n<p>I would imagine if you're hoping to reverse-engineer or code-generate to/from UML that different tools would us different techniques (if they support it at all).</p>\n\n<p>A quick test of some reverse engineering using Enterprise Architect (EA v7) confirms that they use the above <code>InnerClass::OuterClass</code> syntax when processing some C# with a public inner class.</p>\n" }, { "answer_id": 242035, "author": "chimp", "author_id": 18364, "author_profile": "https://Stackoverflow.com/users/18364", "pm_score": 5, "selected": true, "text": "<p>Consider using a nesting relationship (a line with a '+' in a circle at the parent end).</p>\n" }, { "answer_id": 242045, "author": "chimp", "author_id": 18364, "author_profile": "https://Stackoverflow.com/users/18364", "pm_score": 0, "selected": false, "text": "<p>Or you can show the inner class fully enclosed by the outer class, one rectangle inside another.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22108/" ]
I've got a VB.NET class that is invoked with a context menu extension in Internet Explorer. The code has access to the object model of the page, and reading data is not a problem. This is the code of a test function...it changes the status bar text (OK), prints the page HTML (OK), changes the HTML by adding a text and prints again the page HTML (OK, in the second pop-up my added text is in the HTML) But the Internet Explorer window doesn't show it. Where am I doing wrong? ``` Public Sub CallingTest(ByRef Source As Object) Dim D As mshtml.HTMLDocument = Source.document Source.status = "Working..." Dim H As String = D.documentElement.innerHTML() MsgBox(H) D.documentElement.insertAdjacentText("beforeEnd", "ThisIsATest") H = D.documentElement.outerHTML() MsgBox(H) Source.status = "" End Sub ``` The function is called like this from JavaScript: ``` <script> var EB = new ActiveXObject("MyObject.MyClass"); EB.CallingTest(external.menuArguments); </script> ```
Consider using a nesting relationship (a line with a '+' in a circle at the parent end).
240,425
<p>When I merge the trunk into a feature-branch, a delete that occurred on the trunk will not be replicated to my working copy.</p> <p>Why will a delete on trunk not delete the same file on a branch when merging? I'm using subversion 1.5 client and server.</p> <p>I'm assuming that changes to the file in the branch will be skipped when reintegrating the branch?</p> <p>What's the best way to redeem the file on trunk, as a colleague deleted the file from trunk only because it was not "ready".</p> <p>Situation:</p> <pre><code>cd project; svn copy trunk branches/f1; svn ci -m "branching out" branches f1; echo "modifying a file on branch." &gt;&gt; branches/f1/file1; svn ci branches/f1 -m "Branch modified"; echo "Above modify is not even needed to state the case"; svn rm trunk/file1; svn ci trunk -m "creating (conflicting) delete on trunk"; cd branches/f1; svn merge svn+ssh://repos/trunk . [ -f file1 ] &amp;&amp; echo "file f1 does exist while it should have been deleted by merge."; </code></pre> <p>So, the file still exists in my working copy even though I'm merging in trunk where the file has been actively deleted. Highly unexpected. In my case I haven't even made any changes to the file, which is the only reason i can think of why svn would save the file.</p>
[ { "answer_id": 242636, "author": "JXG", "author_id": 15456, "author_profile": "https://Stackoverflow.com/users/15456", "pm_score": 1, "selected": false, "text": "<p>To the best of my understanding, what you've done is create a local conflict in file1. In your branch, it was modified. In your trunk, it was deleted. When you merge, it will be in conflict. So the file will still be around.</p>\n\n<p>I suggest 2 tests:</p>\n\n<ol>\n<li>After running the code above,\ninclude the results of <code>svn status</code>.</li>\n<li>Try the same code as above, but\nwithout modifying that branch at\nall. (<code>svn status</code> would be helpful\nhere as well.)</li>\n</ol>\n" }, { "answer_id": 4337918, "author": "RjOllos", "author_id": 121694, "author_profile": "https://Stackoverflow.com/users/121694", "pm_score": 0, "selected": false, "text": "<p>Are you sure that the file deleted on the trunk is still under version control after the merge? It may be unversioned, but still present, which is the expected behavior. Looking at the output of <code>svn status</code> will let you see whether the file is still under version control.</p>\n\n<p>You may wish to take a look at this bug report, which thoroughly explains the situation: <a href=\"http://subversion.tigris.org/issues/show_bug.cgi?id=2282\" rel=\"nofollow\">http://subversion.tigris.org/issues/show_bug.cgi?id=2282</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240425", "https://Stackoverflow.com", "https://Stackoverflow.com/users/972/" ]
When I merge the trunk into a feature-branch, a delete that occurred on the trunk will not be replicated to my working copy. Why will a delete on trunk not delete the same file on a branch when merging? I'm using subversion 1.5 client and server. I'm assuming that changes to the file in the branch will be skipped when reintegrating the branch? What's the best way to redeem the file on trunk, as a colleague deleted the file from trunk only because it was not "ready". Situation: ``` cd project; svn copy trunk branches/f1; svn ci -m "branching out" branches f1; echo "modifying a file on branch." >> branches/f1/file1; svn ci branches/f1 -m "Branch modified"; echo "Above modify is not even needed to state the case"; svn rm trunk/file1; svn ci trunk -m "creating (conflicting) delete on trunk"; cd branches/f1; svn merge svn+ssh://repos/trunk . [ -f file1 ] && echo "file f1 does exist while it should have been deleted by merge."; ``` So, the file still exists in my working copy even though I'm merging in trunk where the file has been actively deleted. Highly unexpected. In my case I haven't even made any changes to the file, which is the only reason i can think of why svn would save the file.
To the best of my understanding, what you've done is create a local conflict in file1. In your branch, it was modified. In your trunk, it was deleted. When you merge, it will be in conflict. So the file will still be around. I suggest 2 tests: 1. After running the code above, include the results of `svn status`. 2. Try the same code as above, but without modifying that branch at all. (`svn status` would be helpful here as well.)
240,467
<p>Of course, there are a whole range of possible errors relating to document validity, but my immediate stumbling block occurs when changing a paragraph (<code>p</code>) into an <code>address</code> element. My current method is (more-or-less):</p> <pre><code>var p = $('p#test'); p.replaceWith('&lt;address&gt;' + p.html() + '&lt;/address&gt;'); </code></pre> <p>but that fails for this specific case; it works perfectly for p -> blockquote or h2 -> h3. Firebug suggests that a self-closing element (<code>&lt;address/&gt;</code>) has been added to the document, for some reason.</p> <p>Can anyone spot the bug or suggest an alternative method?</p>
[ { "answer_id": 240480, "author": "Ady", "author_id": 31395, "author_profile": "https://Stackoverflow.com/users/31395", "pm_score": 0, "selected": false, "text": "<p>You'll could use a placeholder around the title:</p>\n\n<pre>\n&lt;span id=\"demo\">&lt;h1>Title&lt;/h1>&lt;/span>\n</pre>\n\n<p>Then use JavaScript DOM to create new values for the innerHTML property.</p>\n\n<pre>\n&lt;script type=\"javascript\">\n\nsetTitle = function(id, tag, title) {\n var container = document.getElementById(id);\n container.innerHTML = '&lt;' + tag + '>' + title + '&lt;/' + tag + '>';\n}\n\nsetTitle('demo', 'h1', 'My Title');\n\n&lt;/script>\n</pre>\n" }, { "answer_id": 240494, "author": "Daniel Cassidy", "author_id": 31662, "author_profile": "https://Stackoverflow.com/users/31662", "pm_score": 4, "selected": true, "text": "<pre><code>var p = $('p#test');\nvar a = $('&lt;address&gt;').\n append(p.contents());\np.replaceWith(a);\n</code></pre>\n<p>Your solution is subject to all sorts of horrible HTML escaping issues and possibly injection attacks.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5058/" ]
Of course, there are a whole range of possible errors relating to document validity, but my immediate stumbling block occurs when changing a paragraph (`p`) into an `address` element. My current method is (more-or-less): ``` var p = $('p#test'); p.replaceWith('<address>' + p.html() + '</address>'); ``` but that fails for this specific case; it works perfectly for p -> blockquote or h2 -> h3. Firebug suggests that a self-closing element (`<address/>`) has been added to the document, for some reason. Can anyone spot the bug or suggest an alternative method?
``` var p = $('p#test'); var a = $('<address>'). append(p.contents()); p.replaceWith(a); ``` Your solution is subject to all sorts of horrible HTML escaping issues and possibly injection attacks.
240,470
<p>I want to get user input in one page, store that in a php variable and use it in another php page. I have tried using 'sessions' but it doesn't seem to be working. Is there another safe alternative? This information is likely to be usernames and passwords.</p>
[ { "answer_id": 240489, "author": "ZombieSheep", "author_id": 377, "author_profile": "https://Stackoverflow.com/users/377", "pm_score": 3, "selected": false, "text": "<p>I Agree with carson, sessions should work for this. Make sure you are calling <a href=\"http://uk3.php.net/session_start\" rel=\"noreferrer\">session_start()</a> before anything else on any page you want to use the session variables.</p>\n\n<p>Also, I would not store password info directly, rather use some kind of authentication token mechanism. IMHO, it is not <em>intrinsically</em> unsafe to store password data in a session, but if there is no need to do so, you should probably try to avoid it.</p>\n" }, { "answer_id": 240499, "author": "milot", "author_id": 22637, "author_profile": "https://Stackoverflow.com/users/22637", "pm_score": 0, "selected": false, "text": "<p>You can try using POST and GET methods for transferring user inputs within PHP scripts.</p>\n\n<p><a href=\"http://www.php.net/manual/en/reserved.variables.get.php\" rel=\"nofollow noreferrer\">PHP GET</a></p>\n\n<p><a href=\"http://www.php.net/manual/en/reserved.variables.post.php\" rel=\"nofollow noreferrer\">PHP POST</a></p>\n" }, { "answer_id": 240503, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 5, "selected": true, "text": "<p>Try changing your session code as this is the best way to do this.</p>\n\n<p>For example:</p>\n\n<h2>index.php</h2>\n\n<pre><code>&lt;?php\nsession_start();\n\nif (isset($_POST['username'], $_POST['password']) {\n $_SESSION['username'] = $_POST['username'];\n $_SESSION['password'] = $_POST['password'];\n echo '&lt;a href=\"nextpage.php\"&gt;Click to continue.&lt;/a&gt;';\n} else {\n // form\n}\n?&gt;\n</code></pre>\n\n<h2>nextpage.php</h2>\n\n<pre><code>&lt;?php\nsession_start();\n\nif (isset($_SESSION['username'])) {\n echo $_SESSION['username'];\n} else {\n header('Location: index.php');\n}\n?&gt;\n</code></pre>\n\n<p>However I'd probably store something safer like a userid in a session rather than the user's login credentials.</p>\n" }, { "answer_id": 240507, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 3, "selected": false, "text": "<p>There are several ways:</p>\n\n<ul>\n<li>use <a href=\"http://de2.php.net/manual/en/book.session.php\" rel=\"noreferrer\">sessions</a> (but don't forget to call <a href=\"http://de2.php.net/manual/en/function.session-start.php\" rel=\"noreferrer\">session_start()</a> on every page you'll use the session data store (<a href=\"http://de2.php.net/manual/en/reserved.variables.session.php\" rel=\"noreferrer\">$_SESSION</a>))</li>\n<li>append your data to the query string of the \"next\" page (<a href=\"http://de2.php.net/manual/en/reserved.variables.get.php\" rel=\"noreferrer\">$_GET</a>)</li>\n<li>post your data to the \"next\" page (<a href=\"http://de2.php.net/manual/en/reserved.variables.post.php\" rel=\"noreferrer\">$_POST</a>)</li>\n</ul>\n\n<p>The session-way is the only way on which the data does not \"leave\" the server as it's stored on the server itself. For all other ways mentioned above you have to take care of sanitizing and validating the data on the receiving page.</p>\n\n<p>The most simple way would be</p>\n\n<pre><code>//page1.php\nsession_start();\n$_SESSION['user']='user';\n$_SESSION['password']='password';\n\n//page2.php\nsession_start();\necho $_SESSION['user'] . ' ' . $_SESSION['password'];\n</code></pre>\n" }, { "answer_id": 240512, "author": "Treb", "author_id": 22114, "author_profile": "https://Stackoverflow.com/users/22114", "pm_score": 0, "selected": false, "text": "<p>I agree too, sessions are the best solution. See this chapter from <a href=\"http://oreilly.com/catalog/webdbapps/chapter/ch08.html\" rel=\"nofollow noreferrer\">Web Database Applications with PHP &amp; MySQL</a> for some examples.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24391/" ]
I want to get user input in one page, store that in a php variable and use it in another php page. I have tried using 'sessions' but it doesn't seem to be working. Is there another safe alternative? This information is likely to be usernames and passwords.
Try changing your session code as this is the best way to do this. For example: index.php --------- ``` <?php session_start(); if (isset($_POST['username'], $_POST['password']) { $_SESSION['username'] = $_POST['username']; $_SESSION['password'] = $_POST['password']; echo '<a href="nextpage.php">Click to continue.</a>'; } else { // form } ?> ``` nextpage.php ------------ ``` <?php session_start(); if (isset($_SESSION['username'])) { echo $_SESSION['username']; } else { header('Location: index.php'); } ?> ``` However I'd probably store something safer like a userid in a session rather than the user's login credentials.
240,510
<p>I have a string from an email header, like <code>Date: Mon, 27 Oct 2008 08:33:29 -0700</code>. What I need is an instance of GregorianCalendar, that will represent the same moment. As easy as that -- how do I do it?</p> <p>And for the fastest ones -- this is <strong>not</strong> going to work properly:</p> <pre><code>SimpleDateFormat format = ... // whatever you want Date date = format.parse(myString) GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(date) </code></pre> <p>because it will normalize the timezone to UTC (or your local machine time, depending on Java version). What I need is calendar.getTimeZone().getRawOffset() to return <code>-7 * milisInAnHour</code>.</p>
[ { "answer_id": 240565, "author": "Jack Leow", "author_id": 31506, "author_profile": "https://Stackoverflow.com/users/31506", "pm_score": 5, "selected": true, "text": "<p>I'd recommend looking into the Joda Time library, if that's an option. I'm normally against using a third-party library when the core platform provides similar functionality, but I made this an exception because the author of Joda Time is also behind JSR310, and Joda Time is basically going to be rolled into Java 7 eventually.</p>\n\n<p><a href=\"http://joda-time.sourceforge.net/\" rel=\"noreferrer\">http://joda-time.sourceforge.net/</a></p>\n\n<p>So anyway, if Joda Time is an option, something like this <em>should</em> work:</p>\n\n<pre><code>DateTimeFormatter formatter =\n DateTimeFormat.forPattern(\"your pattern\").withOffsetParsed();\nDateTime dateTime = formatter.parseDateTime(\"your input\");\nGregorianCalendar cal = dateTime.toGregorianCalendar();\n</code></pre>\n\n<p>I hope this helps.</p>\n" }, { "answer_id": 240734, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>And for the fastest ones -- this is not going to work properly ... \n because it will normalize the timezone to UTC (or your local machine time, depending on Java version). What I need is calendar.getTimeZone().getRawOffset() to return -7 * milisInAnHour.</p>\n</blockquote>\n\n<p>Well technically this does work, because while it will return an object with TimeZone equal to the current system TimeZone, the time will be modified to account for the offset.</p>\n\n<p>This code: </p>\n\n<pre><code>String dateString = \"Mon, 27 Oct 2008 08:33:29 -0700\";\nDateFormat df = new SimpleDateFormat(\"E, dd MMM yyyy hh:mm:ss Z\");\nDate parsed = df.parse(dateString);\nSystem.out.println(\"parsed date: \" + parsed);\n\nCalendar newCalendar = Calendar.getInstance();\nnewCalendar.setTime(parsed);\n</code></pre>\n\n<p>outputs:</p>\n\n<blockquote>\n <p>parsed date: Mon Oct 27 11:33:29 EDT 2008</p>\n</blockquote>\n\n<p>which technically is correct, since my system timezone is EDT / UTC minus four hours (which is three hours ahead of yours). If you express time as the number of milliseconds since January 1, 1970, 00:00:00 GMT (which is how the <code>Date</code> object stores it's date/time), then these date/times are equal, it's just the TimeZone that is different.</p>\n\n<p>Your issue is really <em>How do I convert a Date/Calendar into my timezone?</em> For that, take a look at my response to the previous question <a href=\"https://stackoverflow.com/questions/230126/how-to-handle-calendar-timezones-using-java#230383\">How to handle calendar TimeZones using Java?</a></p>\n" }, { "answer_id": 67472622, "author": "Arvind Kumar Avinash", "author_id": 10819573, "author_profile": "https://Stackoverflow.com/users/10819573", "pm_score": 2, "selected": false, "text": "<h1><em>java.time</em></h1>\n<p><strong>Solution using <code>java.time</code>, the <a href=\"https://www.oracle.com/technical-resources/articles/java/jf14-date-time.html\" rel=\"nofollow noreferrer\">modern date-time API</a>:</strong></p>\n<p>The modern date-time API offers <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/OffsetDateTime.html\" rel=\"nofollow noreferrer\"><code>OffsetDateTime</code></a> to represent a date-time object with a timezone offset. It can be converted to <a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html\" rel=\"nofollow noreferrer\"><code>Instant</code></a> which represents an instantaneous point on the timeline. An <code>Instant</code> is independent of any timezone i.e. it has a timezone offset of <code>+00:00</code> hours, designated as <code>Z</code> in the <a href=\"https://en.wikipedia.org/wiki/ISO_8601#Time_zone_designators\" rel=\"nofollow noreferrer\">ISO 8601</a> standards.</p>\n<p><a href=\"https://docs.oracle.com/javase/8/docs/api/java/time/Instant.html#toEpochMilli--\" rel=\"nofollow noreferrer\"><code>Instant#toEpochMilli</code></a> converts this instant to the number of milliseconds from the epoch of 1970-01-01T00:00:00Z. This value can be set into an object of <code>GregorianCalendar</code> which will then represent the same moment.</p>\n<p><strong>Demo:</strong></p>\n<pre><code>import java.time.Instant;\nimport java.time.OffsetDateTime;\nimport java.time.format.DateTimeFormatter;\nimport java.util.Calendar;\nimport java.util.GregorianCalendar;\nimport java.util.Locale;\n\npublic class Main {\n public static void main(String[] args) {\n String strDateTime = &quot;Mon, 27 Oct 2008 08:33:29 -0700&quot;;\n OffsetDateTime odt = OffsetDateTime.parse(strDateTime, DateTimeFormatter.RFC_1123_DATE_TIME);\n System.out.println(odt);\n \n // In case you want a time zone neutral object, convert to Instant\n Instant instant = odt.toInstant();\n System.out.println(instant);\n \n // Edit: If the requirement is a GregorianCalendar having the offset from\n // the string — typically for an old API not yet upgraded to java.time: \n ZonedDateTime zdt = ZonedDateTime.parse(strDateTime, DateTimeFormatter.RFC_1123_DATE_TIME);\n GregorianCalendar gc = GregorianCalendar.from(zdt);\n \n System.out.println(&quot;As Date: &quot; + gc.getTime());\n System.out.println(&quot;Time zone ID: &quot; + gc.getTimeZone().getID());\n System.out.println(&quot;Hour of day: &quot; + gc.get(Calendar.HOUR_OF_DAY));\n // ...\n }\n}\n</code></pre>\n<p><strong>Output:</strong></p>\n<pre><code>2008-10-27T08:33:29-07:00\n2008-10-27T15:33:29Z\nAs Date: Mon Oct 27 15:33:29 GMT 2008\nTime zone ID: GMT-07:00\nHour of day: 8\n</code></pre>\n<p>Calling <code>getTime()</code> on the <code>GregorianCalendar</code> converts to a <code>Date</code> (another old and error-prone class) which doesn’t have a time zone, so the offset is lost. Printing the time zone ID and the hour of day demonstrates that both offset and time of day are preserved in the <code>GregorianCalendar</code>.</p>\n<p>Learn more about the modern date-time API from <strong><a href=\"https://docs.oracle.com/javase/tutorial/datetime/index.html\" rel=\"nofollow noreferrer\">Trail: Date Time</a></strong>.</p>\n<hr />\n<p><sup>* For any reason, if you have to stick to Java 6 or Java 7, you can use <a href=\"http://www.threeten.org/threetenbp/\" rel=\"nofollow noreferrer\"><em><strong>ThreeTen-Backport</strong></em></a> which backports most of the <em>java.time</em> functionality to Java 6 &amp; 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check <a href=\"https://developer.android.com/studio/write/java8-support-table\" rel=\"nofollow noreferrer\">Java 8+ APIs available through desugaring</a> and <a href=\"https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project\">How to use ThreeTenABP in Android Project</a>.\n</sup></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3105/" ]
I have a string from an email header, like `Date: Mon, 27 Oct 2008 08:33:29 -0700`. What I need is an instance of GregorianCalendar, that will represent the same moment. As easy as that -- how do I do it? And for the fastest ones -- this is **not** going to work properly: ``` SimpleDateFormat format = ... // whatever you want Date date = format.parse(myString) GregorianCalendar calendar = new GregorianCalendar(); calendar.setTime(date) ``` because it will normalize the timezone to UTC (or your local machine time, depending on Java version). What I need is calendar.getTimeZone().getRawOffset() to return `-7 * milisInAnHour`.
I'd recommend looking into the Joda Time library, if that's an option. I'm normally against using a third-party library when the core platform provides similar functionality, but I made this an exception because the author of Joda Time is also behind JSR310, and Joda Time is basically going to be rolled into Java 7 eventually. <http://joda-time.sourceforge.net/> So anyway, if Joda Time is an option, something like this *should* work: ``` DateTimeFormatter formatter = DateTimeFormat.forPattern("your pattern").withOffsetParsed(); DateTime dateTime = formatter.parseDateTime("your input"); GregorianCalendar cal = dateTime.toGregorianCalendar(); ``` I hope this helps.
240,531
<p>I have a weird date rounding problem that hopefully someone can solve. My client uses a work week that runs from Monday through Sunday. Sunday's date is considered the end of the week, and is used to identify all records entered in a particular week (so anything entered last week would have a WEEKDATE value of '10/26/2008', which is Sunday's date).</p> <p>One little twist is that users enter records for the previous week up until 11 AM on the Monday of the current week.</p> <p>So I need a function that starts with DateTime.Now and returns the week-ending date (no time part) according to the rules above. Thanks for your help. I have a solution that works, but I'm too embarassed to post it.</p> <p>Oh, and I can't use LINQ.</p>
[ { "answer_id": 240560, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": true, "text": "<pre><code>public DateTime WeekNum(DateTime now)\n{\n DateTime NewNow = now.AddHours(-11).AddDays(6);\n\n return (NewNow.AddDays(- (int) NewNow.DayOfWeek).Date);\n}\n\npublic void Code(params string[] args)\n{\n\n Console.WriteLine(WeekNum(DateTime.Now)); \n Console.WriteLine(WeekNum(new DateTime(2008,10,27, 10, 00, 00)));\n Console.WriteLine(WeekNum(new DateTime(2008,10,27, 12, 00, 00)));\n Console.WriteLine(WeekNum(new DateTime(2008,10,28)));\n Console.WriteLine(WeekNum(new DateTime(2008,10,25)));\n\n\n}\n</code></pre>\n\n<p>You may hard-code DateTime.Now instead of passing a DateTime object. It just made testing easier this way.</p>\n" }, { "answer_id": 240605, "author": "Rob", "author_id": 2595, "author_profile": "https://Stackoverflow.com/users/2595", "pm_score": 2, "selected": false, "text": "<p>This passes for me as well:</p>\n\n<pre><code>[Test]\npublic void Test()\n{\n DateTime sunday = DateTime.Parse(\"10/26/2008\");\n DateTime nextSunday = DateTime.Parse(\"11/2/2008\");\n\n Assert.AreEqual(sunday, GetSunday(DateTime.Parse(\"10/21/2008\")));\n Assert.AreEqual(sunday, GetSunday(DateTime.Parse(\"10/22/2008\")));\n Assert.AreEqual(sunday, GetSunday(DateTime.Parse(\"10/23/2008\")));\n Assert.AreEqual(sunday, GetSunday(DateTime.Parse(\"10/24/2008\")));\n Assert.AreEqual(sunday, GetSunday(DateTime.Parse(\"10/25/2008\")));\n Assert.AreEqual(sunday, GetSunday(DateTime.Parse(\"10/26/2008\")));\n Assert.AreEqual(sunday, GetSunday(DateTime.Parse(\"10/27/2008 10:59 AM\")));\n Assert.AreEqual(nextSunday, GetSunday(DateTime.Parse(\"10/27/2008 11:00 AM\")));\n}\n\nprivate DateTime GetSunday(DateTime date)\n{\n if (date.DayOfWeek == DayOfWeek.Monday &amp;&amp; date.Hour &lt; 11)\n return date.Date.AddDays(-1);\n\n while (date.DayOfWeek != DayOfWeek.Sunday)\n date = date.AddDays(1);\n\n return date.Date;\n}\n</code></pre>\n" }, { "answer_id": 240782, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I've used these extensions with great success:</p>\n\n<p><a href=\"http://www.codeplex.com/DateTimeExtensions\" rel=\"nofollow noreferrer\">http://www.codeplex.com/DateTimeExtensions</a></p>\n" }, { "answer_id": 240940, "author": "Dan Finucane", "author_id": 30026, "author_profile": "https://Stackoverflow.com/users/30026", "pm_score": 1, "selected": false, "text": "<pre><code>DateTime GetMidnightFollowingSunday()\n{\n DateTime now = DateTime.Now;\n return now.AddDays(7 - (int)now.DayOfWeek).Date;\n}\n</code></pre>\n\n<p>If you need to start the new week after 11AM on Monday morning just subtract 11 hours from now but then it probably makes sense to name the method something else.</p>\n\n<pre><code>DateTime GetRecordDate()\n{\n DateTime nowMinusOffset = DateTime.Now.AddHours(-11);\n return nowMinusOffset.AddDays(7-(int)nowMinusOffset.DayOfWeek).Date;\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14606/" ]
I have a weird date rounding problem that hopefully someone can solve. My client uses a work week that runs from Monday through Sunday. Sunday's date is considered the end of the week, and is used to identify all records entered in a particular week (so anything entered last week would have a WEEKDATE value of '10/26/2008', which is Sunday's date). One little twist is that users enter records for the previous week up until 11 AM on the Monday of the current week. So I need a function that starts with DateTime.Now and returns the week-ending date (no time part) according to the rules above. Thanks for your help. I have a solution that works, but I'm too embarassed to post it. Oh, and I can't use LINQ.
``` public DateTime WeekNum(DateTime now) { DateTime NewNow = now.AddHours(-11).AddDays(6); return (NewNow.AddDays(- (int) NewNow.DayOfWeek).Date); } public void Code(params string[] args) { Console.WriteLine(WeekNum(DateTime.Now)); Console.WriteLine(WeekNum(new DateTime(2008,10,27, 10, 00, 00))); Console.WriteLine(WeekNum(new DateTime(2008,10,27, 12, 00, 00))); Console.WriteLine(WeekNum(new DateTime(2008,10,28))); Console.WriteLine(WeekNum(new DateTime(2008,10,25))); } ``` You may hard-code DateTime.Now instead of passing a DateTime object. It just made testing easier this way.
240,544
<p>I have the following rails migration:</p> <pre><code>create_table :articles do |t| t.integer :user_id, :allow_null =&gt; false t.integer :genre_id, :allow_null =&gt; false t.string :url, :limit =&gt; 255, :allow_null =&gt; false t.string :title, :limit =&gt; 60, :allow_null =&gt; false t.text :summary, :limit =&gt; 350, :allow_null =&gt; false t.integer :votes_count, :default =&gt; 0 t.datetime :published_at, :default =&gt; nil t.timestamps end </code></pre> <p>All the fields that are "NOT NULL" are validated in the model first, so I'm wondering if I need to bother having allow_null in the migration? I'm not sure what benefits "NOT NULL" gives to the database, if any.</p>
[ { "answer_id": 240556, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 5, "selected": true, "text": "<p>Not much if you mean in terms of performance or storage efficiency. However, it's just good practice to push as many of your low-level constraints into the database layer. For one thing, it guarantees that a subtle bug in Rails isn't going to lead to some randomly <code>NULL</code> data in a not-null field. Likewise, if you ever run another app against the same database, it will be extremely helpful to have the constraints in a central place for maintenance and to avoid duplication.</p>\n" }, { "answer_id": 240642, "author": "Andy Lester", "author_id": 8454, "author_profile": "https://Stackoverflow.com/users/8454", "pm_score": 2, "selected": false, "text": "<p>NOT NULL is one more thing where the computer can keep an eye on you and keep you from making mistakes.</p>\n" }, { "answer_id": 240759, "author": "Gene T", "author_id": 413049, "author_profile": "https://Stackoverflow.com/users/413049", "pm_score": 1, "selected": false, "text": "<p>This doesn't seemt o affect mySQL, but you should be aware of 2 recently fixed migration issues (one when you don't specify default)</p>\n\n<p><a href=\"http://blog.codefront.net/2008/05/04/living-on-the-edge-of-rails-19-change_table-for-migrations-and-more/\" rel=\"nofollow noreferrer\">http://blog.codefront.net/2008/05/04/living-on-the-edge-of-rails-19-change_table-for-migrations-and-more/</a></p>\n\n<p><a href=\"http://antoniocangiano.com/2008/07/14/a-close-look-at-three-rails-21-bugs/\" rel=\"nofollow noreferrer\">http://antoniocangiano.com/2008/07/14/a-close-look-at-three-rails-21-bugs/</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31810/" ]
I have the following rails migration: ``` create_table :articles do |t| t.integer :user_id, :allow_null => false t.integer :genre_id, :allow_null => false t.string :url, :limit => 255, :allow_null => false t.string :title, :limit => 60, :allow_null => false t.text :summary, :limit => 350, :allow_null => false t.integer :votes_count, :default => 0 t.datetime :published_at, :default => nil t.timestamps end ``` All the fields that are "NOT NULL" are validated in the model first, so I'm wondering if I need to bother having allow\_null in the migration? I'm not sure what benefits "NOT NULL" gives to the database, if any.
Not much if you mean in terms of performance or storage efficiency. However, it's just good practice to push as many of your low-level constraints into the database layer. For one thing, it guarantees that a subtle bug in Rails isn't going to lead to some randomly `NULL` data in a not-null field. Likewise, if you ever run another app against the same database, it will be extremely helpful to have the constraints in a central place for maintenance and to avoid duplication.
240,546
<p>Is there a good way to remove HTML from a Java string? A simple regex like</p> <pre class="lang-js prettyprint-override"><code>replaceAll(&quot;\\&lt;.*?&gt;&quot;, &quot;&quot;) </code></pre> <p>will work, but some things like <code>&amp;amp;</code> won't be converted correctly and non-HTML between the two angle brackets will be removed (i.e. the <code>.*?</code> in the regex will disappear).</p>
[ { "answer_id": 240630, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 7, "selected": false, "text": "<p>If the user enters <code>&lt;b&gt;hey!&lt;/b&gt;</code>, do you want to display <code>&lt;b&gt;hey!&lt;/b&gt;</code> or <code>hey!</code>? If the first, escape less-thans, and html-encode ampersands (and optionally quotes) and you're fine. A modification to your code to implement the second option would be:</p>\n\n<pre><code>replaceAll(\"\\\\&lt;[^&gt;]*&gt;\",\"\")\n</code></pre>\n\n<p>but you will run into issues if the user enters something malformed, like <code>&lt;bhey!&lt;/b&gt;</code>.</p>\n\n<p>You can also check out <a href=\"http://jtidy.sourceforge.net/\" rel=\"noreferrer\">JTidy</a> which will parse \"dirty\" html input, and should give you a way to remove the tags, keeping the text.</p>\n\n<p>The problem with trying to strip html is that browsers have very lenient parsers, more lenient than any library you can find will, so even if you do your best to strip all tags (using the replace method above, a DOM library, or JTidy), you will <em>still</em> need to make sure to encode any remaining HTML special characters to keep your output safe.</p>\n" }, { "answer_id": 240636, "author": "Tim Howland", "author_id": 4276, "author_profile": "https://Stackoverflow.com/users/4276", "pm_score": 4, "selected": false, "text": "<p>HTML Escaping is really hard to do right- I'd definitely suggest using library code to do this, as it's a lot more subtle than you'd think. Check out Apache's <a href=\"http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/StringEscapeUtils.html\" rel=\"nofollow noreferrer\">StringEscapeUtils</a> for a pretty good library for handling this in Java.</p>\n" }, { "answer_id": 241757, "author": "foxy", "author_id": 30119, "author_profile": "https://Stackoverflow.com/users/30119", "pm_score": 3, "selected": false, "text": "<p>You might want to replace <code>&lt;br/&gt;</code> and <code>&lt;/p&gt;</code> tags with newlines before stripping the HTML to prevent it becoming an illegible mess as Tim suggests.</p>\n\n<p>The only way I can think of removing HTML tags but leaving non-HTML between angle brackets would be check against a <a href=\"http://www.w3schools.com/tags/default.asp\" rel=\"noreferrer\">list of HTML tags</a>. Something along these lines...</p>\n\n<pre><code>replaceAll(\"\\\\&lt;[\\s]*tag[^&gt;]*&gt;\",\"\")\n</code></pre>\n\n<p>Then HTML-decode special characters such as <code>&amp;amp;</code>. The result should not be considered to be sanitized.</p>\n" }, { "answer_id": 454511, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>It sounds like you want to go from HTML to plain text.<br>\nIf that is the case look at www.htmlparser.org. Here is an example that strips all the tags out from the html file found at a URL.<br>\nIt makes use of <em>org.htmlparser.beans.StringBean</em>.</p>\n\n<pre><code>static public String getUrlContentsAsText(String url) {\n String content = \"\";\n StringBean stringBean = new StringBean();\n stringBean.setURL(url);\n content = stringBean.getStrings();\n return content;\n}\n</code></pre>\n" }, { "answer_id": 455196, "author": "RealHowTo", "author_id": 25122, "author_profile": "https://Stackoverflow.com/users/25122", "pm_score": 5, "selected": false, "text": "<p>Another way is to use <em>javax.swing.text.html.HTMLEditorKit</em> to extract the text.</p>\n\n<pre><code>import java.io.*;\nimport javax.swing.text.html.*;\nimport javax.swing.text.html.parser.*;\n\npublic class Html2Text extends HTMLEditorKit.ParserCallback {\n StringBuffer s;\n\n public Html2Text() {\n }\n\n public void parse(Reader in) throws IOException {\n s = new StringBuffer();\n ParserDelegator delegator = new ParserDelegator();\n // the third parameter is TRUE to ignore charset directive\n delegator.parse(in, this, Boolean.TRUE);\n }\n\n public void handleText(char[] text, int pos) {\n s.append(text);\n }\n\n public String getText() {\n return s.toString();\n }\n\n public static void main(String[] args) {\n try {\n // the HTML to convert\n FileReader in = new FileReader(\"java-new.html\");\n Html2Text parser = new Html2Text();\n parser.parse(in);\n in.close();\n System.out.println(parser.getText());\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n}\n</code></pre>\n\n<p>ref : <a href=\"http://www.rgagnon.com/javadetails/java-0424.html\" rel=\"noreferrer\">Remove HTML tags from a file to extract only the TEXT</a> </p>\n" }, { "answer_id": 2702056, "author": "Mike", "author_id": 324610, "author_profile": "https://Stackoverflow.com/users/324610", "pm_score": 3, "selected": false, "text": "<p>Here's a lightly more fleshed out update to try to handle some formatting for breaks and lists. I used Amaya's output as a guide. </p>\n\n<pre><code>import java.io.IOException;\nimport java.io.Reader;\nimport java.io.StringReader;\nimport java.util.Stack;\nimport java.util.logging.Logger;\n\nimport javax.swing.text.MutableAttributeSet;\nimport javax.swing.text.html.HTML;\nimport javax.swing.text.html.HTMLEditorKit;\nimport javax.swing.text.html.parser.ParserDelegator;\n\npublic class HTML2Text extends HTMLEditorKit.ParserCallback {\n private static final Logger log = Logger\n .getLogger(Logger.GLOBAL_LOGGER_NAME);\n\n private StringBuffer stringBuffer;\n\n private Stack&lt;IndexType&gt; indentStack;\n\n public static class IndexType {\n public String type;\n public int counter; // used for ordered lists\n\n public IndexType(String type) {\n this.type = type;\n counter = 0;\n }\n }\n\n public HTML2Text() {\n stringBuffer = new StringBuffer();\n indentStack = new Stack&lt;IndexType&gt;();\n }\n\n public static String convert(String html) {\n HTML2Text parser = new HTML2Text();\n Reader in = new StringReader(html);\n try {\n // the HTML to convert\n parser.parse(in);\n } catch (Exception e) {\n log.severe(e.getMessage());\n } finally {\n try {\n in.close();\n } catch (IOException ioe) {\n // this should never happen\n }\n }\n return parser.getText();\n }\n\n public void parse(Reader in) throws IOException {\n ParserDelegator delegator = new ParserDelegator();\n // the third parameter is TRUE to ignore charset directive\n delegator.parse(in, this, Boolean.TRUE);\n }\n\n public void handleStartTag(HTML.Tag t, MutableAttributeSet a, int pos) {\n log.info(\"StartTag:\" + t.toString());\n if (t.toString().equals(\"p\")) {\n if (stringBuffer.length() &gt; 0\n &amp;&amp; !stringBuffer.substring(stringBuffer.length() - 1)\n .equals(\"\\n\")) {\n newLine();\n }\n newLine();\n } else if (t.toString().equals(\"ol\")) {\n indentStack.push(new IndexType(\"ol\"));\n newLine();\n } else if (t.toString().equals(\"ul\")) {\n indentStack.push(new IndexType(\"ul\"));\n newLine();\n } else if (t.toString().equals(\"li\")) {\n IndexType parent = indentStack.peek();\n if (parent.type.equals(\"ol\")) {\n String numberString = \"\" + (++parent.counter) + \".\";\n stringBuffer.append(numberString);\n for (int i = 0; i &lt; (4 - numberString.length()); i++) {\n stringBuffer.append(\" \");\n }\n } else {\n stringBuffer.append(\"* \");\n }\n indentStack.push(new IndexType(\"li\"));\n } else if (t.toString().equals(\"dl\")) {\n newLine();\n } else if (t.toString().equals(\"dt\")) {\n newLine();\n } else if (t.toString().equals(\"dd\")) {\n indentStack.push(new IndexType(\"dd\"));\n newLine();\n }\n }\n\n private void newLine() {\n stringBuffer.append(\"\\n\");\n for (int i = 0; i &lt; indentStack.size(); i++) {\n stringBuffer.append(\" \");\n }\n }\n\n public void handleEndTag(HTML.Tag t, int pos) {\n log.info(\"EndTag:\" + t.toString());\n if (t.toString().equals(\"p\")) {\n newLine();\n } else if (t.toString().equals(\"ol\")) {\n indentStack.pop();\n ;\n newLine();\n } else if (t.toString().equals(\"ul\")) {\n indentStack.pop();\n ;\n newLine();\n } else if (t.toString().equals(\"li\")) {\n indentStack.pop();\n ;\n newLine();\n } else if (t.toString().equals(\"dd\")) {\n indentStack.pop();\n ;\n }\n }\n\n public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a, int pos) {\n log.info(\"SimpleTag:\" + t.toString());\n if (t.toString().equals(\"br\")) {\n newLine();\n }\n }\n\n public void handleText(char[] text, int pos) {\n log.info(\"Text:\" + new String(text));\n stringBuffer.append(text);\n }\n\n public String getText() {\n return stringBuffer.toString();\n }\n\n public static void main(String args[]) {\n String html = \"&lt;html&gt;&lt;body&gt;&lt;p&gt;paragraph at start&lt;/p&gt;hello&lt;br /&gt;What is happening?&lt;p&gt;this is a&lt;br /&gt;mutiline paragraph&lt;/p&gt;&lt;ol&gt; &lt;li&gt;This&lt;/li&gt; &lt;li&gt;is&lt;/li&gt; &lt;li&gt;an&lt;/li&gt; &lt;li&gt;ordered&lt;/li&gt; &lt;li&gt;list &lt;p&gt;with&lt;/p&gt; &lt;ul&gt; &lt;li&gt;another&lt;/li&gt; &lt;li&gt;list &lt;dl&gt; &lt;dt&gt;This&lt;/dt&gt; &lt;dt&gt;is&lt;/dt&gt; &lt;dd&gt;sdasd&lt;/dd&gt; &lt;dd&gt;sdasda&lt;/dd&gt; &lt;dd&gt;asda &lt;p&gt;aasdas&lt;/p&gt; &lt;/dd&gt; &lt;dd&gt;sdada&lt;/dd&gt; &lt;dt&gt;fsdfsdfsd&lt;/dt&gt; &lt;/dl&gt; &lt;dl&gt; &lt;dt&gt;vbcvcvbcvb&lt;/dt&gt; &lt;dt&gt;cvbcvbc&lt;/dt&gt; &lt;dd&gt;vbcbcvbcvb&lt;/dd&gt; &lt;dt&gt;cvbcv&lt;/dt&gt; &lt;dt&gt;&lt;/dt&gt; &lt;/dl&gt; &lt;dl&gt; &lt;dt&gt;&lt;/dt&gt; &lt;/dl&gt;&lt;/li&gt; &lt;li&gt;cool&lt;/li&gt; &lt;/ul&gt; &lt;p&gt;stuff&lt;/p&gt; &lt;/li&gt; &lt;li&gt;cool&lt;/li&gt;&lt;/ol&gt;&lt;p&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;\";\n System.out.println(convert(html));\n }\n}\n</code></pre>\n" }, { "answer_id": 3149645, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 10, "selected": true, "text": "<p>Use a HTML parser instead of regex. This is dead simple with <a href=\"http://jsoup.org\" rel=\"noreferrer\">Jsoup</a>.</p>\n<pre><code>public static String html2text(String html) {\n return Jsoup.parse(html).text();\n}\n</code></pre>\n<p>Jsoup also <a href=\"https://jsoup.org/cookbook/cleaning-html/whitelist-sanitizer\" rel=\"noreferrer\">supports</a> removing HTML tags against a customizable whitelist, which is very useful if you want to allow only e.g. <code>&lt;b&gt;</code>, <code>&lt;i&gt;</code> and <code>&lt;u&gt;</code>.</p>\n<h3>See also:</h3>\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags\">RegEx match open tags except XHTML self-contained tags</a></li>\n<li><a href=\"https://stackoverflow.com/questions/3152138/what-are-the-pros-and-cons-of-the-leading-java-html-parsers\">What are the pros and cons of the leading Java HTML parsers?</a></li>\n<li><a href=\"https://stackoverflow.com/questions/2658922/xss-prevention-in-jsp-servlet-web-application\">XSS prevention in JSP/Servlet web application</a></li>\n</ul>\n" }, { "answer_id": 3426610, "author": "rjha94", "author_id": 262376, "author_profile": "https://Stackoverflow.com/users/262376", "pm_score": 3, "selected": false, "text": "<p>One more way can be to use com.google.gdata.util.common.html.HtmlToText class \nlike </p>\n\n<pre><code>MyWriter.toConsole(HtmlToText.htmlToPlainText(htmlResponse));\n</code></pre>\n\n<p>This is not bullet proof code though and when I run it on wikipedia entries I am getting style info also. However I believe for small/simple jobs this would be effective.</p>\n" }, { "answer_id": 3472783, "author": "dfrankow", "author_id": 34935, "author_profile": "https://Stackoverflow.com/users/34935", "pm_score": 3, "selected": false, "text": "<p>The accepted answer did not work for me for the test case I indicated: the result of \"a &lt; b or b > c\" is \"a b or b > c\".</p>\n\n<p>So, I used TagSoup instead. Here's a shot that worked for my test case (and a couple of others):</p>\n\n<pre><code>import java.io.IOException;\nimport java.io.StringReader;\nimport java.util.logging.Logger;\n\nimport org.ccil.cowan.tagsoup.Parser;\nimport org.xml.sax.Attributes;\nimport org.xml.sax.ContentHandler;\nimport org.xml.sax.InputSource;\nimport org.xml.sax.Locator;\nimport org.xml.sax.SAXException;\nimport org.xml.sax.XMLReader;\n\n/**\n * Take HTML and give back the text part while dropping the HTML tags.\n *\n * There is some risk that using TagSoup means we'll permute non-HTML text.\n * However, it seems to work the best so far in test cases.\n *\n * @author dan\n * @see &lt;a href=\"http://home.ccil.org/~cowan/XML/tagsoup/\"&gt;TagSoup&lt;/a&gt; \n */\npublic class Html2Text2 implements ContentHandler {\nprivate StringBuffer sb;\n\npublic Html2Text2() {\n}\n\npublic void parse(String str) throws IOException, SAXException {\n XMLReader reader = new Parser();\n reader.setContentHandler(this);\n sb = new StringBuffer();\n reader.parse(new InputSource(new StringReader(str)));\n}\n\npublic String getText() {\n return sb.toString();\n}\n\n@Override\npublic void characters(char[] ch, int start, int length)\n throws SAXException {\n for (int idx = 0; idx &lt; length; idx++) {\n sb.append(ch[idx+start]);\n }\n}\n\n@Override\npublic void ignorableWhitespace(char[] ch, int start, int length)\n throws SAXException {\n sb.append(ch);\n}\n\n// The methods below do not contribute to the text\n@Override\npublic void endDocument() throws SAXException {\n}\n\n@Override\npublic void endElement(String uri, String localName, String qName)\n throws SAXException {\n}\n\n@Override\npublic void endPrefixMapping(String prefix) throws SAXException {\n}\n\n\n@Override\npublic void processingInstruction(String target, String data)\n throws SAXException {\n}\n\n@Override\npublic void setDocumentLocator(Locator locator) {\n}\n\n@Override\npublic void skippedEntity(String name) throws SAXException {\n}\n\n@Override\npublic void startDocument() throws SAXException {\n}\n\n@Override\npublic void startElement(String uri, String localName, String qName,\n Attributes atts) throws SAXException {\n}\n\n@Override\npublic void startPrefixMapping(String prefix, String uri)\n throws SAXException {\n}\n}\n</code></pre>\n" }, { "answer_id": 4095615, "author": "Serge", "author_id": 395815, "author_profile": "https://Stackoverflow.com/users/395815", "pm_score": 5, "selected": false, "text": "<p>I think that the simpliest way to filter the html tags is:</p>\n\n<pre><code>private static final Pattern REMOVE_TAGS = Pattern.compile(\"&lt;.+?&gt;\");\n\npublic static String removeTags(String string) {\n if (string == null || string.length() == 0) {\n return string;\n }\n\n Matcher m = REMOVE_TAGS.matcher(string);\n return m.replaceAll(\"\");\n}\n</code></pre>\n" }, { "answer_id": 4200787, "author": "Rizwan", "author_id": 507112, "author_profile": "https://Stackoverflow.com/users/507112", "pm_score": -1, "selected": false, "text": "<p>you can simply make a method with multiple replaceAll() like</p>\n\n<pre><code>String RemoveTag(String html){\n html = html.replaceAll(\"\\\\&lt;.*?&gt;\",\"\")\n html = html.replaceAll(\"&amp;nbsp;\",\"\");\n html = html.replaceAll(\"&amp;amp;\".\"\");\n ----------\n ----------\n return html;\n}\n</code></pre>\n\n<p>Use this link for most common replacements you need:\n<a href=\"http://tunes.org/wiki/html_20special_20characters_20and_20symbols.html\" rel=\"nofollow\">http://tunes.org/wiki/html_20special_20characters_20and_20symbols.html</a></p>\n\n<p>It is simple but effective. I use this method first to remove the junk but not the very first line i.e replaceAll(\"\\&lt;.*?>\",\"\"), and later i use specific keywords to search for indexes and then use .substring(start, end) method to strip away unnecessary stuff. As this is more robust and you can pin point exactly what you need in the entire html page.</p>\n" }, { "answer_id": 6266528, "author": "rqualis", "author_id": 787614, "author_profile": "https://Stackoverflow.com/users/787614", "pm_score": 2, "selected": false, "text": "<p>I know this is old, but I was just working on a project that required me to filter HTML and this worked fine:</p>\n\n<pre><code>noHTMLString.replaceAll(\"\\\\&amp;.*?\\\\;\", \"\");\n</code></pre>\n\n<p>instead of this:</p>\n\n<pre><code>html = html.replaceAll(\"&amp;nbsp;\",\"\");\nhtml = html.replaceAll(\"&amp;amp;\".\"\");\n</code></pre>\n" }, { "answer_id": 6385950, "author": "Ken Goodridge", "author_id": 233878, "author_profile": "https://Stackoverflow.com/users/233878", "pm_score": 8, "selected": false, "text": "<p>If you're writing for <strong>Android</strong> you can do this...</p>\n<p>androidx.core.text.HtmlCompat.fromHtml(instruction,HtmlCompat.FROM_HTML_MODE_LEGACY).toString()</p>\n" }, { "answer_id": 6962693, "author": "Josh", "author_id": 881338, "author_profile": "https://Stackoverflow.com/users/881338", "pm_score": 4, "selected": false, "text": "<p>Also very simple using <a href=\"http://jericho.htmlparser.net/docs/index.html\" rel=\"noreferrer\">Jericho</a>, and you can retain some of the formatting (line breaks and links, for example).</p>\n\n<pre><code> Source htmlSource = new Source(htmlText);\n Segment htmlSeg = new Segment(htmlSource, 0, htmlSource.length());\n Renderer htmlRend = new Renderer(htmlSeg);\n System.out.println(htmlRend.toString());\n</code></pre>\n" }, { "answer_id": 6997978, "author": "Alexander", "author_id": 698723, "author_profile": "https://Stackoverflow.com/users/698723", "pm_score": 0, "selected": false, "text": "<p>My 5 cents:</p>\n\n<pre><code>String[] temp = yourString.split(\"&amp;amp;\");\nString tmp = \"\";\nif (temp.length &gt; 1) {\n\n for (int i = 0; i &lt; temp.length; i++) {\n tmp += temp[i] + \"&amp;\";\n }\n yourString = tmp.substring(0, tmp.length() - 1);\n}\n</code></pre>\n" }, { "answer_id": 7784001, "author": "blackStar", "author_id": 941748, "author_profile": "https://Stackoverflow.com/users/941748", "pm_score": 2, "selected": false, "text": "<p>Here is another way to do it:</p>\n\n<pre><code>public static String removeHTML(String input) {\n int i = 0;\n String[] str = input.split(\"\");\n\n String s = \"\";\n boolean inTag = false;\n\n for (i = input.indexOf(\"&lt;\"); i &lt; input.indexOf(\"&gt;\"); i++) {\n inTag = true;\n }\n if (!inTag) {\n for (i = 0; i &lt; str.length; i++) {\n s = s + str[i];\n }\n }\n return s;\n}\n</code></pre>\n" }, { "answer_id": 12259801, "author": "Maksim Sorokin", "author_id": 417297, "author_profile": "https://Stackoverflow.com/users/417297", "pm_score": 2, "selected": false, "text": "<p>One could also use <a href=\"http://tika.apache.org/\" rel=\"nofollow\">Apache Tika</a> for this purpose. By default it preserves whitespaces from the stripped html, which may be desired in certain situations:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>InputStream htmlInputStream = ..\nHtmlParser htmlParser = new HtmlParser();\nHtmlContentHandler htmlContentHandler = new HtmlContentHandler();\nhtmlParser.parse(htmlInputStream, htmlContentHandler, new Metadata())\nSystem.out.println(htmlContentHandler.getBodyText().trim())\n</code></pre>\n" }, { "answer_id": 16220579, "author": "surfealokesea", "author_id": 1773233, "author_profile": "https://Stackoverflow.com/users/1773233", "pm_score": 0, "selected": false, "text": "<p>To get <strong>formateed plain html text</strong> you can do that:</p>\n\n<pre><code>String BR_ESCAPED = \"&amp;lt;br/&amp;gt;\";\nElement el=Jsoup.parse(html).select(\"body\");\nel.select(\"br\").append(BR_ESCAPED);\nel.select(\"p\").append(BR_ESCAPED+BR_ESCAPED);\nel.select(\"h1\").append(BR_ESCAPED+BR_ESCAPED);\nel.select(\"h2\").append(BR_ESCAPED+BR_ESCAPED);\nel.select(\"h3\").append(BR_ESCAPED+BR_ESCAPED);\nel.select(\"h4\").append(BR_ESCAPED+BR_ESCAPED);\nel.select(\"h5\").append(BR_ESCAPED+BR_ESCAPED);\nString nodeValue=el.text();\nnodeValue=nodeValue.replaceAll(BR_ESCAPED, \"&lt;br/&gt;\");\nnodeValue=nodeValue.replaceAll(\"(\\\\s*&lt;br[^&gt;]*&gt;){3,}\", \"&lt;br/&gt;&lt;br/&gt;\");\n</code></pre>\n\n<p>To get <strong>formateed plain text</strong> change &lt;br/&gt; by \\n and change last line by:</p>\n\n<pre><code>nodeValue=nodeValue.replaceAll(\"(\\\\s*\\n){3,}\", \"&lt;br/&gt;&lt;br/&gt;\");\n</code></pre>\n" }, { "answer_id": 21838532, "author": "Stephan", "author_id": 363573, "author_profile": "https://Stackoverflow.com/users/363573", "pm_score": 3, "selected": false, "text": "<p>Alternatively, one can use <a href=\"http://htmlcleaner.sourceforge.net/index.php\" rel=\"noreferrer\">HtmlCleaner</a>:</p>\n\n<pre><code>private CharSequence removeHtmlFrom(String html) {\n return new HtmlCleaner().clean(html).getText();\n}\n</code></pre>\n" }, { "answer_id": 23622675, "author": "Damien", "author_id": 271887, "author_profile": "https://Stackoverflow.com/users/271887", "pm_score": 4, "selected": false, "text": "<p>The accepted answer of doing simply <code>Jsoup.parse(html).text()</code> has 2 potential issues (with JSoup 1.7.3):</p>\n\n<ul>\n<li>It removes line breaks from the text</li>\n<li>It converts text <code>&amp;lt;script&amp;gt;</code> into <code>&lt;script&gt;</code></li>\n</ul>\n\n<p>If you use this to protect against XSS, this is a bit annoying. Here is my best shot at an improved solution, using both JSoup and Apache StringEscapeUtils:</p>\n\n<pre><code>// breaks multi-level of escaping, preventing &amp;amp;lt;script&amp;amp;gt; to be rendered as &lt;script&gt;\nString replace = input.replace(\"&amp;amp;\", \"\");\n// decode any encoded html, preventing &amp;lt;script&amp;gt; to be rendered as &lt;script&gt;\nString html = StringEscapeUtils.unescapeHtml(replace);\n// remove all html tags, but maintain line breaks\nString clean = Jsoup.clean(html, \"\", Whitelist.none(), new Document.OutputSettings().prettyPrint(false));\n// decode html again to convert character entities back into text\nreturn StringEscapeUtils.unescapeHtml(clean);\n</code></pre>\n\n<p>Note that the last step is because I need to use the output as plain text. If you need only HTML output then you should be able to remove it.</p>\n\n<p>And here is a bunch of test cases (input to output):</p>\n\n<pre><code>{\"regular string\", \"regular string\"},\n{\"&lt;a href=\\\"link\\\"&gt;A link&lt;/a&gt;\", \"A link\"},\n{\"&lt;script src=\\\"http://evil.url.com\\\"/&gt;\", \"\"},\n{\"&amp;lt;script&amp;gt;\", \"\"},\n{\"&amp;amp;lt;script&amp;amp;gt;\", \"lt;scriptgt;\"}, // best effort\n{\"\\\" ' &gt; &lt; \\n \\\\ é å à ü and &amp; preserved\", \"\\\" ' &gt; &lt; \\n \\\\ é å à ü and &amp; preserved\"}\n</code></pre>\n\n<p>If you find a way to make it better, please let me know.</p>\n" }, { "answer_id": 25648860, "author": "Satya Prakash", "author_id": 2934974, "author_profile": "https://Stackoverflow.com/users/2934974", "pm_score": -1, "selected": false, "text": "<p>Remove HTML tags from string. Somewhere we need to parse some string which is received by some responses like Httpresponse from the server.</p>\n\n<p>So we need to parse it.</p>\n\n<p>Here I will show how to remove html tags from string.</p>\n\n<pre><code> // sample text with tags\n\n string str = \"&lt;html&gt;&lt;head&gt;sdfkashf sdf&lt;/head&gt;&lt;body&gt;sdfasdf&lt;/body&gt;&lt;/html&gt;\";\n\n\n\n // regex which match tags\n\n System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex(\"&lt;[^&gt;]*&gt;\");\n\n\n\n // replace all matches with empty strin\n\n str = rx.Replace(str, \"\");\n\n\n\n //now str contains string without html tags\n</code></pre>\n" }, { "answer_id": 30022636, "author": "Ameen Maheen", "author_id": 3836137, "author_profile": "https://Stackoverflow.com/users/3836137", "pm_score": 4, "selected": false, "text": "<p>On Android, try this:</p>\n\n<pre><code>String result = Html.fromHtml(html).toString();\n</code></pre>\n" }, { "answer_id": 32406442, "author": "RobMen", "author_id": 5302242, "author_profile": "https://Stackoverflow.com/users/5302242", "pm_score": 1, "selected": false, "text": "<p>One way to retain new-line info with JSoup is to precede all new line tags with some dummy string, execute JSoup and replace dummy string with \"\\n\".</p>\n\n<pre><code>String html = \"&lt;p&gt;Line one&lt;/p&gt;&lt;p&gt;Line two&lt;/p&gt;Line three&lt;br/&gt;etc.\";\nString NEW_LINE_MARK = \"NEWLINESTART1234567890NEWLINEEND\";\nfor (String tag: new String[]{\"&lt;/p&gt;\",\"&lt;br/&gt;\",\"&lt;/h1&gt;\",\"&lt;/h2&gt;\",\"&lt;/h3&gt;\",\"&lt;/h4&gt;\",\"&lt;/h5&gt;\",\"&lt;/h6&gt;\",\"&lt;/li&gt;\"}) {\n html = html.replace(tag, NEW_LINE_MARK+tag);\n}\n\nString text = Jsoup.parse(html).text();\n\ntext = text.replace(NEW_LINE_MARK + \" \", \"\\n\\n\");\ntext = text.replace(NEW_LINE_MARK, \"\\n\\n\");\n</code></pre>\n" }, { "answer_id": 33870804, "author": "IntelliJ Amiya", "author_id": 3395198, "author_profile": "https://Stackoverflow.com/users/3395198", "pm_score": 3, "selected": false, "text": "<p>Use <strong><code>Html.fromHtml</code></strong></p>\n\n<p><strong><em>HTML</em></strong> Tags are</p>\n\n<pre><code>&lt;a href=”…”&gt; &lt;b&gt;, &lt;big&gt;, &lt;blockquote&gt;, &lt;br&gt;, &lt;cite&gt;, &lt;dfn&gt;\n&lt;div align=”…”&gt;, &lt;em&gt;, &lt;font size=”…” color=”…” face=”…”&gt;\n&lt;h1&gt;, &lt;h2&gt;, &lt;h3&gt;, &lt;h4&gt;, &lt;h5&gt;, &lt;h6&gt;\n&lt;i&gt;, &lt;p&gt;, &lt;small&gt;\n&lt;strike&gt;, &lt;strong&gt;, &lt;sub&gt;, &lt;sup&gt;, &lt;tt&gt;, &lt;u&gt;\n</code></pre>\n\n<p>As per <strong><a href=\"http://developer.android.com/intl/es/reference/android/text/Html.html\" rel=\"noreferrer\">Android’s official Documentations</a></strong> any tags in the <strong>HTML</strong> will display as a generic replacement <strong>String</strong> which your program can then go through and replace with real <strong><em>strings</em></strong>.</p>\n\n<p><strong><code>Html.formHtml</code></strong> method takes an <strong><code>Html.TagHandler</code></strong> and an Html.ImageGetter as arguments as well as the text to parse.</p>\n\n<h2>Example</h2>\n\n<pre><code>String Str_Html=\" &lt;p&gt;This is about me text that the user can put into their profile&lt;/p&gt; \";\n</code></pre>\n\n<p>Then</p>\n\n<pre><code>Your_TextView_Obj.setText(Html.fromHtml(Str_Html).toString());\n</code></pre>\n\n<p>Output</p>\n\n<p><strong>This is about me text that the user can put into their profile</strong></p>\n" }, { "answer_id": 44845644, "author": "Sandeep1699", "author_id": 8237054, "author_profile": "https://Stackoverflow.com/users/8237054", "pm_score": 4, "selected": false, "text": "<p>This should work - </p>\n\n<p>use this</p>\n\n<pre><code> text.replaceAll('&lt;.*?&gt;' , \" \") -&gt; This will replace all the html tags with a space.\n</code></pre>\n\n<p>and this</p>\n\n<pre><code> text.replaceAll('&amp;.*?;' , \"\")-&gt; this will replace all the tags which starts with \"&amp;\" and ends with \";\" like &amp;nbsp;, &amp;amp;, &amp;gt; etc.\n</code></pre>\n" }, { "answer_id": 48461365, "author": "Guilherme Oliveira", "author_id": 8115060, "author_profile": "https://Stackoverflow.com/users/8115060", "pm_score": 1, "selected": false, "text": "<pre><code>classeString.replaceAll(\"\\\\&lt;(/?[^\\\\&gt;]+)\\\\&gt;\", \"\\\\ \").replaceAll(\"\\\\s+\", \" \").trim() \n</code></pre>\n" }, { "answer_id": 50942752, "author": "silentsudo", "author_id": 1752366, "author_profile": "https://Stackoverflow.com/users/1752366", "pm_score": 2, "selected": false, "text": "<p>Here is one more variant of how to replace all(HTML Tags | HTML Entities | Empty Space in HTML content)</p>\n\n<p><code>content.replaceAll(\"(&lt;.*?&gt;)|(&amp;.*?;)|([ ]{2,})\", \"\");</code> where content is a String.</p>\n" }, { "answer_id": 55413383, "author": "Anuraganu Punalur", "author_id": 9385470, "author_profile": "https://Stackoverflow.com/users/9385470", "pm_score": 3, "selected": false, "text": "<p><strong>You can simply use the Android's default HTML filter</strong></p>\n\n<pre><code> public String htmlToStringFilter(String textToFilter){\n\n return Html.fromHtml(textToFilter).toString();\n\n }\n</code></pre>\n\n<p>The above method will return the HTML filtered string for your input.</p>\n" }, { "answer_id": 62001289, "author": "Itay Sasson", "author_id": 13612863, "author_profile": "https://Stackoverflow.com/users/13612863", "pm_score": 0, "selected": false, "text": "<p>I know it is been a while since this question as been asked, but I found another solution, this is what worked for me:</p>\n\n<pre><code>Pattern REMOVE_TAGS = Pattern.compile(\"&lt;.+?&gt;\");\n Source source= new Source(htmlAsString);\n Matcher m = REMOVE_TAGS.matcher(sourceStep.getTextExtractor().toString());\n String clearedHtml= m.replaceAll(\"\");\n</code></pre>\n" }, { "answer_id": 62920964, "author": "Jared Beach", "author_id": 1834329, "author_profile": "https://Stackoverflow.com/users/1834329", "pm_score": 0, "selected": false, "text": "<p>Worth noting that if you're trying to accomplish this in a <a href=\"https://servicestack.net/\" rel=\"nofollow noreferrer\">Service Stack</a> project, it's already a built-in string extension</p>\n<pre><code>using ServiceStack.Text;\n// ...\n&quot;The &lt;b&gt;quick&lt;/b&gt; brown &lt;p&gt; fox &lt;/p&gt; jumps over the lazy dog&quot;.StripHtml();\n</code></pre>\n" }, { "answer_id": 63552068, "author": "Parker", "author_id": 2074605, "author_profile": "https://Stackoverflow.com/users/2074605", "pm_score": 0, "selected": false, "text": "<p>I often find that I only need to strip out comments and script elements. This has worked reliably for me for 15 years and can easily be extended to handle any element name in HTML or XML:</p>\n<pre><code>// delete all comments\nresponse = response.replaceAll(&quot;&lt;!--[^&gt;]*--&gt;&quot;, &quot;&quot;);\n// delete all script elements\nresponse = response.replaceAll(&quot;&lt;(script|SCRIPT)[^+]*?&gt;[^&gt;]*?&lt;(/script|SCRIPT)&gt;&quot;, &quot;&quot;);\n</code></pre>\n" }, { "answer_id": 63720307, "author": "jiamo", "author_id": 976371, "author_profile": "https://Stackoverflow.com/users/976371", "pm_score": 1, "selected": false, "text": "<p>Sometimes the html string come from xml with such <code>&amp;lt</code>. When using Jsoup we need parse it and then clean it.</p>\n<pre><code>Document doc = Jsoup.parse(htmlstrl);\nWhitelist wl = Whitelist.none();\nString plain = Jsoup.clean(doc.text(), wl);\n</code></pre>\n<p>While only using <code>Jsoup.parse(htmlstrl).text()</code> can't remove tags.</p>\n" }, { "answer_id": 63832019, "author": "Muneeb Ahmed", "author_id": 9533811, "author_profile": "https://Stackoverflow.com/users/9533811", "pm_score": 1, "selected": false, "text": "<p><strong>Try this for javascript:</strong></p>\n<pre class=\"lang-js prettyprint-override\"><code>const strippedString = htmlString.replace(/(&lt;([^&gt;]+)&gt;)/gi, &quot;&quot;);\nconsole.log(strippedString);\n</code></pre>\n" }, { "answer_id": 66425176, "author": "Arefe", "author_id": 2746110, "author_profile": "https://Stackoverflow.com/users/2746110", "pm_score": 1, "selected": false, "text": "<p>You can use this method to remove the HTML tags from the String,</p>\n<pre><code>public static String stripHtmlTags(String html) {\n\n return html.replaceAll(&quot;&lt;.*?&gt;&quot;, &quot;&quot;);\n\n}\n</code></pre>\n" }, { "answer_id": 69073444, "author": "Ahmad Nabeel Butt", "author_id": 11709551, "author_profile": "https://Stackoverflow.com/users/11709551", "pm_score": 0, "selected": false, "text": "<p>You can use this code to remove HTML tags including line breaks.</p>\n<pre><code>function remove_html_tags(html) {\n html = html.replace(/&lt;div&gt;/g, &quot;&quot;).replace(/&lt;\\/div&gt;/g, &quot;&lt;br&gt;&quot;);\n html = html.replace(/&lt;br&gt;/g, &quot;$br$&quot;);\n html = html.replace(/(?:\\r\\n|\\r|\\n)/g, '$br$');\n var tmp = document.createElement(&quot;DIV&quot;);\n tmp.innerHTML = html;\n html = tmp.textContent || tmp.innerText;\n html = html.replace(/\\$br\\$/g, &quot;\\n&quot;);\n return html;\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8973/" ]
Is there a good way to remove HTML from a Java string? A simple regex like ```js replaceAll("\\<.*?>", "") ``` will work, but some things like `&amp;` won't be converted correctly and non-HTML between the two angle brackets will be removed (i.e. the `.*?` in the regex will disappear).
Use a HTML parser instead of regex. This is dead simple with [Jsoup](http://jsoup.org). ``` public static String html2text(String html) { return Jsoup.parse(html).text(); } ``` Jsoup also [supports](https://jsoup.org/cookbook/cleaning-html/whitelist-sanitizer) removing HTML tags against a customizable whitelist, which is very useful if you want to allow only e.g. `<b>`, `<i>` and `<u>`. ### See also: * [RegEx match open tags except XHTML self-contained tags](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) * [What are the pros and cons of the leading Java HTML parsers?](https://stackoverflow.com/questions/3152138/what-are-the-pros-and-cons-of-the-leading-java-html-parsers) * [XSS prevention in JSP/Servlet web application](https://stackoverflow.com/questions/2658922/xss-prevention-in-jsp-servlet-web-application)
240,582
<p>I have tried the following two statements:</p> <ul> <li><code>SELECT col FROM db.tbl WHERE col (LIKE 'str1' OR LIKE 'str2') AND col2 = num</code> results in a syntax error</li> <li><code>SELECT col FROM db.tbl WHERE page LIKE ('str1' OR 'str2') AND col2 = num</code> results in "Truncated incorrect DOUBLE value: str1" and "Truncated incorrect DOUBLE value: str2" for what looks like every result. However, no results are actually returned.</li> </ul> <p>I figured one of the two statements would work, but they aren't.</p>
[ { "answer_id": 240585, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 7, "selected": true, "text": "<blockquote>\n<pre><code>SELECT col FROM db.tbl WHERE (col LIKE 'str1' OR col LIKE 'str2') AND col2 = num\n</code></pre>\n</blockquote>\n" }, { "answer_id": 240588, "author": "Elie", "author_id": 23249, "author_profile": "https://Stackoverflow.com/users/23249", "pm_score": 1, "selected": false, "text": "<p>try SELECT col FROM db.tbl WHERE (col LIKE 'str1' or col LIKE 'str2') AND col2 = num</p>\n" }, { "answer_id": 240589, "author": "Daniel Spiewak", "author_id": 9815, "author_profile": "https://Stackoverflow.com/users/9815", "pm_score": 2, "selected": false, "text": "<p>Think simple:</p>\n\n<pre><code>SELECT col FROM db.tbl WHERE (col LIKE 'str1' OR col LIKE 'str2') AND col2 = ...\n</code></pre>\n" }, { "answer_id": 240591, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 3, "selected": false, "text": "<p>I believe you need <code>WHERE ((page LIKE 'str1') OR (page LIKE 'str2'))</code></p>\n" }, { "answer_id": 240612, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 2, "selected": false, "text": "<p>The \"OR\" operator applies to expressions. \"LIKE 'str1'\" and \"LIKE 'str2'\" are not valid expressions, since the \"LIKE\" operator requires both a left hand side and a right hand side. </p>\n\n<pre><code>page LIKE ('str1' OR 'str2')\n</code></pre>\n\n<p>would first try to OR together 'str1' and 'str2', giving the value TRUE. It would then try and evaluate <code>page LIKE TRUE</code>, and report an error.</p>\n" }, { "answer_id": 41220435, "author": "Developer", "author_id": 6516777, "author_profile": "https://Stackoverflow.com/users/6516777", "pm_score": 3, "selected": false, "text": "<p>USE <code>%</code> at the Start and End of the String. So that it will check the Sub-Strings as well</p>\n\n<pre><code>SELECT col FROM db.tbl WHERE (col LIKE '%str1%' OR col LIKE '%str2%') AND col2 = num\n</code></pre>\n" }, { "answer_id": 62834101, "author": "AMF", "author_id": 6292891, "author_profile": "https://Stackoverflow.com/users/6292891", "pm_score": 0, "selected": false, "text": "<p>In recent versions of SQL you can use the <code>IN</code> operator:</p>\n<pre><code>SELECT col FROM db.tbl WHERE col IN('str1','str2') AND col2 = num\n</code></pre>\n" }, { "answer_id": 66513302, "author": "Dominic Flynn", "author_id": 12087633, "author_profile": "https://Stackoverflow.com/users/12087633", "pm_score": 2, "selected": false, "text": "<p>I assume what you want is,</p>\n<pre><code>SELECT col FROM db.tbl WHERE col LIKE '%str[12]%' AND col2 = num\n</code></pre>\n<p>That will literally find all cases where (col like %str1% or col like %str2%) AND col2 = num</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
I have tried the following two statements: * `SELECT col FROM db.tbl WHERE col (LIKE 'str1' OR LIKE 'str2') AND col2 = num` results in a syntax error * `SELECT col FROM db.tbl WHERE page LIKE ('str1' OR 'str2') AND col2 = num` results in "Truncated incorrect DOUBLE value: str1" and "Truncated incorrect DOUBLE value: str2" for what looks like every result. However, no results are actually returned. I figured one of the two statements would work, but they aren't.
> > > ``` > SELECT col FROM db.tbl WHERE (col LIKE 'str1' OR col LIKE 'str2') AND col2 = num > > ``` > >
240,592
<p>I'm working on a fiddly web interface which is mostly built with JavaScript. Its basically one (very) large form with many sections. Each section is built based on options from other parts of the form. Whenever those options change the new values are noted in a "registry" type object and the other sections re-populate accordingly.</p> <p>Having event listeners on the many form fields is starting to slow things down, and refreshing the whole form for each change would be too heavy/slow for the user.</p> <p>I'm wondering whether its possible to add listeners to the registry object's attributes rather than the form elements to speed things up a bit? And, if so, could you provide/point me to some sample code?</p> <p>Further information:</p> <ul> <li>This is a plug-in for jQuery, so any functionality I can build-on from that library would be helpful but not essential.</li> <li>Our users are using IE6/7, Safari and FF2/3, so if it is possible but only for "modern" browsers I'll have to find a different solution.</li> </ul>
[ { "answer_id": 240663, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 2, "selected": false, "text": "<p>You could attach a listener to a container (the body or the form) and then use the event parameter to react to the change. You get all the listener goodness but only have to attach one for the container instead of one for every element. </p>\n\n<pre><code>$('body').change(function(event){\n /* do whatever you want with event.target here */\n console.debug(event.target); /* assuming firebug */\n });\n</code></pre>\n\n<p>The event.target holds the element that was clicked on.</p>\n\n<p><a href=\"http://www.sitepoint.com/blogs/2008/07/23/javascript-event-delegation-is-easier-than-you-think/\" rel=\"nofollow noreferrer\">SitePoint</a> has a nice explanation here of event delegation:</p>\n\n<blockquote>\n <p>JavaScript event delegation is a simple technique by which you add a single event handler to a parent element in order to avoid having to add event handlers to multiple child elements.</p>\n</blockquote>\n" }, { "answer_id": 240696, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 1, "selected": false, "text": "<p>Mozilla-engined browsers support <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/watch\" rel=\"nofollow noreferrer\">Object.watch</a>, but I'm not aware of a cross-browser compatible equivalent.</p>\n\n<p>Have you profiled the page with Firebug to get an idea of exactly what's causing the slowness, or is \"lots of event handlers\" a guess?</p>\n" }, { "answer_id": 240700, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 3, "selected": false, "text": "<p>As far as I know, there are no events fired on Object attribute changes (edit: except, apparently, for <code>Object.watch</code>).</p>\n\n<p>Why not use event delegation wherever possible? That is, events on the form rather than on individual form elements, capturing events as they bubble up?</p>\n\n<p>For instance (my jQuery is rusty, forgive me for using Prototype instead, but I'm sure you'll be able to adapt it easily):</p>\n\n<pre><code>$(form).observe('change', function(e) {\n // To identify changed field, in Proto use e.element()\n // but I think in jQuery it's e.target (as it should be)\n});\n</code></pre>\n\n<p>You can also capture <code>input</code> and <code>keyup</code> and <code>paste</code> events if you want it to fire on text fields before they lose focus. My solution for this is usually:</p>\n\n<ol>\n<li><strong>Gecko/Webkit-based browsers:</strong> observe <code>input</code> on the <code>form</code>.</li>\n<li><strong>Also in Webkit-based browsers:</strong> observe <code>keyup</code> and <code>paste</code> events on <code>textarea</code>s (they do not fire <code>input</code> on <code>textarea</code>s for some reason).</li>\n<li><strong>IE:</strong> observe <code>keyup</code> and <code>paste</code> on the <code>form</code></li>\n<li>Observe <code>change</code> on the <code>form</code> (this fires on <code>select</code>s).</li>\n<li>For <code>keyup</code> and <code>paste</code> events, compare a field's current value against its default (what its value was when the page was loaded) by comparing a text field's <code>value</code> to its <code>defaultValue</code></li>\n</ol>\n\n<p>Edit: Here's example code I developed for preventing unmodified form submission and the like:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/194101/what-is-the-best-way-to-track-changes-in-a-form-via-javascript#194347\">What is the best way to track changes in a form via javascript?</a></p>\n" }, { "answer_id": 240722, "author": "Brian J Cardiff", "author_id": 30948, "author_profile": "https://Stackoverflow.com/users/30948", "pm_score": 0, "selected": false, "text": "<p>jQuery is just amazing. Although you could take a look to ASP.NET AJAX Preview.</p>\n\n<p>Some features are just .js files, no dependency with .NET. May be you could find usefull the observer pattern implementation.</p>\n\n<pre><code>var o = { foo: \"Change this string\" };\n\nSys.Observer.observe(o);\n\no.add_propertyChanged(function(sender, args) {\n var name = args.get_propertyName();\n alert(\"Property '\" + name + \"' was changed to '\" + sender[name] + \"'.\");\n});\n\no.setValue(\"foo\", \"New string value.\");\n</code></pre>\n\n<p>Also, Client Side templates are ready to use for some interesting scenarios.</p>\n\n<p>A final note, this is fully compatible with jQuery (not problem with $)</p>\n\n<p>Links: <a href=\"http://www.codeplex.com/aspnet/Wiki/View.aspx?title=AJAX\" rel=\"nofollow noreferrer\">Home page</a>, <a href=\"http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=14924\" rel=\"nofollow noreferrer\">Version I currently use</a></p>\n" }, { "answer_id": 242873, "author": "Phillip B Oldham", "author_id": 30478, "author_profile": "https://Stackoverflow.com/users/30478", "pm_score": 4, "selected": true, "text": "<p>Thanks for the comments guys. I've gone with the following:</p>\n\n<pre><code>var EntriesRegistry = (function(){\n\n var instance = null;\n\n function __constructor() {\n\n var\n self = this,\n observations = {};\n\n this.set = function(n,v)\n {\n self[n] = v;\n\n if( observations[n] )\n for( var i=0; i &lt; observations[n].length; i++ )\n observations[n][i].apply(null, [v, n]);\n\n }\n\n this.get = function(n)\n {\n return self[n];\n }\n\n this.observe = function(n,f)\n {\n\n if(observations[n] == undefined)\n observations[n] = [];\n\n observations[n].push(f);\n }\n\n }\n\n return new function(){\n this.getInstance = function(){\n if (instance == null)\n {\n instance = new __constructor();\n instance.constructor = null;\n }\n return instance;\n }\n }\n})();\n\nvar entries = EntriesRegistry.getInstance();\n\nvar test = function(v){ alert(v); };\n\nentries.set('bob', 'meh');\n\nentries.get('bob');\n\nentries.observe('seth', test);\n\nentries.set('seth', 'dave');\n</code></pre>\n\n<p>Taking on-board your comments, I'll be using event delegation on the form objects to update the registry and trigger the registered observing methods.</p>\n\n<p>This is working well for me so far... can you guys see any problems with this?</p>\n" }, { "answer_id": 15144909, "author": "rafaelcastrocouto", "author_id": 1242389, "author_profile": "https://Stackoverflow.com/users/1242389", "pm_score": 0, "selected": false, "text": "<p>I was searching for the same thing and hitted your question... none of the answers satisfied my needs so I came up with this solution that I would like to share:</p>\n\n<pre><code>var ObservedObject = function(){\n this.customAttribute = 0\n this.events = {}\n // your code...\n}\nObservedObject.prototype.changeAttribute = function(v){\n this.customAttribute = v\n // your code...\n this.dispatchEvent('myEvent')\n}\nObservedObject.prototype.addEventListener = function(type, f){\n if(!this.events[type]) this.events[type] = []\n this.events[type].push({\n action: f,\n type: type,\n target: this\n })\n}\nObservedObject.prototype.dispatchEvent = function(type){\n for(var e = 0; e &lt; this.events[type].length; ++e){\n this.events[type][e].action(this.events[type][e])\n }\n}\nObservedObject.prototype.removeEventListener = function(type, f){\n if(this.events[type]) {\n for(var e = 0; e &lt; this.events[type].length; ++e){\n if(this.events[type][e].action == f)\n this.events[type].splice(e, 1)\n }\n }\n}\n\nvar myObj = new ObservedObject()\n\nmyObj.addEventListener('myEvent', function(e){// your code...})\n</code></pre>\n\n<p>It's a simplification of the DOM Events API and works just fine!\nHere is a more complete <a href=\"http://jsfiddle.net/nNfFv/\" rel=\"nofollow\">example</a></p>\n" }, { "answer_id": 32336310, "author": "Sumi Straessle", "author_id": 2012120, "author_profile": "https://Stackoverflow.com/users/2012120", "pm_score": 1, "selected": false, "text": "<p>Small modification to the previous answer : by moving the observable code to an object, one can make an abstraction out of it and use it to extend other objects with jQuery's extend method.</p>\n\n<pre><code>ObservableProperties = {\n events : {},\n on : function(type, f)\n {\n if(!this.events[type]) this.events[type] = [];\n this.events[type].push({\n action: f,\n type: type,\n target: this\n });\n },\n trigger : function(type)\n {\n if (this.events[type]!==undefined)\n {\n for(var e = 0, imax = this.events[type].length ; e &lt; imax ; ++e)\n {\n this.events[type][e].action(this.events[type][e]);\n }\n }\n },\n removeEventListener : function(type, f)\n {\n if(this.events[type])\n {\n for(var e = 0, imax = this.events[type].length ; e &lt; imax ; ++e)\n {\n if(this.events[type][e].action == f)\n this.events[type].splice(e, 1);\n }\n }\n }\n};\nObject.freeze(ObservableProperties);\n\nvar SomeBusinessObject = function (){\n self = $.extend(true,{},ObservableProperties);\n self.someAttr = 1000\n self.someMethod = function(){\n // some code\n }\n return self;\n}\n</code></pre>\n\n<p>See the fiddle : <a href=\"https://jsfiddle.net/v2mcwpw7/3/\" rel=\"nofollow\">https://jsfiddle.net/v2mcwpw7/3/</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240592", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30478/" ]
I'm working on a fiddly web interface which is mostly built with JavaScript. Its basically one (very) large form with many sections. Each section is built based on options from other parts of the form. Whenever those options change the new values are noted in a "registry" type object and the other sections re-populate accordingly. Having event listeners on the many form fields is starting to slow things down, and refreshing the whole form for each change would be too heavy/slow for the user. I'm wondering whether its possible to add listeners to the registry object's attributes rather than the form elements to speed things up a bit? And, if so, could you provide/point me to some sample code? Further information: * This is a plug-in for jQuery, so any functionality I can build-on from that library would be helpful but not essential. * Our users are using IE6/7, Safari and FF2/3, so if it is possible but only for "modern" browsers I'll have to find a different solution.
Thanks for the comments guys. I've gone with the following: ``` var EntriesRegistry = (function(){ var instance = null; function __constructor() { var self = this, observations = {}; this.set = function(n,v) { self[n] = v; if( observations[n] ) for( var i=0; i < observations[n].length; i++ ) observations[n][i].apply(null, [v, n]); } this.get = function(n) { return self[n]; } this.observe = function(n,f) { if(observations[n] == undefined) observations[n] = []; observations[n].push(f); } } return new function(){ this.getInstance = function(){ if (instance == null) { instance = new __constructor(); instance.constructor = null; } return instance; } } })(); var entries = EntriesRegistry.getInstance(); var test = function(v){ alert(v); }; entries.set('bob', 'meh'); entries.get('bob'); entries.observe('seth', test); entries.set('seth', 'dave'); ``` Taking on-board your comments, I'll be using event delegation on the form objects to update the registry and trigger the registered observing methods. This is working well for me so far... can you guys see any problems with this?
240,648
<p>I am trying to do a search in my Eclipse (Java) workspace to find all instances of static variables that are not final.</p> <p>I tried various regexes but they do not result in any matches. Can someone suggest a regex that will match all lines containing <code>static</code> and not containing <code>final</code>, and not ending in a <code>{</code>?</p> <p>The last part about not ending with a <code>{</code> will eliminate static methods.</p> <p>An example:</p> <pre><code>public class FlagOffendingStatics { private static String shouldBeFlagged = "not ok"; private static final String ok = "this is fine"; public static void methodsAreOK() { } } </code></pre>
[ { "answer_id": 240687, "author": "a2800276", "author_id": 27408, "author_profile": "https://Stackoverflow.com/users/27408", "pm_score": 2, "selected": false, "text": "<p>Eclipse should have some sort of Java search built-in where you could specify that... Else, instead of writing one large monster regexp, try chaining together a bunch of greps:</p>\n\n<p><code>grep -r static . | grep -v final</code></p>\n\n<p>in the 1st statement, the -r causes the grep to recurse over a directory tree starting at the local directory, the results get piped to the 2nd grep which removes all the \n<code>final</code>'s. Keep adding -v until everything superfluous is removed from the results. This is usually easier --albeit less elegant-- than figuring out a complicated regexp to take care of everything. </p>\n" }, { "answer_id": 240838, "author": "Zarkonnen", "author_id": 15255, "author_profile": "https://Stackoverflow.com/users/15255", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://findbugs.sourceforge.net/\" rel=\"nofollow noreferrer\">FindBugs</a> will find static non-final variables for you. (Along with many other interesting things.) I've had good results with using the standalone version. There is also an Eclipse plugin, but I haven't used that.</p>\n" }, { "answer_id": 240848, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 4, "selected": true, "text": "<p>This pattern works:</p>\n\n<pre><code>[^(final)] static [^(final)][^(\\})]*$\n</code></pre>\n\n<p>Here is a test:</p>\n\n<pre><code>$ cat test.txt\nprivate int x = \"3\";\nprivate static x = \"3\";\nprivate final static String x = \"3\";\nprivate static final String x = \"3\";\nprivate static String x = \"3\";\npublic static void main(String args[]) {\n blah;\n}\n\n$ grep \"[^(final)] static [^(final)][^(\\})]*$\" test.txt\nprivate static x = \"3\";\nprivate static String x = \"3\";\n</code></pre>\n\n<p>(I realize that <code>private static x = \"3\";</code> isn't valid syntax, but the pattern still holds ok.)</p>\n\n<p>The pattern accounts for the fact that <code>final</code> can appear before or after <code>static</code> with <code>[^(final)] static [^(final)]</code>. The rest of the pattern, <code>[^(\\})]*$</code>, is meant to prevent any <code>{</code> characters from appearing in the remainder of the line.</p>\n\n<p>This pattern will not work however if anyone likes to write their method statements like this:</p>\n\n<pre><code>private static void blah()\n{\n //hi!\n}\n</code></pre>\n" }, { "answer_id": 240952, "author": "Chris Kessel", "author_id": 29734, "author_profile": "https://Stackoverflow.com/users/29734", "pm_score": 0, "selected": false, "text": "<p>One of the IntelliJ code inspections already does this. You can actually run the code inspector stand alone if you want and have it generate a report (usefull for a nightly build).</p>\n\n<p>As the previous poster said, Find Bugs will do this and I imagine other code inspection tools will do it as well. You're probably better off integrating one of those more complete code inspection tools rather than a one-off script just for this one thing.</p>\n" }, { "answer_id": 241324, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 2, "selected": false, "text": "<p>Instead of checking for the absence of a brace, I would look for a semicolon at the end:</p>\n\n<pre><code>^(?![ \\t]*import\\b)(?!.*\\bfinal\\b).*\\bstatic\\b.*;[ \\t]*$\n</code></pre>\n" }, { "answer_id": 563911, "author": "Skip Head", "author_id": 23271, "author_profile": "https://Stackoverflow.com/users/23271", "pm_score": 0, "selected": false, "text": "<p>This isn't a regex, but here is a plugin called checkstyle that will do that for you, as well as many other source checks. It even fixes many problems it finds automatically.</p>\n\n<p><a href=\"http://eclipse-cs.sourceforge.net/update/\" rel=\"nofollow noreferrer\">http://eclipse-cs.sourceforge.net/update/</a></p>\n" }, { "answer_id": 23958544, "author": "SynteZZZ", "author_id": 175221, "author_profile": "https://Stackoverflow.com/users/175221", "pm_score": 2, "selected": false, "text": "<p>Improved pattern from @matt-b</p>\n\n<pre><code>[^(final|import)] static [^(final|class|{|enum)][^(\\})]*$\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240648", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31837/" ]
I am trying to do a search in my Eclipse (Java) workspace to find all instances of static variables that are not final. I tried various regexes but they do not result in any matches. Can someone suggest a regex that will match all lines containing `static` and not containing `final`, and not ending in a `{`? The last part about not ending with a `{` will eliminate static methods. An example: ``` public class FlagOffendingStatics { private static String shouldBeFlagged = "not ok"; private static final String ok = "this is fine"; public static void methodsAreOK() { } } ```
This pattern works: ``` [^(final)] static [^(final)][^(\})]*$ ``` Here is a test: ``` $ cat test.txt private int x = "3"; private static x = "3"; private final static String x = "3"; private static final String x = "3"; private static String x = "3"; public static void main(String args[]) { blah; } $ grep "[^(final)] static [^(final)][^(\})]*$" test.txt private static x = "3"; private static String x = "3"; ``` (I realize that `private static x = "3";` isn't valid syntax, but the pattern still holds ok.) The pattern accounts for the fact that `final` can appear before or after `static` with `[^(final)] static [^(final)]`. The rest of the pattern, `[^(\})]*$`, is meant to prevent any `{` characters from appearing in the remainder of the line. This pattern will not work however if anyone likes to write their method statements like this: ``` private static void blah() { //hi! } ```
240,659
<p>I have a pretty generic Article model, with m2m relation to Tag model. I want to keep count of each tag usage, i think the best way would be to denormalise count field on Tag model and update it each time Article being saved. How can i accomplish this, or maybe there's a better way?</p>
[ { "answer_id": 241430, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 3, "selected": true, "text": "<p>You can do this by creating an <a href=\"http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships\" rel=\"nofollow noreferrer\">intermediate model</a> for the M2M relationship and use it as your hook for the <code>post_save</code> and <code>post_delete</code> signals to update the denormalised column in the <code>Article</code> table.</p>\n\n<p>For example, I do this for favourited <code>Question</code> counts in <a href=\"http://code.google.com/p/soclone/\" rel=\"nofollow noreferrer\">soclone</a>, where <code>User</code>s have a M2M relationship with <code>Question</code>s:</p>\n\n<pre><code>from django.contrib.auth.models import User\nfrom django.db import connection, models, transaction\nfrom django.db.models.signals import post_delete, post_save\n\nclass Question(models.Model):\n # ...\n favourite_count = models.PositiveIntegerField(default=0)\n\nclass FavouriteQuestion(models.Model):\n question = models.ForeignKey(Question)\n user = models.ForeignKey(User)\n\ndef update_question_favourite_count(instance, **kwargs):\n \"\"\"\n Updates the favourite count for the Question related to the given\n FavouriteQuestion.\n \"\"\"\n if kwargs.get('raw', False):\n return\n cursor = connection.cursor()\n cursor.execute(\n 'UPDATE soclone_question SET favourite_count = ('\n 'SELECT COUNT(*) from soclone_favouritequestion '\n 'WHERE soclone_favouritequestion.question_id = soclone_question.id'\n ') '\n 'WHERE id = %s', [instance.question_id])\n transaction.commit_unless_managed()\n\npost_save.connect(update_question_favourite_count, sender=FavouriteQuestion)\npost_delete.connect(update_question_favourite_count, sender=FavouriteQuestion)\n\n# Very, very naughty\nUser.add_to_class('favourite_questions',\n models.ManyToManyField(Question, through=FavouriteQuestion,\n related_name='favourited_by'))\n</code></pre>\n\n<p>There's been a bit of discussion on the django-developers mailing list about implementing a means of declaratively declaring denormalisations to avoid having to write code like the above:</p>\n\n<ul>\n<li><a href=\"http://groups.google.com/group/django-developers/browse_thread/thread/9a672d5bbbe67562\" rel=\"nofollow noreferrer\">Denormalisation, magic, and is it really that useful?</a></li>\n<li><a href=\"http://groups.google.com/group/django-developers/browse_thread/thread/6630273ab1869c19\" rel=\"nofollow noreferrer\">Denormalisation Magic, Round Two</a> </li>\n</ul>\n" }, { "answer_id": 2732790, "author": "Christian Oudard", "author_id": 3757, "author_profile": "https://Stackoverflow.com/users/3757", "pm_score": 2, "selected": false, "text": "<p>This is a new feature in Django 1.2:\n<a href=\"http://docs.djangoproject.com/en/dev/ref/signals/#m2m-changed\" rel=\"nofollow noreferrer\">http://docs.djangoproject.com/en/dev/ref/signals/#m2m-changed</a></p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7437/" ]
I have a pretty generic Article model, with m2m relation to Tag model. I want to keep count of each tag usage, i think the best way would be to denormalise count field on Tag model and update it each time Article being saved. How can i accomplish this, or maybe there's a better way?
You can do this by creating an [intermediate model](http://docs.djangoproject.com/en/dev/topics/db/models/#extra-fields-on-many-to-many-relationships) for the M2M relationship and use it as your hook for the `post_save` and `post_delete` signals to update the denormalised column in the `Article` table. For example, I do this for favourited `Question` counts in [soclone](http://code.google.com/p/soclone/), where `User`s have a M2M relationship with `Question`s: ``` from django.contrib.auth.models import User from django.db import connection, models, transaction from django.db.models.signals import post_delete, post_save class Question(models.Model): # ... favourite_count = models.PositiveIntegerField(default=0) class FavouriteQuestion(models.Model): question = models.ForeignKey(Question) user = models.ForeignKey(User) def update_question_favourite_count(instance, **kwargs): """ Updates the favourite count for the Question related to the given FavouriteQuestion. """ if kwargs.get('raw', False): return cursor = connection.cursor() cursor.execute( 'UPDATE soclone_question SET favourite_count = (' 'SELECT COUNT(*) from soclone_favouritequestion ' 'WHERE soclone_favouritequestion.question_id = soclone_question.id' ') ' 'WHERE id = %s', [instance.question_id]) transaction.commit_unless_managed() post_save.connect(update_question_favourite_count, sender=FavouriteQuestion) post_delete.connect(update_question_favourite_count, sender=FavouriteQuestion) # Very, very naughty User.add_to_class('favourite_questions', models.ManyToManyField(Question, through=FavouriteQuestion, related_name='favourited_by')) ``` There's been a bit of discussion on the django-developers mailing list about implementing a means of declaratively declaring denormalisations to avoid having to write code like the above: * [Denormalisation, magic, and is it really that useful?](http://groups.google.com/group/django-developers/browse_thread/thread/9a672d5bbbe67562) * [Denormalisation Magic, Round Two](http://groups.google.com/group/django-developers/browse_thread/thread/6630273ab1869c19)
240,660
<p>I have an associative array in the form <code>key =&gt; value</code> where key is a numerical value, however it is not a sequential numerical value. The key is actually an ID number and the value is a count. This is fine for most instances, however I want a function that gets the human-readable name of the array and uses that for the key, without changing the value.</p> <p>I didn't see a function that does this, but I'm assuming I need to provide the old key and new key (both of which I have) and transform the array. Is there an efficient way of doing this?</p>
[ { "answer_id": 240673, "author": "Tom Ritter", "author_id": 8435, "author_profile": "https://Stackoverflow.com/users/8435", "pm_score": 4, "selected": false, "text": "<p>You could use a second associative array that maps human readable names to the id's. That would also provide a Many to 1 relationship. Then do something like this:</p>\n\n<blockquote>\n<pre><code>echo 'Widgets: ' . $data[$humanreadbleMapping['Widgets']];\n</code></pre>\n</blockquote>\n" }, { "answer_id": 240676, "author": "KernelM", "author_id": 22328, "author_profile": "https://Stackoverflow.com/users/22328", "pm_score": 10, "selected": true, "text": "<pre><code>$arr[$newkey] = $arr[$oldkey];\nunset($arr[$oldkey]);\n</code></pre>\n" }, { "answer_id": 4196760, "author": "Simon Franco", "author_id": 509808, "author_profile": "https://Stackoverflow.com/users/509808", "pm_score": 6, "selected": false, "text": "<p>if your <code>array</code> is built from a database query, you can change the key directly from the <code>mysql</code> statement:</p>\n\n<p>instead of</p>\n\n<pre><code>\"select ´id´ from ´tablename´...\"\n</code></pre>\n\n<p>use something like:</p>\n\n<pre><code>\"select ´id´ **as NEWNAME** from ´tablename´...\"\n</code></pre>\n" }, { "answer_id": 4533033, "author": "kjg", "author_id": 547306, "author_profile": "https://Stackoverflow.com/users/547306", "pm_score": 4, "selected": false, "text": "<p>The answer from KernelM is nice, but in order to avoid the issue raised by Greg in the comment (conflicting keys), using a new array would be safer</p>\n\n<pre><code>$newarr[$newkey] = $oldarr[$oldkey];\n$oldarr=$newarr;\nunset($newarr);\n</code></pre>\n" }, { "answer_id": 5227417, "author": "kingjeffrey", "author_id": 315010, "author_profile": "https://Stackoverflow.com/users/315010", "pm_score": 3, "selected": false, "text": "<p>I like KernelM's solution, but I needed something that would handle potential key conflicts (where a new key may match an existing key). Here is what I came up with:</p>\n\n<pre><code>function swapKeys( &amp;$arr, $origKey, $newKey, &amp;$pendingKeys ) {\n if( !isset( $arr[$newKey] ) ) {\n $arr[$newKey] = $arr[$origKey];\n unset( $arr[$origKey] );\n if( isset( $pendingKeys[$origKey] ) ) {\n // recursion to handle conflicting keys with conflicting keys\n swapKeys( $arr, $pendingKeys[$origKey], $origKey, $pendingKeys );\n unset( $pendingKeys[$origKey] );\n }\n } elseif( $newKey != $origKey ) {\n $pendingKeys[$newKey] = $origKey;\n }\n}\n</code></pre>\n\n<p>You can then cycle through an array like this:</p>\n\n<pre><code>$myArray = array( '1970-01-01 00:00:01', '1970-01-01 00:01:00' );\n$pendingKeys = array();\nforeach( $myArray as $key =&gt; $myArrayValue ) {\n // NOTE: strtotime( '1970-01-01 00:00:01' ) = 1 (a conflicting key)\n $timestamp = strtotime( $myArrayValue );\n swapKeys( $myArray, $key, $timestamp, $pendingKeys );\n}\n// RESULT: $myArray == array( 1=&gt;'1970-01-01 00:00:01', 60=&gt;'1970-01-01 00:01:00' )\n</code></pre>\n" }, { "answer_id": 13062010, "author": "pajafumo", "author_id": 1746058, "author_profile": "https://Stackoverflow.com/users/1746058", "pm_score": 3, "selected": false, "text": "<p>If your array is recursive you can use this function:\ntest this data:</p>\n\n<pre><code> $datos = array\n (\n '0' =&gt; array\n (\n 'no' =&gt; 1,\n 'id_maquina' =&gt; 1,\n 'id_transaccion' =&gt; 1276316093,\n 'ultimo_cambio' =&gt; 'asdfsaf',\n 'fecha_ultimo_mantenimiento' =&gt; 1275804000,\n 'mecanico_ultimo_mantenimiento' =&gt;'asdfas',\n 'fecha_ultima_reparacion' =&gt; 1275804000,\n 'mecanico_ultima_reparacion' =&gt; 'sadfasf',\n 'fecha_siguiente_mantenimiento' =&gt; 1275804000,\n 'fecha_ultima_falla' =&gt; 0,\n 'total_fallas' =&gt; 0,\n ),\n\n '1' =&gt; array\n (\n 'no' =&gt; 2,\n 'id_maquina' =&gt; 2,\n 'id_transaccion' =&gt; 1276494575,\n 'ultimo_cambio' =&gt; 'xx',\n 'fecha_ultimo_mantenimiento' =&gt; 1275372000,\n 'mecanico_ultimo_mantenimiento' =&gt; 'xx',\n 'fecha_ultima_reparacion' =&gt; 1275458400,\n 'mecanico_ultima_reparacion' =&gt; 'xx',\n 'fecha_siguiente_mantenimiento' =&gt; 1275372000,\n 'fecha_ultima_falla' =&gt; 0,\n 'total_fallas' =&gt; 0,\n )\n );\n</code></pre>\n\n<p>here is the function:</p>\n\n<pre><code>function changekeyname($array, $newkey, $oldkey)\n{\n foreach ($array as $key =&gt; $value) \n {\n if (is_array($value))\n $array[$key] = changekeyname($value,$newkey,$oldkey);\n else\n {\n $array[$newkey] = $array[$oldkey]; \n }\n\n }\n unset($array[$oldkey]); \n return $array; \n}\n</code></pre>\n" }, { "answer_id": 21299719, "author": "DiverseAndRemote.com", "author_id": 1681414, "author_profile": "https://Stackoverflow.com/users/1681414", "pm_score": 7, "selected": false, "text": "<p>The way you would do this and preserve the ordering of the array is by putting the array keys into a separate array, find and replace the key in that array and then combine it back with the values. </p>\n\n<p>Here is a function that does just that:</p>\n\n<pre><code>function change_key( $array, $old_key, $new_key ) {\n\n if( ! array_key_exists( $old_key, $array ) )\n return $array;\n\n $keys = array_keys( $array );\n $keys[ array_search( $old_key, $keys ) ] = $new_key;\n\n return array_combine( $keys, $array );\n}\n</code></pre>\n" }, { "answer_id": 28168537, "author": "spreadzz", "author_id": 4287410, "author_profile": "https://Stackoverflow.com/users/4287410", "pm_score": 4, "selected": false, "text": "<p>If you want also the position of the new array key to be the same as the old one you can do this:</p>\n\n<pre><code>function change_array_key( $array, $old_key, $new_key) {\n if(!is_array($array)){ print 'You must enter a array as a haystack!'; exit; }\n if(!array_key_exists($old_key, $array)){\n return $array;\n }\n\n $key_pos = array_search($old_key, array_keys($array));\n $arr_before = array_slice($array, 0, $key_pos);\n $arr_after = array_slice($array, $key_pos + 1);\n $arr_renamed = array($new_key =&gt; $array[$old_key]);\n\n return $arr_before + $arr_renamed + $arr_after;\n}\n</code></pre>\n" }, { "answer_id": 30974058, "author": "Karthikeyan Ganesan", "author_id": 3462686, "author_profile": "https://Stackoverflow.com/users/3462686", "pm_score": 2, "selected": false, "text": "<p>this code will help to change the oldkey to new one</p>\n\n<pre><code>$i = 0;\n$keys_array=array(\"0\"=&gt;\"one\",\"1\"=&gt;\"two\");\n\n$keys = array_keys($keys_array);\n\nfor($i=0;$i&lt;count($keys);$i++) {\n $keys_array[$keys_array[$i]]=$keys_array[$i];\n unset($keys_array[$i]);\n}\nprint_r($keys_array);\n</code></pre>\n\n<p>display like</p>\n\n<pre><code>$keys_array=array(\"one\"=&gt;\"one\",\"two\"=&gt;\"two\");\n</code></pre>\n" }, { "answer_id": 31508993, "author": "Nadir", "author_id": 1641763, "author_profile": "https://Stackoverflow.com/users/1641763", "pm_score": 2, "selected": false, "text": "<p>Easy stuff:</p>\n<p>this function will accept the target $hash and $replacements is also a hash containing <strong>newkey=&gt;oldkey associations</strong>.</p>\n<p>This function will <strong>preserve original order</strong>, but could be problematic for very large (like above 10k records) arrays regarding <strong>performance &amp; memory</strong>.</p>\n<pre><code>function keyRename(array $hash, array $replacements) {\n $new=array();\n foreach($hash as $k=&gt;$v)\n {\n if($ok=array_search($k,$replacements))\n $k=$ok;\n $new[$k]=$v;\n }\n return $new; \n}\n</code></pre>\n<p>this alternative function would do the same, with <strong>far better performance</strong> &amp; memory usage, at the cost of losing original order (which should not be a problem since it is hashtable!)</p>\n<pre><code>function keyRename(array $hash, array $replacements) {\n\n foreach($hash as $k=&gt;$v)\n if($ok=array_search($k,$replacements))\n {\n $hash[$ok]=$v;\n unset($hash[$k]);\n }\n\n return $hash; \n}\n</code></pre>\n" }, { "answer_id": 34005346, "author": "kenorb", "author_id": 55075, "author_profile": "https://Stackoverflow.com/users/55075", "pm_score": 3, "selected": false, "text": "<p>Here is a helper function to achieve that:</p>\n\n<pre><code>/**\n * Helper function to rename array keys.\n */\nfunction _rename_arr_key($oldkey, $newkey, array &amp;$arr) {\n if (array_key_exists($oldkey, $arr)) {\n $arr[$newkey] = $arr[$oldkey];\n unset($arr[$oldkey]);\n return TRUE;\n } else {\n return FALSE;\n }\n}\n</code></pre>\n\n<p>pretty based on <a href=\"https://stackoverflow.com/a/240676/55075\">@KernelM answer</a>.</p>\n\n<p>Usage:</p>\n\n<pre><code>_rename_arr_key('oldkey', 'newkey', $my_array);\n</code></pre>\n\n<p>It will return <em>true</em> on successful rename, otherwise <em>false</em>.</p>\n" }, { "answer_id": 36435888, "author": "temuri", "author_id": 84626, "author_profile": "https://Stackoverflow.com/users/84626", "pm_score": 4, "selected": false, "text": "<pre><code>$array = [\n 'old1' =&gt; 1\n 'old2' =&gt; 2\n];\n\n$renameMap = [\n 'old1' =&gt; 'new1', \n 'old2' =&gt; 'new2'\n];\n\n$array = array_combine(array_map(function($el) use ($renameMap) {\n return $renameMap[$el];\n}, array_keys($array)), array_values($array));\n\n/*\n$array = [\n 'new1' =&gt; 1\n 'new2' =&gt; 2\n];\n*/\n</code></pre>\n" }, { "answer_id": 37243759, "author": "wmmso", "author_id": 3930840, "author_profile": "https://Stackoverflow.com/users/3930840", "pm_score": 1, "selected": false, "text": "<p>this works for renaming the first key:</p>\n\n<pre><code>$a = ['catine' =&gt; 'cat', 'canine' =&gt; 'dog'];\n$tmpa['feline'] = $a['catine'];\nunset($a['catine']);\n$a = $tmpa + $a;\n</code></pre>\n\n<p>then, print_r($a) renders a repaired in-order array:</p>\n\n<pre><code>Array\n(\n [feline] =&gt; cat\n [canine] =&gt; dog\n)\n</code></pre>\n\n<p>this works for renaming an arbitrary key:</p>\n\n<pre><code>$a = ['canine' =&gt; 'dog', 'catine' =&gt; 'cat', 'porcine' =&gt; 'pig']\n$af = array_flip($a)\n$af['cat'] = 'feline';\n$a = array_flip($af)\n</code></pre>\n\n<p>print_r($a)</p>\n\n<pre><code>Array\n(\n [canine] =&gt; dog\n [feline] =&gt; cat\n [porcine] =&gt; pig\n)\n</code></pre>\n\n<p>a generalized function:</p>\n\n<pre><code>function renameKey($oldkey, $newkey, $array) {\n $val = $array[$oldkey];\n $tmp_A = array_flip($array);\n $tmp_A[$val] = $newkey;\n\n return array_flip($tmp_A);\n}\n</code></pre>\n" }, { "answer_id": 38341525, "author": "lepe", "author_id": 196507, "author_profile": "https://Stackoverflow.com/users/196507", "pm_score": 2, "selected": false, "text": "<p>If you want to replace several keys at once (preserving order):</p>\n\n<pre><code>/**\n * Rename keys of an array\n * @param array $array (asoc)\n * @param array $replacement_keys (indexed)\n * @return array\n */\nfunction rename_keys($array, $replacement_keys) {\n return array_combine($replacement_keys, array_values($array));\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>$myarr = array(\"a\" =&gt; 22, \"b\" =&gt; 144, \"c\" =&gt; 43);\n$newkeys = array(\"x\",\"y\",\"z\");\nprint_r(rename_keys($myarr, $newkeys));\n//must return: array(\"x\" =&gt; 22, \"y\" =&gt; 144, \"z\" =&gt; 43);\n</code></pre>\n" }, { "answer_id": 41669197, "author": "Frank Vu", "author_id": 2924678, "author_profile": "https://Stackoverflow.com/users/2924678", "pm_score": -1, "selected": false, "text": "<p>Hmm, I'm not test before, but I think this code working</p>\n\n<pre><code>function replace_array_key($data) {\n $mapping = [\n 'old_key_1' =&gt; 'new_key_1',\n 'old_key_2' =&gt; 'new_key_2',\n ];\n\n $data = json_encode($data);\n foreach ($mapping as $needed =&gt; $replace) {\n $data = str_replace('\"'.$needed.'\":', '\"'.$replace.'\":', $data);\n }\n\n return json_decode($data, true);\n}\n</code></pre>\n" }, { "answer_id": 43061290, "author": "Kristoffer Bohmann", "author_id": 169224, "author_profile": "https://Stackoverflow.com/users/169224", "pm_score": 1, "selected": false, "text": "<p>There is an alternative way to change the key of an array element when working with a full array - without changing the order of the array.\nIt's simply to copy the array into a new array.</p>\n\n<p>For instance, I was working with a mixed, multi-dimensional array that contained indexed and associative keys - and I wanted to replace the integer keys with their values, without breaking the order.</p>\n\n<p>I did so by switching key/value for all numeric array entries - here: ['0'=>'foo']. Note that the order is intact.</p>\n\n<pre><code>&lt;?php\n$arr = [\n 'foo',\n 'bar'=&gt;'alfa',\n 'baz'=&gt;['a'=&gt;'hello', 'b'=&gt;'world'],\n];\n\nforeach($arr as $k=&gt;$v) {\n $kk = is_numeric($k) ? $v : $k;\n $vv = is_numeric($k) ? null : $v;\n $arr2[$kk] = $vv;\n}\n\nprint_r($arr2);\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>Array (\n [foo] =&gt; \n [bar] =&gt; alfa\n [baz] =&gt; Array (\n [a] =&gt; hello\n [b] =&gt; world\n )\n)\n</code></pre>\n" }, { "answer_id": 51857398, "author": "Andrew", "author_id": 2035501, "author_profile": "https://Stackoverflow.com/users/2035501", "pm_score": 0, "selected": false, "text": "<p>One which preservers ordering that's simple to understand:</p>\n\n<pre><code>function rename_array_key(array $array, $old_key, $new_key) {\n if (!array_key_exists($old_key, $array)) {\n return $array;\n }\n $new_array = [];\n foreach ($array as $key =&gt; $value) {\n $new_key = $old_key === $key\n ? $new_key\n : $key;\n $new_array[$new_key] = $value;\n }\n return $new_array;\n}\n</code></pre>\n" }, { "answer_id": 52248296, "author": "Alekzander", "author_id": 1331420, "author_profile": "https://Stackoverflow.com/users/1331420", "pm_score": 2, "selected": false, "text": "<p>You can use this function based on array_walk:</p>\n\n<pre><code>function mapToIDs($array, $id_field_name = 'id')\n{\n $result = [];\n array_walk($array, \n function(&amp;$value, $key) use (&amp;$result, $id_field_name)\n {\n $result[$value[$id_field_name]] = $value;\n }\n );\n return $result;\n}\n\n$arr = [0 =&gt; ['id' =&gt; 'one', 'fruit' =&gt; 'apple'], 1 =&gt; ['id' =&gt; 'two', 'fruit' =&gt; 'banana']];\nprint_r($arr);\nprint_r(mapToIDs($arr));\n</code></pre>\n\n<p>It gives:</p>\n\n<pre><code>Array(\n [0] =&gt; Array(\n [id] =&gt; one\n [fruit] =&gt; apple\n )\n [1] =&gt; Array(\n [id] =&gt; two\n [fruit] =&gt; banana\n )\n)\n\nArray(\n [one] =&gt; Array(\n [id] =&gt; one\n [fruit] =&gt; apple\n )\n [two] =&gt; Array(\n [id] =&gt; two\n [fruit] =&gt; banana\n )\n)\n</code></pre>\n" }, { "answer_id": 56388222, "author": "Kamil Dąbrowski", "author_id": 1088058, "author_profile": "https://Stackoverflow.com/users/1088058", "pm_score": 1, "selected": false, "text": "<p>best way is using reference, and not using unset (which make another step to clean memory)</p>\n\n<pre><code>$tab = ['two' =&gt; [] ];\n</code></pre>\n\n<p>solution: </p>\n\n<pre><code>$tab['newname'] = &amp; $tab['two'];\n</code></pre>\n\n<p>you have one original and one reference with new name.</p>\n\n<p>or if you don't want have two names in one value is good make another tab and foreach on reference</p>\n\n<pre><code>foreach($tab as $key=&gt; &amp; $value) {\n if($key=='two') { \n $newtab[\"newname\"] = &amp; $tab[$key];\n } else {\n $newtab[$key] = &amp; $tab[$key];\n }\n}\n</code></pre>\n\n<p>Iterration is better on keys than clone all array, and cleaning old array if you have long data like 100 rows +++ etc..</p>\n" }, { "answer_id": 56800416, "author": "vardius", "author_id": 2160958, "author_profile": "https://Stackoverflow.com/users/2160958", "pm_score": -1, "selected": false, "text": "<p>You can write simple function that applies the callback to the keys of the given array. Similar to <a href=\"https://www.php.net/manual/en/function.array-map.php\" rel=\"nofollow noreferrer\">array_map</a></p>\n\n<pre><code>&lt;?php\nfunction array_map_keys(callable $callback, array $array) {\n return array_merge([], ...array_map(\n function ($key, $value) use ($callback) { return [$callback($key) =&gt; $value]; },\n array_keys($array),\n $array\n ));\n}\n\n$array = ['a' =&gt; 1, 'b' =&gt; 'test', 'c' =&gt; ['x' =&gt; 1, 'y' =&gt; 2]];\n$newArray = array_map_keys(function($key) { return 'new' . ucfirst($key); }, $array);\n\necho json_encode($array); // {\"a\":1,\"b\":\"test\",\"c\":{\"x\":1,\"y\":2}}\necho json_encode($newArray); // {\"newA\":1,\"newB\":\"test\",\"newC\":{\"x\":1,\"y\":2}}\n</code></pre>\n\n<p>Here is a gist <a href=\"https://gist.github.com/vardius/650367e15abfb58bcd72ca47eff096ca#file-array_map_keys-php\" rel=\"nofollow noreferrer\">https://gist.github.com/vardius/650367e15abfb58bcd72ca47eff096ca#file-array_map_keys-php</a>.</p>\n" }, { "answer_id": 58619985, "author": "Léo Benoist", "author_id": 1617857, "author_profile": "https://Stackoverflow.com/users/1617857", "pm_score": 4, "selected": false, "text": "<p>Simple benchmark comparison of both solution.</p>\n<p>Solution 1 Copy and remove (order lost, but way faster) <a href=\"https://stackoverflow.com/a/240676/1617857\">https://stackoverflow.com/a/240676/1617857</a></p>\n<pre><code>&lt;?php\n$array = ['test' =&gt; 'value', ['etc...']];\n\n$array['test2'] = $array['test'];\nunset($array['test']);\n</code></pre>\n<p>Solution 2 Rename the key <a href=\"https://stackoverflow.com/a/21299719/1617857\">https://stackoverflow.com/a/21299719/1617857</a></p>\n<pre><code>&lt;?php\n$array = ['test' =&gt; 'value', ['etc...']];\n\n$keys = array_keys( $array );\n$keys[array_search('test', $keys, true)] = 'test2';\narray_combine( $keys, $array );\n</code></pre>\n<p>Benchmark:</p>\n<pre><code>&lt;?php\n$array = ['test' =&gt; 'value', ['etc...']];\n\n\nfor ($i =0; $i &lt; 100000000; $i++){\n // Solution 1\n}\n\n\nfor ($i =0; $i &lt; 100000000; $i++){\n // Solution 2\n}\n</code></pre>\n<p>Results:</p>\n<pre><code>php solution1.php 6.33s user 0.02s system 99% cpu 6.356 total\nphp solution1.php 6.37s user 0.01s system 99% cpu 6.390 total\nphp solution2.php 12.14s user 0.01s system 99% cpu 12.164 total\nphp solution2.php 12.57s user 0.03s system 99% cpu 12.612 total\n</code></pre>\n" }, { "answer_id": 58630444, "author": "MikeyJ", "author_id": 1665124, "author_profile": "https://Stackoverflow.com/users/1665124", "pm_score": 2, "selected": false, "text": "<p>This basic function handles swapping array keys and keeping the array in the original order...</p>\n\n<pre><code>public function keySwap(array $resource, array $keys)\n{\n $newResource = [];\n\n foreach($resource as $k =&gt; $r){\n if(array_key_exists($k,$keys)){\n $newResource[$keys[$k]] = $r;\n }else{\n $newResource[$k] = $r;\n }\n }\n\n return $newResource;\n}\n</code></pre>\n\n<p>You could then loop through and swap all 'a' keys with 'z' for example...</p>\n\n<pre><code>$inputs = [\n 0 =&gt; ['a'=&gt;'1','b'=&gt;'2'],\n 1 =&gt; ['a'=&gt;'3','b'=&gt;'4']\n]\n\n$keySwap = ['a'=&gt;'z'];\n\nforeach($inputs as $k=&gt;$i){\n $inputs[$k] = $this-&gt;keySwap($i,$keySwap);\n}\n</code></pre>\n" }, { "answer_id": 60765547, "author": "Grant", "author_id": 4582132, "author_profile": "https://Stackoverflow.com/users/4582132", "pm_score": 2, "selected": false, "text": "<p>This function will rename an array key, keeping its position, by combining with index searching.</p>\n\n<pre><code>function renameArrKey($arr, $oldKey, $newKey){\n if(!isset($arr[$oldKey])) return $arr; // Failsafe\n $keys = array_keys($arr);\n $keys[array_search($oldKey, $keys)] = $newKey;\n $newArr = array_combine($keys, $arr);\n return $newArr;\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>$arr = renameArrKey($arr, 'old_key', 'new_key');\n</code></pre>\n" }, { "answer_id": 71274431, "author": "mickmackusa", "author_id": 2943403, "author_profile": "https://Stackoverflow.com/users/2943403", "pm_score": 2, "selected": false, "text": "<p>This page has been peppered with a wide interpretation of what is required because there is no minimal, verifiable example in the question body. Some answers are merely trying to solve the &quot;title&quot; without bothering to understand the question requirements.</p>\n<blockquote>\n<p>The key is actually an ID number and the value is a count. This is\nfine for most instances, however I want a function that gets the\nhuman-readable name of the array and uses that for the key, without\nchanging the value.</p>\n</blockquote>\n<p>PHP keys cannot be <em>changed</em> but they can be replaced -- this is why so many answers are advising the use of <code>array_search()</code> (a relatively poor performer) and <code>unset()</code>.</p>\n<p>Ultimately, you want to create a new array with names as keys relating to the original count. This is most efficiently done via a lookup array because searching for keys will always outperform searching for values.</p>\n<p>Code: (<a href=\"https://3v4l.org/RcaRL\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n<pre><code>$idCounts = [\n 3 =&gt; 15,\n 7 =&gt; 12,\n 8 =&gt; 10,\n 9 =&gt; 4\n];\n\n$idNames = [\n 1 =&gt; 'Steve',\n 2 =&gt; 'Georgia',\n 3 =&gt; 'Elon',\n 4 =&gt; 'Fiona',\n 5 =&gt; 'Tim',\n 6 =&gt; 'Petra',\n 7 =&gt; 'Quentin',\n 8 =&gt; 'Raymond',\n 9 =&gt; 'Barb'\n];\n\n$result = [];\nforeach ($idCounts as $id =&gt; $count) {\n if (isset($idNames[$id])) {\n $result[$idNames[$id]] = $count;\n }\n}\nvar_export($result);\n</code></pre>\n<p>Output:</p>\n<pre><code>array (\n 'Elon' =&gt; 15,\n 'Quentin' =&gt; 12,\n 'Raymond' =&gt; 10,\n 'Barb' =&gt; 4,\n)\n</code></pre>\n<p>This technique maintains the original array order (in case the sorting matters), doesn't do any unnecessary iterating, and will be very swift because of <code>isset()</code>.</p>\n" }, { "answer_id": 73508367, "author": "Andris", "author_id": 2118559, "author_profile": "https://Stackoverflow.com/users/2118559", "pm_score": 0, "selected": false, "text": "<p>Here is an experiment (test)</p>\n<p>Initial array (keys like 0,1,2)</p>\n<pre><code>$some_array[] = '6110';//\n$some_array[] = '6111';//\n$some_array[] = '6210';//\n</code></pre>\n<p>I must change key names to for example <code>human_readable15</code>, <code>human_readable16</code>, <code>human_readable17</code></p>\n<p>Something similar as already posted. During each loop i set necessary key name and remove corresponding key from the initial array.</p>\n<p>For example, i inserted into mysql <code>$some_array</code> got <code>lastInsertId</code> and i need to send key-value pair back to jquery.</p>\n<pre><code>$first_id_of_inserted = 7;//lastInsertId\n$last_loop_for_some_array = count($some_array);\n\n\nfor ($current_loop = 0; $current_loop &lt; $last_loop_for_some_array ; $current_loop++) {\n\n$some_array['human_readable'.($first_id_of_inserted + $current_loop)] = $some_array[$current_loop];//add new key for intial array\n\nunset( $some_array[$current_loop] );//remove already renamed key from array\n\n}\n</code></pre>\n<p>And here is the new array with renamed keys</p>\n<pre><code>echo '&lt;pre&gt;', print_r($some_array, true), '&lt;/pre&gt;$some_array in '. basename(__FILE__, '.php'). '.php &lt;br/&gt;';\n</code></pre>\n<p>If instead of <code>human_readable15</code>, <code>human_readable16</code>, <code>human_readable17</code> need something other. Then could create something like this</p>\n<pre><code>$arr_with_key_names[] = 'human_readable';\n$arr_with_key_names[] = 'something_another';\n$arr_with_key_names[] = 'and_something_else';\n\n\nfor ($current_loop = 0; $current_loop &lt; $last_loop_for_some_array ; $current_loop++) {\n\n $some_array[$arr_with_key_names[$current_loop]] = $some_array[$current_loop];//add new key for intial array\n\n unset( $some_array[$current_loop] );//remove already renamed key from array\n\n }\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240660", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
I have an associative array in the form `key => value` where key is a numerical value, however it is not a sequential numerical value. The key is actually an ID number and the value is a count. This is fine for most instances, however I want a function that gets the human-readable name of the array and uses that for the key, without changing the value. I didn't see a function that does this, but I'm assuming I need to provide the old key and new key (both of which I have) and transform the array. Is there an efficient way of doing this?
``` $arr[$newkey] = $arr[$oldkey]; unset($arr[$oldkey]); ```
240,661
<p>Do you think changing directories inside bash or Perl scripts is acceptable? Or should one avoid doing this at all costs?</p> <p>What is the best practice for this issue?</p>
[ { "answer_id": 240675, "author": "Ovid", "author_id": 8003, "author_profile": "https://Stackoverflow.com/users/8003", "pm_score": 2, "selected": false, "text": "<p>I don't do this often, but sometimes it can save quite a bit of headache. Just be sure that if you change directories, you always change back to the directory you started from. Otherwise, changing code paths could leave the application somewhere it should not be.</p>\n" }, { "answer_id": 240703, "author": "Hugo", "author_id": 972, "author_profile": "https://Stackoverflow.com/users/972", "pm_score": 5, "selected": true, "text": "<p>The current working directory is local to the executing shell, so you can't affect the user unless he is \"dotting\" (running it in the current shell, as opposed to running it normally creating a new shell process) your script.</p>\n\n<p>A very good way of doing this is to use subshells, which i often do in aliases.</p>\n\n<pre><code>alias build-product1='(cd $working-copy/delivery; mvn package;)'\n</code></pre>\n\n<p>The paranthesis will make sure that the command is executed from a sub-shell, and thus will not affect the working directory of my shell. Also it will not affect the last-working-directory, so <strong>cd -;</strong> works as expected.</p>\n" }, { "answer_id": 241474, "author": "Jon Shea", "author_id": 3770, "author_profile": "https://Stackoverflow.com/users/3770", "pm_score": 1, "selected": false, "text": "<p>Consider also that Unix and Windows have a built in directory stack: <a href=\"http://en.wikipedia.org/wiki/Pushd_and_popd\" rel=\"nofollow noreferrer\">pushd and popd</a>. It’s extremely easy to use.</p>\n" }, { "answer_id": 241489, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 5, "selected": false, "text": "<p>Like Hugo said, you can't effect your parent process's cwd so there's no problem.</p>\n\n<p>Where the question is more applicable is if you don't control the whole process, like in a subroutine or module. In those cases you want to exit the subroutine in the same directory as you entered, otherwise subtle action-at-a-distance creeps in which causes bugs.</p>\n\n<p>You can to this by hand...</p>\n\n<pre><code>use Cwd;\nsub foo {\n my $orig_cwd = cwd;\n chdir \"some/dir\";\n\n ...do some work...\n\n chdir $orig_cwd;\n}\n</code></pre>\n\n<p>but that has problems. If the subroutine returns early or dies (and the exception is trapped) your code will still be in <code>some/dir</code>. Also, the <code>chdir</code>s might fail and you have to remember to check each use. Bleh.</p>\n\n<p>Fortunately, there's a couple modules to make this easier. File::pushd is one, but I prefer <a href=\"http://search.cpan.org/perldoc?File::chdir\" rel=\"noreferrer\">File::chdir</a>.</p>\n\n<pre><code>use File::chdir;\nsub foo {\n local $CWD = 'some/dir';\n\n ...do some work...\n}\n</code></pre>\n\n<p>File::chdir makes changing directories into assigning to <code>$CWD</code>. And you can localize <code>$CWD</code> so it will reset at the end of your scope, no matter what. It also automatically checks if the <code>chdir</code> succeeds and throws an exception otherwise. Sometimes it use it in scripts because it's just so convenient.</p>\n" }, { "answer_id": 241531, "author": "tsee", "author_id": 13164, "author_profile": "https://Stackoverflow.com/users/13164", "pm_score": 2, "selected": false, "text": "<p>For Perl, you have the <a href=\"http://search.cpan.org/dist/File-pushd/\" rel=\"nofollow noreferrer\">File::pushd</a> module from CPAN which makes locally changing the working directory quite elegant. Quoting the synopsis:</p>\n\n<pre><code> use File::pushd;\n\n chdir $ENV{HOME};\n\n # change directory again for a limited scope\n {\n my $dir = pushd( '/tmp' );\n # working directory changed to /tmp\n }\n # working directory has reverted to $ENV{HOME}\n\n # tempd() is equivalent to pushd( File::Temp::tempdir )\n {\n my $dir = tempd();\n }\n\n # object stringifies naturally as an absolute path\n {\n my $dir = pushd( '/tmp' );\n my $filename = File::Spec-&gt;catfile( $dir, \"somefile.txt\" );\n # gives /tmp/somefile.txt\n }\n</code></pre>\n" }, { "answer_id": 241551, "author": "mpez0", "author_id": 27898, "author_profile": "https://Stackoverflow.com/users/27898", "pm_score": 2, "selected": false, "text": "<p>I'll second Schwern's and Hugo's comments above. Note Schwern's caution about returning to the original directory in the event of an unexpected exit. He provided appropriate Perl code to handle that. I'll point out the shell (Bash, Korn, Bourne) trap command.</p>\n\n<p>trap \"cd $saved_dir\" 0</p>\n\n<p>will return to saved_dir on subshell exit (if you're .'ing the file).</p>\n\n<p>mike</p>\n" }, { "answer_id": 242235, "author": "Sam Kington", "author_id": 6832, "author_profile": "https://Stackoverflow.com/users/6832", "pm_score": 0, "selected": false, "text": "<p>Is it at all feasible to try and use fully-quantified paths, and not make any assumptions on which directory you're currently in? e.g.</p>\n\n<pre><code>use FileHandle;\nuse FindBin qw($Bin);\n# ...\nmy $file = new FileHandle(\"&lt; $Bin/somefile\");\n</code></pre>\n\n<p>rather than</p>\n\n<pre><code>use FileHandle;\n# ...\nmy $file = new FileHandle(\"&lt; somefile\");\n</code></pre>\n\n<p>This will probably be easier in the long run, as you don't have to worry about weird things happening (your script dying or being killed before it could put the current working directory back to where it was), and is quite possibly more portable.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13523/" ]
Do you think changing directories inside bash or Perl scripts is acceptable? Or should one avoid doing this at all costs? What is the best practice for this issue?
The current working directory is local to the executing shell, so you can't affect the user unless he is "dotting" (running it in the current shell, as opposed to running it normally creating a new shell process) your script. A very good way of doing this is to use subshells, which i often do in aliases. ``` alias build-product1='(cd $working-copy/delivery; mvn package;)' ``` The paranthesis will make sure that the command is executed from a sub-shell, and thus will not affect the working directory of my shell. Also it will not affect the last-working-directory, so **cd -;** works as expected.
240,692
<p>I am trying to download an xml.gz file from a remote server with HttpsURLConnection in java, but I am getting an empty response. Here is a sample of my code:</p> <pre><code>URL server = new URL("https://www.myurl.com/path/sample_file.xml.gz"); HttpsURLConnection connection = (HttpsURLConnection)server.openConnection(); connection.connect(); </code></pre> <p>When I try to get an InputStream from the connection, it is empty. (If I try connection.getInputStream().read() I get -1) The file I am expecting is approximately 50MB. </p> <p>To test my sanity, I aslo tried entering the exact same url in my browser, and it did return the file I needed. Am I missing something? Do I have to set some sort of parameter in the connection? Any help/direction is much appreciated. </p>
[ { "answer_id": 240760, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 2, "selected": false, "text": "<p>Is any exception being logged? Is the website presenting a self-signed SSL certificate, or one that is not signed by a CA? There are several reasons why it might work fine in your browser (the browser might have been told to accept self-signed certs from that domain) and not in your code.</p>\n\n<p>What are the results of using <a href=\"http://curl.haxx.se/\" rel=\"nofollow noreferrer\">curl</a> or <a href=\"http://www.gnu.org/software/wget/\" rel=\"nofollow noreferrer\">wget</a> to fetch the URL?</p>\n\n<p>The fact that the InputStream is empty / result from the InputStream.read() == -1 implies that there is nothing in the stream to read, meaning that the stream was not able to even be set up properly.</p>\n\n<p><strong>Update</strong>: <a href=\"http://www.howardism.org/Technical/Java/SelfSignedCerts.html\" rel=\"nofollow noreferrer\">See this page</a> for some info on how you can deal with invalid/self-signed certificates in your connection code. Or, if the site is presenting a certificate but it is invalid, you can import it into the keystore of the server to tell Java to trust the certificate. <a href=\"http://www.chrissearle.org/blog/technical/adding_self_signed_https_certificates_java_keystore\" rel=\"nofollow noreferrer\">See this page for more info</a>.</p>\n" }, { "answer_id": 240871, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 2, "selected": false, "text": "<ol>\n<li>Verify the <code>response code</code> is 200</li>\n<li>Check that <code>connection.contentType</code> to verify the content type is recognized</li>\n<li>You may need to add a Content-Handler for the GZ mime type, which I can't recall off the top of my head.</li>\n</ol>\n\n<p>After the comment describing the response code as 3xx,</p>\n\n<ol>\n<li>Set 'connection.setFollowRedirects(true)'</li>\n</ol>\n\n<p>Should fix it.</p>\n" }, { "answer_id": 244318, "author": "Zakir Hemraj", "author_id": 29752, "author_profile": "https://Stackoverflow.com/users/29752", "pm_score": 1, "selected": false, "text": "<p>Turns out the download wasn't working because the remote server was redirecting me to a new url to download the file. Even though connection.setFollowRedirects(true) was set, I still had to manually set up a new connection for the redirected URL as follows:</p>\n\n<pre><code>if (connection.getResponseCode() == 302 &amp;&amp; connection.getHeaderField(\"location\") != null){\n URL server2 = new URL(connection.getHeaderField(\"location\"));\n HttpURLConnection connection2 = (HttpURLConnection)server2.openConnection();\n connection2.connect();\n InputStream in = connection2.getInputStream();\n}\n</code></pre>\n\n<p>After that, I was able to retrieve the file from the input stream. Thanks for all your help guys!</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29752/" ]
I am trying to download an xml.gz file from a remote server with HttpsURLConnection in java, but I am getting an empty response. Here is a sample of my code: ``` URL server = new URL("https://www.myurl.com/path/sample_file.xml.gz"); HttpsURLConnection connection = (HttpsURLConnection)server.openConnection(); connection.connect(); ``` When I try to get an InputStream from the connection, it is empty. (If I try connection.getInputStream().read() I get -1) The file I am expecting is approximately 50MB. To test my sanity, I aslo tried entering the exact same url in my browser, and it did return the file I needed. Am I missing something? Do I have to set some sort of parameter in the connection? Any help/direction is much appreciated.
Is any exception being logged? Is the website presenting a self-signed SSL certificate, or one that is not signed by a CA? There are several reasons why it might work fine in your browser (the browser might have been told to accept self-signed certs from that domain) and not in your code. What are the results of using [curl](http://curl.haxx.se/) or [wget](http://www.gnu.org/software/wget/) to fetch the URL? The fact that the InputStream is empty / result from the InputStream.read() == -1 implies that there is nothing in the stream to read, meaning that the stream was not able to even be set up properly. **Update**: [See this page](http://www.howardism.org/Technical/Java/SelfSignedCerts.html) for some info on how you can deal with invalid/self-signed certificates in your connection code. Or, if the site is presenting a certificate but it is invalid, you can import it into the keystore of the server to tell Java to trust the certificate. [See this page for more info](http://www.chrissearle.org/blog/technical/adding_self_signed_https_certificates_java_keystore).
240,704
<p>Does anyone have any suggestions for a good approach to finding all the CPAN dependencies that might have arisen in a bespoke development project. As tends to be the case your local development environment rarely matches your live one and as you build more and more projects you tend to build up a local library of installed modules. These then lead to you not necessarily noticing that your latest project has a requirement on a non-core module. As there is generally a requirement to package the entire project up for deployment to another group (in our case our operations team), it is important to know what modules should be included in the package. </p> <p>Does anyone have any insights into the problem.</p> <p>Thanks</p> <p>Peter</p>
[ { "answer_id": 240723, "author": "Vagnerr", "author_id": 3720, "author_profile": "https://Stackoverflow.com/users/3720", "pm_score": 3, "selected": false, "text": "<p>In the past I have used <a href=\"http://search.cpan.org/dist/Devel-Modlist/\" rel=\"noreferrer\">Devel::Modlist</a> which is reasonably good allowing you to go</p>\n\n<pre><code>perl -d:Modlist script.pl\n</code></pre>\n\n<p>To get a list of the required modules.</p>\n" }, { "answer_id": 240770, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>You can use online web-service at <a href=\"http://deps.cpantesters.org/\" rel=\"nofollow noreferrer\">deps.cpantesters.org</a> that will provide you many useful dependency data. All modules on CPAN already have the link to the dependency site (on the right side of the module page).</p>\n" }, { "answer_id": 240773, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<p>The 'obvious' way - painful but moderately effective - is to install a brand new build of base Perl in some out of the way location (you aren't going to use this in production), and then try to install your module using this 'virgin' version of Perl. You will find all the missing dependencies. The first time, this could be painful. After the first time, you'll already have the majority of the dependencies covered, and it will be vastly less painful.</p>\n\n<p>Consider running your own local repository of CPAN modules - so that you won't always have to download the code. Also consider how you clean up the out of date modules.</p>\n" }, { "answer_id": 240927, "author": "KeyserSoze", "author_id": 14116, "author_profile": "https://Stackoverflow.com/users/14116", "pm_score": 3, "selected": false, "text": "<p>I have a Make-based build system for all my C/C++ applications (both PC-based and for various embedded projects), and while I love being able to do a top-level build on a fresh machine and verify all dependencies are in place (I check my toolchains in to revision control :D), I've been frustrated at not doing the same for interpreted languages that currently have no makefile in my build system.</p>\n\n<p>I'm tempted to write a script that:</p>\n\n<ul>\n<li>searches my revision control repository for files with the .pl or .pm extension</li>\n<li>runs <code>perl -d:Modlist</code> on them (thanks Vagnerr!)</li>\n<li>concatenating it to the list of required modules</li>\n<li>and finally comparing it to the list of installed modules.</li>\n</ul>\n\n<p>I'd then execute that script as part of my top-level build, so that anyone building anything will know if they have everything they need to run every perl script they got from revision control. If there is some perl script they never run and don't want to CPAN install what's required to run it, they'd have to remove the unwanted script from their harddrive, so the dependency checker can't find them. I know how to modify a perforce client to leave out certain subdirectories when you do a 'sync', I'll have to figure that out for subversion...</p>\n\n<p>I'd suggest making the dependency checker a single script that searches for pl files, as opposed to an individual makefile to check dependencies for each script, or based on a hard-coded list of script names. If you choose a method that requires user action to have a script checked for dependencies, people will forget to perform that action, since they will be able to run the script even if they don't do the dependency check.</p>\n\n<p>Like I said, I haven't implemented the above yet, but this question has prompted me to try to do so. I'll post back with my experience after I'm done.</p>\n" }, { "answer_id": 241081, "author": "draegtun", "author_id": 12195, "author_profile": "https://Stackoverflow.com/users/12195", "pm_score": 2, "selected": false, "text": "<p>Its a \"horse that's bolted\" answer but I've got into the habit of creating a Bundle file with all my dependencies. Thus when I go to a new environment I just copy it over and install it.</p>\n\n<p>For eg. I have a Baz.pm</p>\n\n<pre><code>package Bundle::Baz;\n$VERSION = '0.1';\n1;\n__END__\n=head1 NAME\nBundle::Baz\n=head1 SYNOPSIS\nperl -MCPAN -e 'install Bundle::Baz'\n=head1 CONTENTS\n# Baz's modules\nXML::Twig\nXML::Writer\nPerl6::Say\nMoose\n</code></pre>\n\n<p>Put this in ~/.cpan/Bundle/ (or wherever your .cpan lives) and then install 'Bundle::Baz' like a normal CPAN module. This then installs all the modules listed under \"=head1 CONTENTS\".</p>\n" }, { "answer_id": 241353, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 5, "selected": true, "text": "<p>I've had this problem myself. <a href=\"http://search.cpan.org/perldoc?Devel::Modlist\" rel=\"nofollow noreferrer\">Devel::Modlist</a> (as suggested by <a href=\"https://stackoverflow.com/questions/240704/how-can-i-determine-cpan-dependencies-before-i-deploy-a-perl-project#240723\">this answer</a>) takes a dynamic approach. It reports the modules that were actually loaded during a particular run of your script. This catches modules that are loaded by any means, but it may not catch conditional requirements. That is, if you have code like this:</p>\n\n<pre><code>if ($some_condition) { require Some::Module }\n</code></pre>\n\n<p>and <code>$some_condition</code> happens to be false, <code>Devel::Modlist</code> will not list <code>Some::Module</code> as a requirement.</p>\n\n<p>I decided to use <a href=\"http://search.cpan.org/perldoc?Module::ExtractUse\" rel=\"nofollow noreferrer\">Module::ExtractUse</a> instead. It does a static analysis, which means that it will always catch <code>Some::Module</code> in the above example. On the other hand, it can't do anything about code like:</p>\n\n<pre><code>my $module = \"Other::Module\";\neval \"use $module;\";\n</code></pre>\n\n<p>Of course, you could use both approaches and then combine the two lists.</p>\n\n<p>Anyway, here's the solution I came up with:</p>\n\n<pre><code>#! /usr/bin/perl\n#---------------------------------------------------------------------\n# Copyright 2008 Christopher J. Madsen &lt;perl at cjmweb.net&gt;\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the same terms as Perl itself.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either the\n# GNU General Public License or the Artistic License for more details.\n#\n# Recursively collect dependencies of Perl scripts\n#---------------------------------------------------------------------\n\nuse strict;\nuse warnings;\nuse File::Spec ();\nuse Module::CoreList ();\nuse Module::ExtractUse ();\n\nmy %need;\nmy $core = $Module::CoreList::version{'5.008'};\n\n# These modules have lots of dependencies. I don't need to see them now.\nmy %noRecurse = map { $_ =&gt; 1 } qw(\n Log::Log4perl\n XML::Twig\n);\n\nforeach my $file (@ARGV) {\n findDeps($file);\n}\n\nforeach my $module (sort keys %need) {\n print \" $module\\n\";\n}\n\n#---------------------------------------------------------------------\nsub findDeps\n{\n my ($file) = @_;\n\n my $p = Module::ExtractUse-&gt;new;\n\n $p-&gt;extract_use($file);\n\n foreach my $module ($p-&gt;array) {\n next if exists $core-&gt;{$module};\n next if $module =~ /^5[._\\d]+/; # Ignore \"use MIN-PERL-VERSION\"\n next if $module =~ /\\$/; # Run-time specified module\n\n if (++$need{$module} == 1 and not $noRecurse{$module}) {\n my $path = findModule($module);\n if ($path) { findDeps($path) }\n else { warn \"WARNING: Can't find $module\\n\" }\n } # end if first use of $module\n } # end foreach $module used\n} # end findDeps\n\n#---------------------------------------------------------------------\nsub findModule\n{\n my ($module) = @_;\n\n $module =~ s!::|\\'!/!g;\n $module .= '.pm';\n\n foreach my $dir (@INC) {\n my $path = File::Spec-&gt;catfile($dir, $module);\n return $path if -f $path;\n }\n\n return;\n} # end findModule\n</code></pre>\n\n<p>You'd run this like:</p>\n\n<pre><code>perl finddeps.pl scriptToCheck.pl otherScriptToCheck.pl\n</code></pre>\n\n<p>It prints a list of all non-core modules necessary to run the scripts listed. (Unless they do fancy tricks with module loading that prevent Module::ExtractUse from seeing them.)</p>\n" }, { "answer_id": 245158, "author": "JDrago", "author_id": 29060, "author_profile": "https://Stackoverflow.com/users/29060", "pm_score": 2, "selected": false, "text": "<pre><code>use Acme::Magic::Pony;\n</code></pre>\n\n<p>Seriously. It will auto-install Perl modules if they turn up missing. See the <a href=\"http://search.cpan.org/~jlavallee/Acme-Magic-Pony-0.02/lib/Acme/Magic/Pony.pm\" rel=\"nofollow noreferrer\">Acme::Magic::Pony</a> page in CPAN.</p>\n" }, { "answer_id": 245167, "author": "Robert Krimen", "author_id": 25171, "author_profile": "https://Stackoverflow.com/users/25171", "pm_score": 1, "selected": false, "text": "<p>Here is a quickie bash function (using the excellent <a href=\"http://petdance.com/ack/\" rel=\"nofollow noreferrer\">ack</a>):</p>\n\n<pre><code># find-perl-module-use &lt;directory&gt; (lib/ by default)\nfunction find-perl-module-use() {\n dir=${1:-lib}\n ack '^\\s*use\\s+.*;\\s*$' $dir | awk '{ print $2 }' | sed 's/();\\?$\\|;$//' | sort | uniq\n ack '^\\s*use\\s+base\\s+.*;\\s*$' $dir | awk '{ print $3 }' | sed 's/();\\?$\\|;$//' | sort | uniq\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3720/" ]
Does anyone have any suggestions for a good approach to finding all the CPAN dependencies that might have arisen in a bespoke development project. As tends to be the case your local development environment rarely matches your live one and as you build more and more projects you tend to build up a local library of installed modules. These then lead to you not necessarily noticing that your latest project has a requirement on a non-core module. As there is generally a requirement to package the entire project up for deployment to another group (in our case our operations team), it is important to know what modules should be included in the package. Does anyone have any insights into the problem. Thanks Peter
I've had this problem myself. [Devel::Modlist](http://search.cpan.org/perldoc?Devel::Modlist) (as suggested by [this answer](https://stackoverflow.com/questions/240704/how-can-i-determine-cpan-dependencies-before-i-deploy-a-perl-project#240723)) takes a dynamic approach. It reports the modules that were actually loaded during a particular run of your script. This catches modules that are loaded by any means, but it may not catch conditional requirements. That is, if you have code like this: ``` if ($some_condition) { require Some::Module } ``` and `$some_condition` happens to be false, `Devel::Modlist` will not list `Some::Module` as a requirement. I decided to use [Module::ExtractUse](http://search.cpan.org/perldoc?Module::ExtractUse) instead. It does a static analysis, which means that it will always catch `Some::Module` in the above example. On the other hand, it can't do anything about code like: ``` my $module = "Other::Module"; eval "use $module;"; ``` Of course, you could use both approaches and then combine the two lists. Anyway, here's the solution I came up with: ``` #! /usr/bin/perl #--------------------------------------------------------------------- # Copyright 2008 Christopher J. Madsen <perl at cjmweb.net> # # This program is free software; you can redistribute it and/or modify # it under the same terms as Perl itself. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See either the # GNU General Public License or the Artistic License for more details. # # Recursively collect dependencies of Perl scripts #--------------------------------------------------------------------- use strict; use warnings; use File::Spec (); use Module::CoreList (); use Module::ExtractUse (); my %need; my $core = $Module::CoreList::version{'5.008'}; # These modules have lots of dependencies. I don't need to see them now. my %noRecurse = map { $_ => 1 } qw( Log::Log4perl XML::Twig ); foreach my $file (@ARGV) { findDeps($file); } foreach my $module (sort keys %need) { print " $module\n"; } #--------------------------------------------------------------------- sub findDeps { my ($file) = @_; my $p = Module::ExtractUse->new; $p->extract_use($file); foreach my $module ($p->array) { next if exists $core->{$module}; next if $module =~ /^5[._\d]+/; # Ignore "use MIN-PERL-VERSION" next if $module =~ /\$/; # Run-time specified module if (++$need{$module} == 1 and not $noRecurse{$module}) { my $path = findModule($module); if ($path) { findDeps($path) } else { warn "WARNING: Can't find $module\n" } } # end if first use of $module } # end foreach $module used } # end findDeps #--------------------------------------------------------------------- sub findModule { my ($module) = @_; $module =~ s!::|\'!/!g; $module .= '.pm'; foreach my $dir (@INC) { my $path = File::Spec->catfile($dir, $module); return $path if -f $path; } return; } # end findModule ``` You'd run this like: ``` perl finddeps.pl scriptToCheck.pl otherScriptToCheck.pl ``` It prints a list of all non-core modules necessary to run the scripts listed. (Unless they do fancy tricks with module loading that prevent Module::ExtractUse from seeing them.)
240,713
<p>I need to encrypt and decrypt a querystring in ASP.NET. </p> <p>The querystring might look something like this:</p> <blockquote> <p><a href="http://www.mysite.com/report.aspx?id=12345&amp;year=2008" rel="noreferrer">http://www.mysite.com/report.aspx?id=12345&amp;year=2008</a></p> </blockquote> <p>How do I go about encrypting the entire querystring so that it looks something like the following?</p> <blockquote> <p><a href="http://www.mysite.com/report.aspx?crypt=asldjfaf32as98df8a" rel="noreferrer">http://www.mysite.com/report.aspx?crypt=asldjfaf32as98df8a</a></p> </blockquote> <p>And then, of course, how to I decrypt it? What's the best encryption to use for something like this? TripleDES?</p>
[ { "answer_id": 240730, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 0, "selected": false, "text": "<p>I can't give you a turn key solution off the top of my head, but you should avoid TripleDES since it is <a href=\"http://en.wikipedia.org/wiki/Triple_DES\" rel=\"nofollow noreferrer\">not as secure as other encryption methods</a>.</p>\n\n<p>If I were doing it, I'd just take the entire URL (domain and querystring) as a <a href=\"http://msdn.microsoft.com/en-us/library/system.uri.aspx\" rel=\"nofollow noreferrer\">URI object</a>, encrypt it with one of the <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndael.aspx\" rel=\"nofollow noreferrer\">built-in .NET libraries</a> and supply it as the <code>crypt</code> object. When I need to decrypt it, do so, then create a new URI object, which will let you get everything back out of the original querystring.</p>\n" }, { "answer_id": 240751, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 4, "selected": true, "text": "<p>Here is a way to do it in VB From: <a href=\"http://www.devcity.net/Articles/47/1/encrypt_querystring.aspx\" rel=\"noreferrer\">http://www.devcity.net/Articles/47/1/encrypt_querystring.aspx</a></p>\n\n<p><strong>Wrapper for the encryption code:</strong> Pass your querystring parameters into this, and change the key!!!</p>\n\n<pre><code>Private _key as string = \"!#$a54?3\"\nPublic Function encryptQueryString(ByVal strQueryString As String) As String\n Dim oES As New ExtractAndSerialize.Encryption64()\n Return oES.Encrypt(strQueryString, _key)\nEnd Function\n\nPublic Function decryptQueryString(ByVal strQueryString As String) As String\n Dim oES As New ExtractAndSerialize.Encryption64()\n Return oES.Decrypt(strQueryString, _key)\nEnd Function\n</code></pre>\n\n<p><strong>Encryption Code:</strong></p>\n\n<pre><code>Imports System\nImports System.IO\nImports System.Xml\nImports System.Text\nImports System.Security.Cryptography\n\nPublic Class Encryption64\n Private key() As Byte = {}\n Private IV() As Byte = {&amp;H12, &amp;H34, &amp;H56, &amp;H78, &amp;H90, &amp;HAB, &amp;HCD, &amp;HEF}\n\n Public Function Decrypt(ByVal stringToDecrypt As String, _\n ByVal sEncryptionKey As String) As String\n Dim inputByteArray(stringToDecrypt.Length) As Byte\n Try\n key = System.Text.Encoding.UTF8.GetBytes(Left(sEncryptionKey, 8))\n Dim des As New DESCryptoServiceProvider()\n inputByteArray = Convert.FromBase64String(stringToDecrypt)\n Dim ms As New MemoryStream()\n Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), _\n CryptoStreamMode.Write)\n cs.Write(inputByteArray, 0, inputByteArray.Length)\n cs.FlushFinalBlock()\n Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8\n Return encoding.GetString(ms.ToArray())\n Catch e As Exception\n Return e.Message\n End Try\n End Function\n\n Public Function Encrypt(ByVal stringToEncrypt As String, _\n ByVal SEncryptionKey As String) As String\n Try\n key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8))\n Dim des As New DESCryptoServiceProvider()\n Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes( _\n stringToEncrypt)\n Dim ms As New MemoryStream()\n Dim cs As New CryptoStream(ms, des.CreateEncryptor(key, IV), _\n CryptoStreamMode.Write)\n cs.Write(inputByteArray, 0, inputByteArray.Length)\n cs.FlushFinalBlock()\n Return Convert.ToBase64String(ms.ToArray())\n Catch e As Exception\n Return e.Message\n End Try\n End Function\n\nEnd Class\n</code></pre>\n" }, { "answer_id": 240769, "author": "Joseph Bui", "author_id": 3275, "author_profile": "https://Stackoverflow.com/users/3275", "pm_score": -1, "selected": false, "text": "<p>Why are you trying to encrypt your query string? If the data is sensitive, you should be using SSL. If you are worried about someone looking over the user's shoulder, use form POST instead of GET.</p>\n\n<p>I think it is pretty likely that there is a better solution for your fundamental problem than encrypting the query string.</p>\n" }, { "answer_id": 240858, "author": "Brendan Kendrick", "author_id": 13473, "author_profile": "https://Stackoverflow.com/users/13473", "pm_score": 0, "selected": false, "text": "<p>Here's a sort of fancy version of the decrypt function from Brian's example above that you could use if you were only going to use this for the QueryString as it returns a NameValueCollection instead of a string. It also contains a slight correction as Brian's example will break without</p>\n\n<pre><code>stringToDecrypt = stringToDecrypt.Replace(\" \", \"+\")\n</code></pre>\n\n<p>if there are any 'space' characters in the string to decrypt:</p>\n\n<pre><code>Public Shared Function DecryptQueryString(ByVal stringToDecrypt As String, ByVal encryptionKey As String) As Collections.Specialized.NameValueCollection\n Dim inputByteArray(stringToDecrypt.Length) As Byte\n Try\n Dim key() As Byte = System.Text.Encoding.UTF8.GetBytes(encryptionKey.Substring(0, encryptionKey.Length))\n Dim IV() As Byte = {&amp;H12, &amp;H34, &amp;H56, &amp;H78, &amp;H90, &amp;HAB, &amp;HCD, &amp;HEF}\n Dim des As New DESCryptoServiceProvider()\n stringToDecrypt = stringToDecrypt.Replace(\" \", \"+\")\n inputByteArray = Convert.FromBase64String(stringToDecrypt)\n Dim ms As New MemoryStream()\n Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write)\n cs.Write(inputByteArray, 0, inputByteArray.Length)\n cs.FlushFinalBlock()\n Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8\n Dim decryptedString As String = encoding.GetString(ms.ToArray())\n Dim nameVals() As String = decryptedString.Split(CChar(\"&amp;\"))\n Dim queryString As New Collections.Specialized.NameValueCollection(nameVals.Length)\n For Each nameValPair As String In nameVals\n Dim pair() As String = nameValPair.Split(CChar(\"=\"))\n queryString.Add(pair(0), pair(1))\n Next\n Return queryString\n\n Catch e As Exception\n Throw New Exception(e.Message)\n End Try\nEnd Function\n</code></pre>\n\n<p>I hope you find this useful!</p>\n" }, { "answer_id": 240889, "author": "smbarbour", "author_id": 29115, "author_profile": "https://Stackoverflow.com/users/29115", "pm_score": 0, "selected": false, "text": "<p>I was originally going to agree with Joseph Bui on the grounds that it would be more processor efficient to use the POST method instead, web standards dictate that if the request is not changing data on the server, the GET method should be used.</p>\n\n<p>It will be much more code to encrypt the data than to just use POST.</p>\n" }, { "answer_id": 50232009, "author": "Ravindra Vairagi", "author_id": 6656918, "author_profile": "https://Stackoverflow.com/users/6656918", "pm_score": 3, "selected": false, "text": "<p>Encryption in C# using AES encryption- </p>\n\n<pre><code>protected void Submit(object sender, EventArgs e)\n{\n string name = HttpUtility.UrlEncode(Encrypt(txtName.Text.Trim()));\n string technology = HttpUtility.UrlEncode(Encrypt(ddlTechnology.SelectedItem.Value));\n Response.Redirect(string.Format(\"~/CS2.aspx?name={0}&amp;technology={1}\", name, technology));\n}\n</code></pre>\n\n<p><strong>AES Algorithm Encryption and Decryption functions</strong></p>\n\n<pre><code>private string Encrypt(string clearText)\n{\n string EncryptionKey = \"hyddhrii%2moi43Hd5%%\";\n byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);\n using (Aes encryptor = Aes.Create())\n {\n Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });\n encryptor.Key = pdb.GetBytes(32);\n encryptor.IV = pdb.GetBytes(16);\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))\n {\n cs.Write(clearBytes, 0, clearBytes.Length);\n cs.Close();\n }\n clearText = Convert.ToBase64String(ms.ToArray());\n }\n }\n return clearText;\n}\n\n\nprivate string Decrypt(string cipherText)\n{\n string EncryptionKey = \"hyddhrii%2moi43Hd5%%\";\n cipherText = cipherText.Replace(\" \", \"+\");\n byte[] cipherBytes = Convert.FromBase64String(cipherText);\n using (Aes encryptor = Aes.Create())\n {\n Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });\n encryptor.Key = pdb.GetBytes(32);\n encryptor.IV = pdb.GetBytes(16);\n using (MemoryStream ms = new MemoryStream())\n {\n using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))\n {\n cs.Write(cipherBytes, 0, cipherBytes.Length);\n cs.Close();\n }\n cipherText = Encoding.Unicode.GetString(ms.ToArray());\n }\n }\n return cipherText;\n}\n</code></pre>\n\n<p><strong>To Decrypt</strong></p>\n\n<pre><code>lblName.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString[\"name\"]));\nlblTechnology.Text = Decrypt(HttpUtility.UrlDecode(Request.QueryString[\"technology\"]));\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7072/" ]
I need to encrypt and decrypt a querystring in ASP.NET. The querystring might look something like this: > > <http://www.mysite.com/report.aspx?id=12345&year=2008> > > > How do I go about encrypting the entire querystring so that it looks something like the following? > > <http://www.mysite.com/report.aspx?crypt=asldjfaf32as98df8a> > > > And then, of course, how to I decrypt it? What's the best encryption to use for something like this? TripleDES?
Here is a way to do it in VB From: <http://www.devcity.net/Articles/47/1/encrypt_querystring.aspx> **Wrapper for the encryption code:** Pass your querystring parameters into this, and change the key!!! ``` Private _key as string = "!#$a54?3" Public Function encryptQueryString(ByVal strQueryString As String) As String Dim oES As New ExtractAndSerialize.Encryption64() Return oES.Encrypt(strQueryString, _key) End Function Public Function decryptQueryString(ByVal strQueryString As String) As String Dim oES As New ExtractAndSerialize.Encryption64() Return oES.Decrypt(strQueryString, _key) End Function ``` **Encryption Code:** ``` Imports System Imports System.IO Imports System.Xml Imports System.Text Imports System.Security.Cryptography Public Class Encryption64 Private key() As Byte = {} Private IV() As Byte = {&H12, &H34, &H56, &H78, &H90, &HAB, &HCD, &HEF} Public Function Decrypt(ByVal stringToDecrypt As String, _ ByVal sEncryptionKey As String) As String Dim inputByteArray(stringToDecrypt.Length) As Byte Try key = System.Text.Encoding.UTF8.GetBytes(Left(sEncryptionKey, 8)) Dim des As New DESCryptoServiceProvider() inputByteArray = Convert.FromBase64String(stringToDecrypt) Dim ms As New MemoryStream() Dim cs As New CryptoStream(ms, des.CreateDecryptor(key, IV), _ CryptoStreamMode.Write) cs.Write(inputByteArray, 0, inputByteArray.Length) cs.FlushFinalBlock() Dim encoding As System.Text.Encoding = System.Text.Encoding.UTF8 Return encoding.GetString(ms.ToArray()) Catch e As Exception Return e.Message End Try End Function Public Function Encrypt(ByVal stringToEncrypt As String, _ ByVal SEncryptionKey As String) As String Try key = System.Text.Encoding.UTF8.GetBytes(Left(SEncryptionKey, 8)) Dim des As New DESCryptoServiceProvider() Dim inputByteArray() As Byte = Encoding.UTF8.GetBytes( _ stringToEncrypt) Dim ms As New MemoryStream() Dim cs As New CryptoStream(ms, des.CreateEncryptor(key, IV), _ CryptoStreamMode.Write) cs.Write(inputByteArray, 0, inputByteArray.Length) cs.FlushFinalBlock() Return Convert.ToBase64String(ms.ToArray()) Catch e As Exception Return e.Message End Try End Function End Class ```
240,719
<p>I'm running SQL Server 2000 and I need to export the SQL Statement from all the DTS objects so that they can be parsed and put into a wiki documentation if needed. </p> <p>Is there a way to do that?</p> <p>maybe dumping each DTS object out into a text file with the object name as the file name with the name of the process and the date it was extracted as a file header.</p> <p>thanks.</p>
[ { "answer_id": 240797, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 2, "selected": false, "text": "<p>There is an API with an object model for the DTS packages. You can get the SQL text through this. The Books on Line docs describe this to some extent <a href=\"http://msdn.microsoft.com/en-us/library/aa298646(SQL.80).aspx\" rel=\"nofollow noreferrer\">Here.</a> You can get examples of the object model usage by <a href=\"http://msdn.microsoft.com/en-us/library/aa216414(SQL.80).aspx\" rel=\"nofollow noreferrer\">Saving the DTS package to a Visual BASIC file</a> and looking at what the VB file does to the object model.</p>\n" }, { "answer_id": 1022221, "author": "JAG", "author_id": 16032, "author_profile": "https://Stackoverflow.com/users/16032", "pm_score": 1, "selected": false, "text": "<p>If you want to save some work and you don't mind paying a few bucks there's a <a href=\"http://www.dtsdoc.com\" rel=\"nofollow noreferrer\">tool</a> that fully documents your DTS packages. It outputs to XML too, so it should be relatively easy to get those SQL statements.</p>\n" }, { "answer_id": 1070447, "author": "eksortso", "author_id": 446456, "author_profile": "https://Stackoverflow.com/users/446456", "pm_score": 2, "selected": true, "text": "<p>I have a <a href=\"http://www.python.org/\" rel=\"nofollow noreferrer\">Python 2.6</a> script (easily portable to Python 2.5) that dumps the SQL from the tasks in a DTS package that has been saved as Visual Basic code.</p>\n\n<p>Refer to ConcernedOfTunbridgeWells' post to find out how to save the DTS package to a VB file. After you save a VB file, run this function on it. It will create a folder in the same location as the VB file which contains the code from the package, and it will dump the SQL code that it finds. It assumes the output of the SQL goes into CSV files (see the <code>outExt</code> parameter) or comes from an \"Execute SQL Task\" task, and names the SQL queries after the output file or SQL task. If your package doesn't do anything else, this is an useful solution.</p>\n\n<p>Feel free to clean this code up if you're so inclined.</p>\n\n<pre class=\"lang-py prettyprint-override\"><code># from __future__ import with_statement # Version 2.5 requires this.\nimport os, re\n\ndef dump_sql(infile, outExt=r'csv'):\n \"\"\"Parse a DTS package saved as a .bas file, and dump the SQL code.\n\n Pull out the SQL code and the filename for each task. This process\n depends on the way that DTS saves packages as VB modules.\n\n Keyword arguments:\n infile - The .bas file defining a DTS package.\n outExt - The extension (without a period) of the files exported by the\n data pumps in the DTS package. These are used to rename the\n extracted SQL scripts. If an extract file does not use this\n extension, then the whole name of the extract file is used to\n name the SQL script. (default: csv)\n\n The function produces a folder in the same folder that contains the\n .bas file. It's named like this: if the .bas file is \"DTS package.bas\",\n then the directory will be named \"DTS package_SQL\". The SQL scripts are\n stored in this folder.\n\n \"\"\"\n #Declare all of the RE's used in the script here.\n basExtRE = re.compile(r'\\.bas$', re.IGNORECASE)\n outExtRE = re.compile(r'\\.' + outExt + r'$', re.IGNORECASE)\n startTaskRE = re.compile(r'Set oCustomTask(\\d+) = oTask.CustomTask')\n startSqlRE = re.compile(\n r'oCustomTask(\\d+)\\.(?:Source)?SQLStatement = \"(.*)\"( &amp; vbCrLf)?')\n nextSqlRE = re.compile(\n r'oCustomTask(\\d+)\\.(?:Source)?SQLStatement = oCustomTask\\1\\.'\n r'(?:Source)?SQLStatement &amp; \"(.*)\"( &amp; vbCrLf)?')\n filenameRE = re.compile(\n r'oCustomTask(\\d+)\\.DestinationObjectName = \"(.*)\"')\n descripRE = re.compile(r'oCustomTask(\\d+)\\.Description = \"(.*)\"')\n invalidCharsRE = re.compile(r'[][+/*?&lt;&gt;,.;:\"=\\\\|]')\n\n #Read the file\n with open(infile, 'r') as f:\n\n #Produce the directory for the SQL scripts.\n outfolder = '%s_SQL\\\\' % basExtRE.sub('', infile)\n if not os.path.exists(outfolder):\n os.makedirs(outfolder)\n\n taskNum = -1\n outfile = ''\n sql = []\n\n for line in f:\n line = line.rstrip().lstrip()\n\n if taskNum == -1:\n #Seek the beginning of a task.\n m = startTaskRE.match(line)\n if m is not None:\n taskNum = int(m.group(1))\n elif line == '' and outfile != '':\n #Save the SQL code to a file.\n if sql:\n if os.path.exists(outfile):\n os.unlink(outfile)\n with open(outfile, 'w') as fw:\n fw.writelines([\"%s\" % sqlQ for sqlQ in sql])\n print \"%2d - %s\" % (taskNum, outfile)\n else:\n print \"%2d &gt; No SQL (%s)\" % (\n taskNum, os.path.basename(outfile))\n sql = []\n outfile = ''\n taskNum = -1\n else:\n #Acquire SQL code and filename\n m = startSqlRE.match(line)\n if m:\n #Start assembling the SQL query.\n tnum, sqlQ, lf = m.groups()\n assert int(tnum) == taskNum\n sql = [sqlQ.replace('\"\"', '\"')\n + ('\\n' if lf is not None else '')]\n continue\n m = nextSqlRE.match(line)\n if m:\n #Continue assembling the SQL query\n tnum, sqlQ, lf = m.groups()\n assert int(tnum) == taskNum\n sql.append(sqlQ.replace('\"\"', '\"')\n + ('\\n' if lf is not None else ''))\n continue\n m = descripRE.match(line)\n if m:\n # Get a SQL output filename from the task's\n # description. This always appears near the top of the\n # task's definition.\n tnum, outfile = m.groups()\n assert int(tnum) == taskNum\n outfile = invalidCharsRE.sub('_', outfile)\n outfile = \"%s%s.sql\" % (outfolder, outfile)\n continue\n m = filenameRE.match(line)\n if m:\n # Get a SQL output filename from the task's output\n # filename. This always appears near the bottom of the\n # task's definition, so we overwrite the description if\n # one was found earlier.\n tnum, outfile = m.groups()\n assert int(tnum) == taskNum\n outfile = os.path.basename(outfile)\n outfile = outExtRE.sub('', outfile)\n outfile = \"%s%s.sql\" % (outfolder, outfile)\n continue\n print 'Done.'\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/730/" ]
I'm running SQL Server 2000 and I need to export the SQL Statement from all the DTS objects so that they can be parsed and put into a wiki documentation if needed. Is there a way to do that? maybe dumping each DTS object out into a text file with the object name as the file name with the name of the process and the date it was extracted as a file header. thanks.
I have a [Python 2.6](http://www.python.org/) script (easily portable to Python 2.5) that dumps the SQL from the tasks in a DTS package that has been saved as Visual Basic code. Refer to ConcernedOfTunbridgeWells' post to find out how to save the DTS package to a VB file. After you save a VB file, run this function on it. It will create a folder in the same location as the VB file which contains the code from the package, and it will dump the SQL code that it finds. It assumes the output of the SQL goes into CSV files (see the `outExt` parameter) or comes from an "Execute SQL Task" task, and names the SQL queries after the output file or SQL task. If your package doesn't do anything else, this is an useful solution. Feel free to clean this code up if you're so inclined. ```py # from __future__ import with_statement # Version 2.5 requires this. import os, re def dump_sql(infile, outExt=r'csv'): """Parse a DTS package saved as a .bas file, and dump the SQL code. Pull out the SQL code and the filename for each task. This process depends on the way that DTS saves packages as VB modules. Keyword arguments: infile - The .bas file defining a DTS package. outExt - The extension (without a period) of the files exported by the data pumps in the DTS package. These are used to rename the extracted SQL scripts. If an extract file does not use this extension, then the whole name of the extract file is used to name the SQL script. (default: csv) The function produces a folder in the same folder that contains the .bas file. It's named like this: if the .bas file is "DTS package.bas", then the directory will be named "DTS package_SQL". The SQL scripts are stored in this folder. """ #Declare all of the RE's used in the script here. basExtRE = re.compile(r'\.bas$', re.IGNORECASE) outExtRE = re.compile(r'\.' + outExt + r'$', re.IGNORECASE) startTaskRE = re.compile(r'Set oCustomTask(\d+) = oTask.CustomTask') startSqlRE = re.compile( r'oCustomTask(\d+)\.(?:Source)?SQLStatement = "(.*)"( & vbCrLf)?') nextSqlRE = re.compile( r'oCustomTask(\d+)\.(?:Source)?SQLStatement = oCustomTask\1\.' r'(?:Source)?SQLStatement & "(.*)"( & vbCrLf)?') filenameRE = re.compile( r'oCustomTask(\d+)\.DestinationObjectName = "(.*)"') descripRE = re.compile(r'oCustomTask(\d+)\.Description = "(.*)"') invalidCharsRE = re.compile(r'[][+/*?<>,.;:"=\\|]') #Read the file with open(infile, 'r') as f: #Produce the directory for the SQL scripts. outfolder = '%s_SQL\\' % basExtRE.sub('', infile) if not os.path.exists(outfolder): os.makedirs(outfolder) taskNum = -1 outfile = '' sql = [] for line in f: line = line.rstrip().lstrip() if taskNum == -1: #Seek the beginning of a task. m = startTaskRE.match(line) if m is not None: taskNum = int(m.group(1)) elif line == '' and outfile != '': #Save the SQL code to a file. if sql: if os.path.exists(outfile): os.unlink(outfile) with open(outfile, 'w') as fw: fw.writelines(["%s" % sqlQ for sqlQ in sql]) print "%2d - %s" % (taskNum, outfile) else: print "%2d > No SQL (%s)" % ( taskNum, os.path.basename(outfile)) sql = [] outfile = '' taskNum = -1 else: #Acquire SQL code and filename m = startSqlRE.match(line) if m: #Start assembling the SQL query. tnum, sqlQ, lf = m.groups() assert int(tnum) == taskNum sql = [sqlQ.replace('""', '"') + ('\n' if lf is not None else '')] continue m = nextSqlRE.match(line) if m: #Continue assembling the SQL query tnum, sqlQ, lf = m.groups() assert int(tnum) == taskNum sql.append(sqlQ.replace('""', '"') + ('\n' if lf is not None else '')) continue m = descripRE.match(line) if m: # Get a SQL output filename from the task's # description. This always appears near the top of the # task's definition. tnum, outfile = m.groups() assert int(tnum) == taskNum outfile = invalidCharsRE.sub('_', outfile) outfile = "%s%s.sql" % (outfolder, outfile) continue m = filenameRE.match(line) if m: # Get a SQL output filename from the task's output # filename. This always appears near the bottom of the # task's definition, so we overwrite the description if # one was found earlier. tnum, outfile = m.groups() assert int(tnum) == taskNum outfile = os.path.basename(outfile) outfile = outExtRE.sub('', outfile) outfile = "%s%s.sql" % (outfolder, outfile) continue print 'Done.' ```
240,721
<p>Has anyone used jQuery to populate an autocomplete list on a textbox using ASP.NET webforms? If so, can anyone recommend a good method? From my reading so far, it seems like most people are using delimited lists rather than JSON to bring the items back. I'm open to any ideas that will get me up and running rather quickly. </p>
[ { "answer_id": 240882, "author": "Pablo", "author_id": 22696, "author_profile": "https://Stackoverflow.com/users/22696", "pm_score": 2, "selected": true, "text": "<p>There are many, many examples on the web. I've used this one before, and if I recall you only need to create an aspx that will return matching terms as a <code>&lt;BR/&gt;</code> separated list:</p>\n\n<p><a href=\"http://www.dyve.net/jquery/?autocomplete\" rel=\"nofollow noreferrer\">http://www.dyve.net/jquery/?autocomplete</a></p>\n\n<p>The documentation shows php in the example, but there's no difference in the way the plugin itself works and I didn't have to do anything special as a result.</p>\n\n<p>From the documentation:</p>\n\n<pre><code>&gt; $(\"#input_box\").autocomplete(\"my_autocomplete_backend.php\");\n</code></pre>\n\n<blockquote>\n <p>In the above example, Autocomplete\n expects an input element with the id\n \"input_box\" to exist. When a user\n starts typing in the input box, the\n autocompleter will request\n my_autocomplete_backend.php with a GET\n parameter named q that contains the\n current value of the input box. Let's\n assume that the user has typed\n \"foo\"(without quotes). Autocomplete\n will then request\n my_autocomplete_backend.php?q=foo.</p>\n \n <p>The backend should output possible\n values for the autocompleter, each on\n a single line. Output cannot contain\n the pipe symbol \"|\", since that is\n considered a separator (more on that\n later).</p>\n \n <p>An appropiate simple output would be:\n foo \n fool \n foot \n footloose \n foo fighters\n food fight</p>\n</blockquote>\n" }, { "answer_id": 423531, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>I made a tutorial to do this with asp.net mvc but it should be almost identical for traditional webforms:</p>\n\n<p><a href=\"http://blogs.msdn.com/joecar/archive/2009/01/08/autocomplete-with-asp-net-mvc-and-jquery.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/joecar/archive/2009/01/08/autocomplete-with-asp-net-mvc-and-jquery.aspx</a></p>\n" }, { "answer_id": 6241874, "author": "ilmatte", "author_id": 368116, "author_profile": "https://Stackoverflow.com/users/368116", "pm_score": 1, "selected": false, "text": "<p>I wrote an Asp.Net WebControl and some Asp.Net MVC extension methods wrapping the JQuery UI autocomplete widget.</p>\n\n<p>I wrote documentation as well about how to implement a working resource providing a JSon result.</p>\n\n<p>You can find it at:</p>\n\n<p><a href=\"http://autocompletedotnet.codeplex.com/\" rel=\"nofollow\">http://autocompletedotnet.codeplex.com/</a></p>\n\n<p>Hope it can help</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ]
Has anyone used jQuery to populate an autocomplete list on a textbox using ASP.NET webforms? If so, can anyone recommend a good method? From my reading so far, it seems like most people are using delimited lists rather than JSON to bring the items back. I'm open to any ideas that will get me up and running rather quickly.
There are many, many examples on the web. I've used this one before, and if I recall you only need to create an aspx that will return matching terms as a `<BR/>` separated list: <http://www.dyve.net/jquery/?autocomplete> The documentation shows php in the example, but there's no difference in the way the plugin itself works and I didn't have to do anything special as a result. From the documentation: ``` > $("#input_box").autocomplete("my_autocomplete_backend.php"); ``` > > In the above example, Autocomplete > expects an input element with the id > "input\_box" to exist. When a user > starts typing in the input box, the > autocompleter will request > my\_autocomplete\_backend.php with a GET > parameter named q that contains the > current value of the input box. Let's > assume that the user has typed > "foo"(without quotes). Autocomplete > will then request > my\_autocomplete\_backend.php?q=foo. > > > The backend should output possible > values for the autocompleter, each on > a single line. Output cannot contain > the pipe symbol "|", since that is > considered a separator (more on that > later). > > > An appropiate simple output would be: > foo > fool > foot > footloose > foo fighters > food fight > > >
240,725
<p>I have OS X 10.5 set up with the precompiled versions of PHP 5 and Apache 2. I'm trying to set up the Zend Debugger, but with no luck. Here's what I did:</p> <ul> <li>I downloaded <code>ZendDebugger-5.2.14-darwin8.6-uni.tar</code></li> <li>I created the directory <code>/Developer/Extras/PHP</code> and set the permissions to: <ul> <li>Permissions: <code>drwxrwxr-x</code></li> <li>Owner: <code>root:admin</code></li> </ul></li> <li>I copied <code>ZendDebugger.so</code> from the <code>5_2_x_comp</code> directory to <code>/Developer/Extras/PHP</code></li> <li><p>I updated <code>/etc/php.ini</code> file, adding the following lines:</p> <pre><code>zend_extension=/Developer/Extras/PHP/ZendDebugger.so zend_debugger.expose_remotely=always zend_debugger.connector_port=10013 zend_debugger.allow_hosts=127.0.0.1 </code></pre></li> <li><p>I restarted Apache via the System Preferences "Sharing" panel</p></li> </ul> <p>When I run <code>phpinfo()</code> within a PHP file, I get no mention of the Zend Debugger. When I run <code>php -m</code> from the command line, it shows the Zend Debugger is loaded. Both state that they're running the same version of PHP, and loading the same INI file.</p> <p>Anyone have another suggestion for me to try?</p>
[ { "answer_id": 240830, "author": "Barrett Conrad", "author_id": 1227, "author_profile": "https://Stackoverflow.com/users/1227", "pm_score": 3, "selected": true, "text": "<p>If I remember correctly, this problem is do to the fact that the Zend Debugger is compiled for 32-bit Apache while the Apache that comes with Max OS 10.5 is compiled as 64-bit application. Until Zend comes out with a 64-bit version, you have two options: </p>\n\n<p>1) <a href=\"http://www.entropy.ch/phpbb2/viewtopic.php?t=2905\" rel=\"nofollow noreferrer\">Restart Apache manually into 32-bit</a></p>\n\n<p>2) Recompile Apache and PHP in 32-bit mode.</p>\n\n<p>I haven't actually gotten around to doing either yet, but I think I am leaning to recompiling to avoid future problems. </p>\n" }, { "answer_id": 270352, "author": "inxilpro", "author_id": 12549, "author_profile": "https://Stackoverflow.com/users/12549", "pm_score": 1, "selected": false, "text": "<p>Restarting in 32-bit mode did the trick. For those of you who want to be able to do this easily, here's a little bit of AppleScript:</p>\n\n<pre><code>do shell script \"apachectl stop\" with administrator privileges\ndo shell script \"arch -i386 /usr/sbin/httpd\" with administrator privileges\n</code></pre>\n\n<p>It's nice to have sitting somewhere so you can quickly pop into 32-bit mode when needed.</p>\n" }, { "answer_id": 769605, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Me too, HOURS!! Thanks so much!!\nAlso if for some reason you need to restart apache/httpd after running this (e.g. you need to make a change in your php.ini) but when you run \"sudo arch -i386 /usr/sbin/httpd\" you're getting this error:</p>\n\n<p>(48)Address already in use: make_sock: could not bind to address [::]:80</p>\n\n<p>type this in a terminal window:\nsudo killall httpd</p>\n\n<p>then \"sudo arch -i386 /usr/sbin/httpd\" should work fine to restart apache/httpd.</p>\n" }, { "answer_id": 7129531, "author": "NJordan", "author_id": 903411, "author_profile": "https://Stackoverflow.com/users/903411", "pm_score": 1, "selected": false, "text": "<p>Zend released the 64bit version for Mac OSX, so just download the file from <a href=\"http://www.zend.com/en/products/studio/downloads\" rel=\"nofollow\">http&#58;//www.zend.com/en/products/studio/downloads</a> and procede as normal.</p>\n\n<p>You will have to register and answer some questions, but it worked for me.</p>\n\n<p>Good Luck.</p>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12549/" ]
I have OS X 10.5 set up with the precompiled versions of PHP 5 and Apache 2. I'm trying to set up the Zend Debugger, but with no luck. Here's what I did: * I downloaded `ZendDebugger-5.2.14-darwin8.6-uni.tar` * I created the directory `/Developer/Extras/PHP` and set the permissions to: + Permissions: `drwxrwxr-x` + Owner: `root:admin` * I copied `ZendDebugger.so` from the `5_2_x_comp` directory to `/Developer/Extras/PHP` * I updated `/etc/php.ini` file, adding the following lines: ``` zend_extension=/Developer/Extras/PHP/ZendDebugger.so zend_debugger.expose_remotely=always zend_debugger.connector_port=10013 zend_debugger.allow_hosts=127.0.0.1 ``` * I restarted Apache via the System Preferences "Sharing" panel When I run `phpinfo()` within a PHP file, I get no mention of the Zend Debugger. When I run `php -m` from the command line, it shows the Zend Debugger is loaded. Both state that they're running the same version of PHP, and loading the same INI file. Anyone have another suggestion for me to try?
If I remember correctly, this problem is do to the fact that the Zend Debugger is compiled for 32-bit Apache while the Apache that comes with Max OS 10.5 is compiled as 64-bit application. Until Zend comes out with a 64-bit version, you have two options: 1) [Restart Apache manually into 32-bit](http://www.entropy.ch/phpbb2/viewtopic.php?t=2905) 2) Recompile Apache and PHP in 32-bit mode. I haven't actually gotten around to doing either yet, but I think I am leaning to recompiling to avoid future problems.
240,755
<p>I have to create the sin function from scratch in my Comp Sci class, and I am getting close to a solution. However, I am still having a few problems. If I put in a value of .5PI or less it works, but otherwise I get the incorrect result. Here is the code I have so far:</p> <pre><code>double i=1; double sinSoFar = 0; int term = 1; while(i &gt;= .000001) { i = pow(-1, term + 1) * pow(sinOf, 2*term-1) / factorial(2*term-1); sinSoFar=sinSoFar + i; term++; } </code></pre>
[ { "answer_id": 240831, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 2, "selected": false, "text": "<p>Some advices:</p>\n\n<ul>\n<li>Start with term = 0. The canonical MacLaurin expansion also does</li>\n<li>compute the powers and the factorial <em>while you are cycling</em> (that is, updating them at each step). Maybe the problem is within pow() or factorial().</li>\n</ul>\n\n<p>EDIT. Suggestion: once you have computed the k-th term, you can compute the (k+1)-th one by:</p>\n\n<ul>\n<li>Multiplying by (-1)</li>\n<li>Multiplying by sinOf^2</li>\n<li>Dividing by (2k+2)(2k+3)</li>\n</ul>\n\n<p>In this way you can completely <em>avoid</em> the computation of powers and factorials.</p>\n" }, { "answer_id": 240859, "author": "Luiz Fernando Penkal", "author_id": 4355, "author_profile": "https://Stackoverflow.com/users/4355", "pm_score": 4, "selected": true, "text": "<p>Like Federico pointed, the problem probably is in your factorial() or pow(). I ran a test that worked fine replacing your functions with the pow() function provided in the Math class, and this factorial():</p>\n\n<pre><code>public static long factorial(long n) {\n if (n &lt; 0) throw new RuntimeException(\"Underflow error in factorial\");\n else if (n &gt; 20) throw new RuntimeException(\"Overflow error in factorial\");\n else if (n == 0) return 1;\n else return n * factorial(n-1);\n} \n</code></pre>\n" }, { "answer_id": 241006, "author": "billjamesdev", "author_id": 13824, "author_profile": "https://Stackoverflow.com/users/13824", "pm_score": 0, "selected": false, "text": "<p>As far as values outside of 0 - 1/2PI, they can all be computed from values inside the range.</p>\n\n<pre><code>// First, normalize argument angle (ang) to -PI to PI, \n// by adding/subtracting 2*PI until it's within range\nif ( ang &gt; 1/2PI ) {\n sin = sin ( PI - ang );\n}\nelse if ( ang &lt; 0 ) {\n sin = -1 * sin( -1 * ang );\n}\nelse {\n // your original code\n}\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31665/" ]
I have to create the sin function from scratch in my Comp Sci class, and I am getting close to a solution. However, I am still having a few problems. If I put in a value of .5PI or less it works, but otherwise I get the incorrect result. Here is the code I have so far: ``` double i=1; double sinSoFar = 0; int term = 1; while(i >= .000001) { i = pow(-1, term + 1) * pow(sinOf, 2*term-1) / factorial(2*term-1); sinSoFar=sinSoFar + i; term++; } ```
Like Federico pointed, the problem probably is in your factorial() or pow(). I ran a test that worked fine replacing your functions with the pow() function provided in the Math class, and this factorial(): ``` public static long factorial(long n) { if (n < 0) throw new RuntimeException("Underflow error in factorial"); else if (n > 20) throw new RuntimeException("Overflow error in factorial"); else if (n == 0) return 1; else return n * factorial(n-1); } ```
240,764
<p>I have seen some websites use the following tag:</p> <pre><code>&lt;meta type="title" content="Title of the page" /&gt; </code></pre> <p>Is it needed when you have a <code>&lt;title&gt;</code>?</p> <p>Also, what's the best formatting for a page title? Some ideas:</p> <ul> <li>Page Description :: Company Name</li> <li>Page Description - Company Name</li> <li>Page Description &lt;> Company Name</li> <li>Company Name: Page Description</li> <li>...</li> </ul> <p>Does it matter to Google/Yahoo/etc? Do you include the company name or a general description of the site in the title on every page? </p>
[ { "answer_id": 240867, "author": "Leandro López", "author_id": 22695, "author_profile": "https://Stackoverflow.com/users/22695", "pm_score": 2, "selected": false, "text": "<p>Search engines often ignore meta tags as in the past they where used for spamming purposes. The best tag for title is precisely <code>&lt;title&gt;</code>.</p>\n\n<p>As the best formatting for the title there is no best recipe, but instead try to make the title as descriptive as possible of the real contents of the page.</p>\n" }, { "answer_id": 241004, "author": "IAdapter", "author_id": 30453, "author_profile": "https://Stackoverflow.com/users/30453", "pm_score": 1, "selected": false, "text": "<p>Meta Robots: This tag enjoys full support, but you only need\nit if you DO NOT want your pages indexed.</p>\n\n<p>Meta Description: This tag enjoys much support, and it is well worth using.</p>\n\n<p>Meta Keywords: This tag is only supported by some major crawlers\nand probably isn't worth the time to implement.</p>\n\n<p>Meta Else: Any other meta tag you see is ignored by the major crawlers,\nthough they may be used by specialized search engines. </p>\n" }, { "answer_id": 244930, "author": "Robert Elwell", "author_id": 23102, "author_profile": "https://Stackoverflow.com/users/23102", "pm_score": 0, "selected": false, "text": "<p> is what you want to use, because it stands out more than meta tags to most search engines.</p>\n\n<p>My suggestion is to put the keywords that matter first, and avoid repeating the name of your business other than on the homepage, because this only serves to dilute the value of the title text.</p>\n" }, { "answer_id": 404992, "author": "cowgod", "author_id": 6406, "author_profile": "https://Stackoverflow.com/users/6406", "pm_score": 3, "selected": true, "text": "<p>The <code>&lt;meta type=\"title\"&gt;</code> tag has little rank or relevance to search engine crawlers. The good old <code>&lt;title&gt;</code> tag is far and away the <a href=\"http://www.w3.org/QA/Tips/good-titles\" rel=\"nofollow noreferrer\">most important element of a good web page</a>.</p>\n\n<p>As for the format of the title, I think there is good advice in <a href=\"http://www.standards-schmandards.com/2004/title-text-separators/\" rel=\"nofollow noreferrer\">this article at Standards Schmandards</a>:</p>\n\n<blockquote>\n <p>If the title contains the name of the\n site, the name of the site should be\n placed at the end of the title. This\n makes sure that multiple bookmarks\n from the same site are easy to browse\n through in the bookmarks folder and\n listeners to your page get the most\n important information first.</p>\n</blockquote>\n\n<p>I would highly suggest that you <em>do</em> include the company name or site name at the end of each title because:</p>\n\n<ol>\n<li>Consistency is always a good idea.</li>\n<li>Newer browsers like Firefox 3 allow you to search your history and bookmarks by page titles, so users can easily get a view of all the pages they've visited on your site by simply typing in your company name or site name.</li>\n<li>People that use screen readers will have no idea what website they are visiting if it isn't listed somewhere on the page.</li>\n</ol>\n\n<p>However, I would not put a description of the site anywhere but on the home page because that would make the title unnecessarily long and would frustrate screen reader users because they would have to make an extra effort to skip that information on every page they visit.</p>\n\n<p>If you do decide to put the company name in your title, keep these things in mind (also from <a href=\"http://www.standards-schmandards.com/2004/title-text-separators/\" rel=\"nofollow noreferrer\">Standards Schmandards</a>):</p>\n\n<blockquote>\n <ul>\n <li>The separator character should be\n distinct so that users understand\n that it is a separator. (I.e. it\n should not appear as part of text\n items in the title).</li>\n <li>Prime candidates to use as separators are the vertical bar (|),\n the dot (·) and the dash (-).</li>\n <li>Regardless of the character you pick, <em>it is important to surround it\n with whitespace</em>. This will aid both\n sighted visitors and listeners as it\n will distinguish the character from\n the title text.</li>\n </ul>\n</blockquote>\n\n<p>Based on all the information herein, that essentially makes the second example in your question the obvious choice:</p>\n\n<pre><code>&lt;title&gt;\n Page Description - Company Name\n&lt;/title&gt;\n</code></pre>\n" } ]
2008/10/27
[ "https://Stackoverflow.com/questions/240764", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
I have seen some websites use the following tag: ``` <meta type="title" content="Title of the page" /> ``` Is it needed when you have a `<title>`? Also, what's the best formatting for a page title? Some ideas: * Page Description :: Company Name * Page Description - Company Name * Page Description <> Company Name * Company Name: Page Description * ... Does it matter to Google/Yahoo/etc? Do you include the company name or a general description of the site in the title on every page?
The `<meta type="title">` tag has little rank or relevance to search engine crawlers. The good old `<title>` tag is far and away the [most important element of a good web page](http://www.w3.org/QA/Tips/good-titles). As for the format of the title, I think there is good advice in [this article at Standards Schmandards](http://www.standards-schmandards.com/2004/title-text-separators/): > > If the title contains the name of the > site, the name of the site should be > placed at the end of the title. This > makes sure that multiple bookmarks > from the same site are easy to browse > through in the bookmarks folder and > listeners to your page get the most > important information first. > > > I would highly suggest that you *do* include the company name or site name at the end of each title because: 1. Consistency is always a good idea. 2. Newer browsers like Firefox 3 allow you to search your history and bookmarks by page titles, so users can easily get a view of all the pages they've visited on your site by simply typing in your company name or site name. 3. People that use screen readers will have no idea what website they are visiting if it isn't listed somewhere on the page. However, I would not put a description of the site anywhere but on the home page because that would make the title unnecessarily long and would frustrate screen reader users because they would have to make an extra effort to skip that information on every page they visit. If you do decide to put the company name in your title, keep these things in mind (also from [Standards Schmandards](http://www.standards-schmandards.com/2004/title-text-separators/)): > > * The separator character should be > distinct so that users understand > that it is a separator. (I.e. it > should not appear as part of text > items in the title). > * Prime candidates to use as separators are the vertical bar (|), > the dot (·) and the dash (-). > * Regardless of the character you pick, *it is important to surround it > with whitespace*. This will aid both > sighted visitors and listeners as it > will distinguish the character from > the title text. > > > Based on all the information herein, that essentially makes the second example in your question the obvious choice: ``` <title> Page Description - Company Name </title> ```