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
178,462
<p>I'm trying to setup an Apache/PHP/Postgresql server locally on my machine. I'm using Windows vista business 32bit. I tried to install everything manually (one thing at a time, apache, postgresql and php (all the latest stable releases)) and after I get everything up and running.</p> <p>Whenever I try to run a script on my machine, I get a "What do you want to do with the *.php file?" dialog. The dialog is the browser's open/save dialog</p> <p>I'm just trying to get the output of phpinfo() to make sure everything is up and running...</p> <p>I already tried to mess around a bit with the Apache conf file, but since I don't know much about what I'm doing, I reinstalled everything again and the problem is still there. I kinda get the feeling it must have something to do with the PHP thingy isn't correctly installed.</p> <p>When i try to get the output of phpinfo as in:</p> <pre><code>&lt;pre&gt;&lt;?php phpinfo(); ?&gt;&lt;/pre&gt; </code></pre> <p>I get the browser's "Open/Save" dialog for the *.php file.</p>
[ { "answer_id": 178487, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 3, "selected": true, "text": "<p>You should have something like this in your httpd.conf file:</p>\n\n<pre><code>LoadModule php5_module \"c:/php/php5apache2_2.dll\"\nAddType application/x-httpd-php .php\nPHPIniDir \"c:/php\"\n</code></pre>\n\n<p>Make sure that's in place, and don't forget to restart apache!</p>\n\n<p>In Windows, the default location for your conf file is <code>C:\\Program Files\\Apache Group\\Apache2\\conf\\httpd.conf</code></p>\n" }, { "answer_id": 178494, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>are you on Windows?</p>\n\n<p>I use <a href=\"http://www.wampserver.com/en/\" rel=\"nofollow noreferrer\">Wamp server</a>, which is an excellent way of getting Apache, MySQL and PHP installed and configured without any hassle on Windows.</p>\n\n<p>If you want to use Postgres instead, provided that you've got it installed separately it will work fine. (one great thing you can do with Wamp is add and remove PHP extensions via a GUI pretty much on-the-fly, and pgsql is one of them).</p>\n" }, { "answer_id": 178495, "author": "David Thornley", "author_id": 14148, "author_profile": "https://Stackoverflow.com/users/14148", "pm_score": 0, "selected": false, "text": "<p>Maybe somebody can help, but you'd be much better off if you'd provide some relevant details.</p>\n\n<p>What sort of system are you using? Be specific.</p>\n\n<p>What do you mean by \"everything up and running\"?</p>\n\n<p>What are you doing when you \"try to run a script\"?</p>\n\n<p>What installation procedures did you use? (If you were following them off a script or how-to, we at least need to know where to find the script or how-to.)</p>\n\n<p>We don't automatically know these things. What seems obvious to you may not be clear to us, and what seems irrelevant to you may turn out to be crucial.</p>\n" }, { "answer_id": 178502, "author": "Svante Svenson", "author_id": 19707, "author_profile": "https://Stackoverflow.com/users/19707", "pm_score": 0, "selected": false, "text": "<p>In httpd.conf, make sure the PHP module is being loaded and that that line isn't commented out. (Comments in httpd.conf starts with #.)</p>\n\n<p>Also what OS are you running?</p>\n" }, { "answer_id": 178510, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 1, "selected": false, "text": "<p>You can also have a look at the official page of PHP in the <a href=\"http://hu.php.net/manual/en/install.php\" rel=\"nofollow noreferrer\">install section</a>.</p>\n\n<p>There is a closer link if you are on <a href=\"http://hu.php.net/manual/en/install.windows.php\" rel=\"nofollow noreferrer\">Windows</a>.</p>\n\n<p>And you can also use some precompiled installer for this like <a href=\"http://www.apachefriends.org/en/xampp.html\" rel=\"nofollow noreferrer\">XAMMP</a> and install Postgres after all is set up and running with the web server and php.</p>\n" }, { "answer_id": 178513, "author": "Ronald Conco", "author_id": 16092, "author_profile": "https://Stackoverflow.com/users/16092", "pm_score": 0, "selected": false, "text": "<p>I had the same problem, You need to configure apache and add the php module...\ne.g I compiled the php from source as well as the apache. After doing so I then copied the libphp5.so from php/lib dir in to the apache/modules dir. Than you have to add php in the http.conf </p>\n\n<p>LoadModule php5_module modules/libphp5.so</p>\n\n<p>AddHandler php5-script php</p>\n\n<p>you can then restart apache....it's not the most elegant of solutions but it works. </p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24098/" ]
I'm trying to setup an Apache/PHP/Postgresql server locally on my machine. I'm using Windows vista business 32bit. I tried to install everything manually (one thing at a time, apache, postgresql and php (all the latest stable releases)) and after I get everything up and running. Whenever I try to run a script on my machine, I get a "What do you want to do with the \*.php file?" dialog. The dialog is the browser's open/save dialog I'm just trying to get the output of phpinfo() to make sure everything is up and running... I already tried to mess around a bit with the Apache conf file, but since I don't know much about what I'm doing, I reinstalled everything again and the problem is still there. I kinda get the feeling it must have something to do with the PHP thingy isn't correctly installed. When i try to get the output of phpinfo as in: ``` <pre><?php phpinfo(); ?></pre> ``` I get the browser's "Open/Save" dialog for the \*.php file.
You should have something like this in your httpd.conf file: ``` LoadModule php5_module "c:/php/php5apache2_2.dll" AddType application/x-httpd-php .php PHPIniDir "c:/php" ``` Make sure that's in place, and don't forget to restart apache! In Windows, the default location for your conf file is `C:\Program Files\Apache Group\Apache2\conf\httpd.conf`
178,473
<p>I have three TextBox controls on the page</p> <pre><code>&lt;asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox_TextChanged" TabIndex="1"&gt; &lt;asp:TextBox ID="TextBox2" runat="server" AutoPostBack="True" OnTextChanged="TextBox_TextChanged" TabIndex="2"&gt; &lt;asp:TextBox ID="TextBox3" runat="server" AutoPostBack="True" OnTextChanged="TextBox_TextChanged" TabIndex="3"&gt; </code></pre> <p>and an event handler</p> <pre><code>protected void TextBox_TextChanged(object sender, EventArgs e) { WebControl changed_control = (WebControl)sender; var next_controls = from WebControl control in changed_control.Parent.Controls where control.TabIndex &gt; changed_control.TabIndex orderby control.TabIndex select control; next_controls.DefaultIfEmpty(changed_control).First().Focus(); } </code></pre> <p>The meaning of this code is to automatically select TextBox with next TabIndex after page post back (see <a href="https://stackoverflow.com/questions/173810/autopostback-with-textbox-loses-focus-question-made-clearer">Little JB's problem</a>). In reality I receive InvalidCastException because it's impossible to cast from System.Web.UI.LiteralControl (WebControl.Controls contains actually LiteralControls) to System.Web.UI.WebControls.WebControl. </p> <p>I am interested is it possible to modify this aproach somehow to receive working solution? Thank you!</p>
[ { "answer_id": 178507, "author": "Paul Nearney", "author_id": 24071, "author_profile": "https://Stackoverflow.com/users/24071", "pm_score": 1, "selected": false, "text": "<p>You should be able to use the OfType method, to only return controls of a given type.</p>\n\n<p>e.g. </p>\n\n<pre><code>var nextcontrols = from WebControl control in \n Changed_control.Parent.Controls.OfType&lt;TextBox&gt;()... etc\n</code></pre>\n" }, { "answer_id": 178518, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 4, "selected": true, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/bb360913.aspx\" rel=\"noreferrer\">OfType</a></p>\n\n<pre><code>from control in changed_control\n .Parent\n .Controls\n .OfType&lt;WebControl&gt;()\n</code></pre>\n" }, { "answer_id": 178522, "author": "Dan Goldstein", "author_id": 23427, "author_profile": "https://Stackoverflow.com/users/23427", "pm_score": 0, "selected": false, "text": "<p>The problem is that LiteralControl does not inherit from WebControl. It can't have the focus though, so it's OK to not select them. In your LINQ statement, add another condition checking for a WebControl. So your where line should be <code>where control.TabIndex &gt; changed_control.TabIndex &amp;&amp; control is WebControl</code>.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11256/" ]
I have three TextBox controls on the page ``` <asp:TextBox ID="TextBox1" runat="server" AutoPostBack="True" OnTextChanged="TextBox_TextChanged" TabIndex="1"> <asp:TextBox ID="TextBox2" runat="server" AutoPostBack="True" OnTextChanged="TextBox_TextChanged" TabIndex="2"> <asp:TextBox ID="TextBox3" runat="server" AutoPostBack="True" OnTextChanged="TextBox_TextChanged" TabIndex="3"> ``` and an event handler ``` protected void TextBox_TextChanged(object sender, EventArgs e) { WebControl changed_control = (WebControl)sender; var next_controls = from WebControl control in changed_control.Parent.Controls where control.TabIndex > changed_control.TabIndex orderby control.TabIndex select control; next_controls.DefaultIfEmpty(changed_control).First().Focus(); } ``` The meaning of this code is to automatically select TextBox with next TabIndex after page post back (see [Little JB's problem](https://stackoverflow.com/questions/173810/autopostback-with-textbox-loses-focus-question-made-clearer)). In reality I receive InvalidCastException because it's impossible to cast from System.Web.UI.LiteralControl (WebControl.Controls contains actually LiteralControls) to System.Web.UI.WebControls.WebControl. I am interested is it possible to modify this aproach somehow to receive working solution? Thank you!
[OfType](http://msdn.microsoft.com/en-us/library/bb360913.aspx) ``` from control in changed_control .Parent .Controls .OfType<WebControl>() ```
178,479
<p>What are the best workarounds for using a SQL <code>IN</code> clause with instances of <code>java.sql.PreparedStatement</code>, which is not supported for multiple values due to SQL injection attack security issues: One <code>?</code> placeholder represents one value, rather than a list of values.</p> <p>Consider the following SQL statement:</p> <pre><code>SELECT my_column FROM my_table where search_column IN (?) </code></pre> <p>Using <code>preparedStatement.setString( 1, "'A', 'B', 'C'" );</code> is essentially a non-working attempt at a workaround of the reasons for using <code>?</code> in the first place. </p> <p>What workarounds are available?</p>
[ { "answer_id": 178505, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 3, "selected": false, "text": "<p>I've never tried it, but would .setArray() do what you're looking for?</p>\n\n<p><strong>Update</strong>: Evidently not. setArray only seems to work with a java.sql.Array that comes from an ARRAY column that you've retrieved from a previous query, or a subquery with an ARRAY column.</p>\n" }, { "answer_id": 178517, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "<p>I suppose you could (using basic string manipulation) generate the query string in the <code>PreparedStatement</code> to have a number of <code>?</code>'s matching the number of items in your list. </p>\n\n<p>Of course if you're doing that you're just a step away from generating a giant chained <code>OR</code> in your query, but without having the right number of <code>?</code> in the query string, I don't see how else you can work around this.</p>\n" }, { "answer_id": 178635, "author": "stjohnroe", "author_id": 2985, "author_profile": "https://Stackoverflow.com/users/2985", "pm_score": 1, "selected": false, "text": "<p>try using the instr function?</p>\n\n<pre><code>select my_column from my_table where instr(?, ','||search_column||',') &gt; 0\n</code></pre>\n\n<p>then</p>\n\n<pre><code>ps.setString(1, \",A,B,C,\"); \n</code></pre>\n\n<p>Admittedly this is a bit of a dirty hack, but it does reduce the opportunities for sql injection. Works in oracle anyway.</p>\n" }, { "answer_id": 178650, "author": "Carl Smotricz", "author_id": 172211, "author_profile": "https://Stackoverflow.com/users/172211", "pm_score": 0, "selected": false, "text": "<p>Just for completeness: So long as the set of values is not too large, you <em>could</em> also simply string-construct a statement like</p>\n\n<pre><code>... WHERE tab.col = ? OR tab.col = ? OR tab.col = ?\n</code></pre>\n\n<p>which you could then pass to prepare(), and then use setXXX() in a loop to set all the values. This looks yucky, but many \"big\" commercial systems routinely do this kind of thing until they hit DB-specific limits, such as 32 KB (I think it is) for statements in Oracle.</p>\n\n<p>Of course you need to ensure that the set will never be unreasonably large, or do error trapping in the event that it is.</p>\n" }, { "answer_id": 179144, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Following Adam's idea. Make your prepared statement sort of select my_column from my_table where search_column in (#)\nCreate a String x and fill it with a number of \"?,?,?\" depending on your list of values\nThen just change the # in the query for your new String x an populate</p>\n" }, { "answer_id": 180872, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 3, "selected": false, "text": "<p>An unpleasant work-around, but certainly feasible is to use a nested query. Create a temporary table MYVALUES with a column in it. Insert your list of values into the MYVALUES table. Then execute </p>\n\n<pre><code>select my_column from my_table where search_column in ( SELECT value FROM MYVALUES )\n</code></pre>\n\n<p>Ugly, but a viable alternative if your list of values is very large.</p>\n\n<p>This technique has the added advantage of potentially better query plans from the optimizer (check a page for multiple values, tablescan only once instead once per value, etc) may save on overhead if your database doesn't cache prepared statements. Your \"INSERTS\" would need to be done in batch and the MYVALUES table may need to be tweaked to have minimal locking or other high-overhead protections.</p>\n" }, { "answer_id": 189347, "author": "Vladimir Dyuzhev", "author_id": 1163802, "author_profile": "https://Stackoverflow.com/users/1163802", "pm_score": 4, "selected": false, "text": "<p>No simple way AFAIK.\nIf the target is to keep statement cache ratio high (i.e to not create a statement per every parameter count), you may do the following:</p>\n\n<ol>\n<li><p>create a statement with a few (e.g. 10) parameters:</p>\n\n<p>... WHERE A IN (?,?,?,?,?,?,?,?,?,?) ...</p></li>\n<li><p>Bind all actuall parameters</p>\n\n<p>setString(1,\"foo\");\nsetString(2,\"bar\");</p></li>\n<li><p>Bind the rest as NULL</p>\n\n<p>setNull(3,Types.VARCHAR)\n...\nsetNull(10,Types.VARCHAR)</p></li>\n</ol>\n\n<p>NULL never matches anything, so it gets optimized out by the SQL plan builder.</p>\n\n<p>The logic is easy to automate when you pass a List into a DAO function:</p>\n\n<pre><code>while( i &lt; param.size() ) {\n ps.setString(i+1,param.get(i));\n i++;\n}\n\nwhile( i &lt; MAX_PARAMS ) {\n ps.setNull(i+1,Types.VARCHAR);\n i++;\n}\n</code></pre>\n" }, { "answer_id": 189399, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 9, "selected": true, "text": "<p>An analysis of the various options available, and the pros and cons of each is available in Jeanne Boyarsky's <em><a href=\"http://www.javaranch.com/journal/200510/Journal200510.jsp#a2\" rel=\"nofollow noreferrer\">Batching Select Statements in JDBC</a></em> entry on JavaRanch Journal.</p>\n<p>The suggested options are:</p>\n<ul>\n<li>Prepare <code>SELECT my_column FROM my_table WHERE search_column = ?</code>, execute it for each value and UNION the results client-side. Requires only one prepared statement. Slow and painful.</li>\n<li>Prepare <code>SELECT my_column FROM my_table WHERE search_column IN (?,?,?)</code> and execute it. Requires one prepared statement per size-of-IN-list. Fast and obvious.</li>\n<li>Prepare <code>SELECT my_column FROM my_table WHERE search_column = ? ; SELECT my_column FROM my_table WHERE search_column = ? ; ...</code> and execute it. [Or use <code>UNION ALL</code> in place of those semicolons. --ed] Requires one prepared statement per size-of-IN-list. Stupidly slow, strictly worse than <code>WHERE search_column IN (?,?,?)</code>, so I don't know why the blogger even suggested it.</li>\n<li>Use a stored procedure to construct the result set.</li>\n<li>Prepare N different size-of-IN-list queries; say, with 2, 10, and 50 values. To search for an IN-list with 6 different values, populate the size-10 query so that it looks like <code>SELECT my_column FROM my_table WHERE search_column IN (1,2,3,4,5,6,6,6,6,6)</code>. Any decent server will optimize out the duplicate values before running the query.</li>\n</ul>\n<p>None of these options are ideal.</p>\n<p>The best option if you are using JDBC4 and a server that supports <code>x = ANY(y)</code>, is to use <code>PreparedStatement.setArray</code> as described in <a href=\"https://stackoverflow.com/questions/178479/preparedstatement-in-clause-alternatives/10240302#10240302\">Boris's anwser</a>.</p>\n<p>There doesn't seem to be any way to make <code>setArray</code> work with IN-lists, though.</p>\n<hr />\n<p>Sometimes SQL statements are loaded at runtime (e.g., from a properties file) but require a variable number of parameters. In such cases, first define the query:</p>\n<pre class=\"lang-none prettyprint-override\"><code>query=SELECT * FROM table t WHERE t.column IN (?)\n</code></pre>\n<p>Next, load the query. Then determine the number of parameters prior to running it. Once the parameter count is known, run:</p>\n<pre class=\"lang-java prettyprint-override\"><code>sql = any( sql, count );\n</code></pre>\n<p>For example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>/**\n * Converts a SQL statement containing exactly one IN clause to an IN clause\n * using multiple comma-delimited parameters.\n *\n * @param sql The SQL statement string with one IN clause.\n * @param params The number of parameters the SQL statement requires.\n * @return The SQL statement with (?) replaced with multiple parameter\n * placeholders.\n */\npublic static String any(String sql, final int params) {\n // Create a comma-delimited list based on the number of parameters.\n final StringBuilder sb = new StringBuilder(\n String.join(&quot;, &quot;, Collections.nCopies(possibleValue.size(), &quot;?&quot;)));\n\n // For more than 1 parameter, replace the single parameter with\n // multiple parameter placeholders.\n if (sb.length() &gt; 1) {\n sql = sql.replace(&quot;(?)&quot;, &quot;(&quot; + sb + &quot;)&quot;);\n }\n\n // Return the modified comma-delimited list of parameters.\n return sql;\n}\n</code></pre>\n<p>For certain databases where passing an array via the JDBC 4 specification is unsupported, this method can facilitate transforming the slow <code>= ?</code> into the faster <code>IN (?)</code> clause condition, which can then be expanded by calling the <code>any</code> method.</p>\n" }, { "answer_id": 1914440, "author": "neu242", "author_id": 13365, "author_profile": "https://Stackoverflow.com/users/13365", "pm_score": 1, "selected": false, "text": "<p>Generate the query string in the PreparedStatement to have a number of ?'s matching the number of items in your list. Here's an example:</p>\n\n<pre><code>public void myQuery(List&lt;String&gt; items, int other) {\n ...\n String q4in = generateQsForIn(items.size());\n String sql = \"select * from stuff where foo in ( \" + q4in + \" ) and bar = ?\";\n PreparedStatement ps = connection.prepareStatement(sql);\n int i = 1;\n for (String item : items) {\n ps.setString(i++, item);\n }\n ps.setInt(i++, other);\n ResultSet rs = ps.executeQuery();\n ...\n}\n\nprivate String generateQsForIn(int numQs) {\n String items = \"\";\n for (int i = 0; i &lt; numQs; i++) {\n if (i != 0) items += \", \";\n items += \"?\";\n }\n return items;\n}\n</code></pre>\n" }, { "answer_id": 5104833, "author": "Javier Ibanez", "author_id": 632332, "author_profile": "https://Stackoverflow.com/users/632332", "pm_score": 3, "selected": false, "text": "<p>My workaround is:</p>\n\n<pre><code>create or replace type split_tbl as table of varchar(32767);\n/\n\ncreate or replace function split\n(\n p_list varchar2,\n p_del varchar2 := ','\n) return split_tbl pipelined\nis\n l_idx pls_integer;\n l_list varchar2(32767) := p_list;\n l_value varchar2(32767);\nbegin\n loop\n l_idx := instr(l_list,p_del);\n if l_idx &gt; 0 then\n pipe row(substr(l_list,1,l_idx-1));\n l_list := substr(l_list,l_idx+length(p_del));\n else\n pipe row(l_list);\n exit;\n end if;\n end loop;\n return;\nend split;\n/\n</code></pre>\n\n<p>Now you can use one variable to obtain some values in a table:</p>\n\n<pre><code>select * from table(split('one,two,three'))\n one\n two\n three\n\nselect * from TABLE1 where COL1 in (select * from table(split('value1,value2')))\n value1 AAA\n value2 BBB\n</code></pre>\n\n<p>So, the prepared statement could be:</p>\n\n<pre><code> \"select * from TABLE where COL in (select * from table(split(?)))\"\n</code></pre>\n\n<p>Regards,</p>\n\n<p>Javier Ibanez</p>\n" }, { "answer_id": 8217423, "author": "Jeff Miller", "author_id": 912813, "author_profile": "https://Stackoverflow.com/users/912813", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.sormula.org/\" rel=\"nofollow\">Sormula</a> supports SQL IN operator by allowing you to supply a java.util.Collection object as a parameter. It creates a prepared statement with a ? for each of the elements the collection. See <a href=\"http://www.sormula.org/example4/\" rel=\"nofollow\">Example 4</a> (SQL in example is a comment to clarify what is created but is not used by Sormula).</p>\n" }, { "answer_id": 10240302, "author": "Boris", "author_id": 1345608, "author_profile": "https://Stackoverflow.com/users/1345608", "pm_score": 7, "selected": false, "text": "<p>Solution for PostgreSQL:</p>\n<pre><code>final PreparedStatement statement = connection.prepareStatement(\n &quot;SELECT my_column FROM my_table where search_column = ANY (?)&quot;\n);\nfinal String[] values = getValues();\nstatement.setArray(1, connection.createArrayOf(&quot;text&quot;, values));\n\ntry (ResultSet rs = statement.executeQuery()) {\n while(rs.next()) {\n // do some...\n }\n}\n</code></pre>\n<p>or</p>\n<pre><code>final PreparedStatement statement = connection.prepareStatement(\n &quot;SELECT my_column FROM my_table &quot; + \n &quot;where search_column IN (SELECT * FROM unnest(?))&quot;\n);\nfinal String[] values = getValues();\nstatement.setArray(1, connection.createArrayOf(&quot;text&quot;, values));\n\ntry (ResultSet rs = statement.executeQuery()) {\n while(rs.next()) {\n // do some...\n }\n}\n</code></pre>\n" }, { "answer_id": 18422316, "author": "kapil das", "author_id": 2041542, "author_profile": "https://Stackoverflow.com/users/2041542", "pm_score": 1, "selected": false, "text": "<p>instead of using</p>\n\n<pre><code>SELECT my_column FROM my_table where search_column IN (?)\n</code></pre>\n\n<p>use the Sql Statement as </p>\n\n<pre><code>select id, name from users where id in (?, ?, ?)\n</code></pre>\n\n<p>and</p>\n\n<pre><code>preparedStatement.setString( 1, 'A');\npreparedStatement.setString( 2,'B');\npreparedStatement.setString( 3, 'C');\n</code></pre>\n\n<p>or use a stored procedure this would be the best solution, since the sql statements will be compiled and stored in DataBase server</p>\n" }, { "answer_id": 18757911, "author": "Alexander", "author_id": 1752358, "author_profile": "https://Stackoverflow.com/users/1752358", "pm_score": 1, "selected": false, "text": "<p>I came across a number of limitations related to prepared statement:</p>\n\n<ol>\n<li>The prepared statements are cached only inside the same session (Postgres), so it will really work only with connection pooling</li>\n<li>A lot of different prepared statements as proposed by @BalusC may cause the cache to overfill and previously cached statements will be dropped</li>\n<li>The query has to be optimized and use indices. Sounds obvious, however e.g. the ANY(ARRAY...) statement proposed by @Boris in one of the top answers cannot use indices and query will be slow despite caching</li>\n<li>The prepared statement caches the query plan as well and the actual values of any parameters specified in the statement are unavailable.</li>\n</ol>\n\n<p>Among the proposed solutions I would choose the one that doesn't decrease the query performance and makes the less number of queries. This will be the #4 (batching few queries) from the @Don link or specifying NULL values for unneeded '?' marks as proposed by @Vladimir Dyuzhev </p>\n" }, { "answer_id": 21361828, "author": "Pankaj", "author_id": 926520, "author_profile": "https://Stackoverflow.com/users/926520", "pm_score": 0, "selected": false, "text": "<p>There are different alternative approaches that we can use for IN clause in PreparedStatement.</p>\n\n<ol>\n<li>Using Single Queries - slowest performance and resource intensive</li>\n<li>Using StoredProcedure - Fastest but database specific</li>\n<li>Creating dynamic query for PreparedStatement - Good Performance but doesn't get benefit of caching and PreparedStatement is recompiled every time.</li>\n<li><p>Use NULL in PreparedStatement queries - Optimal performance, works great when you know the limit of IN clause arguments. If there is no limit, then you can execute queries in batch. \nSample code snippet is;</p>\n\n<pre><code> int i = 1;\n for(; i &lt;=ids.length; i++){\n ps.setInt(i, ids[i-1]);\n }\n\n //set null for remaining ones\n for(; i&lt;=PARAM_SIZE;i++){\n ps.setNull(i, java.sql.Types.INTEGER);\n }\n</code></pre></li>\n</ol>\n\n<p>You can check more details about these alternative approaches <a href=\"http://www.journaldev.com/2521/jdbc-preparedstatement-in-clause-alternative-approaches\" rel=\"nofollow\">here</a>.</p>\n" }, { "answer_id": 27738214, "author": "Vasili", "author_id": 446098, "author_profile": "https://Stackoverflow.com/users/446098", "pm_score": 0, "selected": false, "text": "<p>For some situations regexp might help. \nHere is an example I've checked on Oracle, and it works. </p>\n\n<pre><code>select * from my_table where REGEXP_LIKE (search_column, 'value1|value2')\n</code></pre>\n\n<p>But there is a number of drawbacks with it:</p>\n\n<ol>\n<li>Any column it applied should be converted to varchar/char, at least implicitly.</li>\n<li>Need to be careful with special characters.</li>\n<li>It can slow down performance - in my case IN version uses index and range scan, and REGEXP version do full scan.</li>\n</ol>\n" }, { "answer_id": 29062027, "author": "bnsk", "author_id": 1666429, "author_profile": "https://Stackoverflow.com/users/1666429", "pm_score": 0, "selected": false, "text": "<p>After examining various solutions in different forums and not finding a good solution, I feel the below hack I came up with, is the easiest to follow and code:</p>\n\n<p>Example: Suppose you have multiple parameters to pass in the 'IN' clause. Just put a dummy String inside the 'IN' clause, say, \"PARAM\" do denote the list of parameters that will be coming in the place of this dummy String.</p>\n\n<pre><code> select * from TABLE_A where ATTR IN (PARAM);\n</code></pre>\n\n<p>You can collect all the parameters into a single String variable in your Java code. This can be done as follows:</p>\n\n<pre><code> String param1 = \"X\";\n String param2 = \"Y\";\n String param1 = param1.append(\",\").append(param2);\n</code></pre>\n\n<p>You can append all your parameters separated by commas into a single String variable, 'param1', in our case.</p>\n\n<p>After collecting all the parameters into a single String you can just replace the dummy text in your query, i.e., \"PARAM\" in this case, with the parameter String, i.e., param1. Here is what you need to do:</p>\n\n<pre><code> String query = query.replaceFirst(\"PARAM\",param1); where we have the value of query as \n\n query = \"select * from TABLE_A where ATTR IN (PARAM)\";\n</code></pre>\n\n<p>You can now execute your query using the executeQuery() method. Just make sure that you don't have the word \"PARAM\" in your query anywhere. You can use a combination of special characters and alphabets instead of the word \"PARAM\" in order to make sure that there is no possibility of such a word coming in the query. Hope you got the solution.</p>\n\n<p>Note: Though this is not a prepared query, it does the work that I wanted my code to do.</p>\n" }, { "answer_id": 29397855, "author": "epeleg", "author_id": 25412, "author_profile": "https://Stackoverflow.com/users/25412", "pm_score": 0, "selected": false, "text": "<p>Just for completeness and because I did not see anyone else suggest it:</p>\n\n<p>Before implementing any of the complicated suggestions above consider if SQL injection is indeed a problem in your scenario. </p>\n\n<p>In many cases the value provided to IN (...) is a list of ids that have been generated in a way that you can be sure that no injection is possible... (e.g. the results of a previous select some_id from some_table where some_condition.)</p>\n\n<p>If that is the case you might just concatenate this value and not use the services or the prepared statement for it or use them for other parameters of this query. </p>\n\n<pre><code>query=\"select f1,f2 from t1 where f3=? and f2 in (\" + sListOfIds + \");\";\n</code></pre>\n" }, { "answer_id": 29739504, "author": "dwjohnston", "author_id": 1068446, "author_profile": "https://Stackoverflow.com/users/1068446", "pm_score": 2, "selected": false, "text": "<p>Here's a complete solution in Java to create the prepared statement for you:</p>\n\n<pre><code>/*usage:\n\nUtil u = new Util(500); //500 items per bracket. \nString sqlBefore = \"select * from myTable where (\";\nList&lt;Integer&gt; values = new ArrayList&lt;Integer&gt;(Arrays.asList(1,2,4,5)); \nstring sqlAfter = \") and foo = 'bar'\"; \n\nPreparedStatement ps = u.prepareStatements(sqlBefore, values, sqlAfter, connection, \"someId\");\n*/\n\n\n\nimport java.sql.Connection;\nimport java.sql.PreparedStatement;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class Util {\n\n private int numValuesInClause;\n\n public Util(int numValuesInClause) {\n super();\n this.numValuesInClause = numValuesInClause;\n }\n\n public int getNumValuesInClause() {\n return numValuesInClause;\n }\n\n public void setNumValuesInClause(int numValuesInClause) {\n this.numValuesInClause = numValuesInClause;\n }\n\n /** Split a given list into a list of lists for the given size of numValuesInClause*/\n public List&lt;List&lt;Integer&gt;&gt; splitList(\n List&lt;Integer&gt; values) {\n\n\n List&lt;List&lt;Integer&gt;&gt; newList = new ArrayList&lt;List&lt;Integer&gt;&gt;(); \n while (values.size() &gt; numValuesInClause) {\n List&lt;Integer&gt; sublist = values.subList(0,numValuesInClause);\n List&lt;Integer&gt; values2 = values.subList(numValuesInClause, values.size()); \n values = values2; \n\n newList.add( sublist);\n }\n newList.add(values);\n\n return newList;\n }\n\n /**\n * Generates a series of split out in clause statements. \n * @param sqlBefore \"\"select * from dual where (\"\n * @param values [1,2,3,4,5,6,7,8,9,10]\n * @param \"sqlAfter ) and id = 5\"\n * @return \"select * from dual where (id in (1,2,3) or id in (4,5,6) or id in (7,8,9) or id in (10)\"\n */\n public String genInClauseSql(String sqlBefore, List&lt;Integer&gt; values,\n String sqlAfter, String identifier) \n {\n List&lt;List&lt;Integer&gt;&gt; newLists = splitList(values);\n String stmt = sqlBefore;\n\n /* now generate the in clause for each list */\n int j = 0; /* keep track of list:newLists index */\n for (List&lt;Integer&gt; list : newLists) {\n stmt = stmt + identifier +\" in (\";\n StringBuilder innerBuilder = new StringBuilder();\n\n for (int i = 0; i &lt; list.size(); i++) {\n innerBuilder.append(\"?,\");\n }\n\n\n\n String inClause = innerBuilder.deleteCharAt(\n innerBuilder.length() - 1).toString();\n\n stmt = stmt + inClause;\n stmt = stmt + \")\";\n\n\n if (++j &lt; newLists.size()) {\n stmt = stmt + \" OR \";\n }\n\n }\n\n stmt = stmt + sqlAfter;\n return stmt;\n }\n\n /**\n * Method to convert your SQL and a list of ID into a safe prepared\n * statements\n * \n * @throws SQLException\n */\n public PreparedStatement prepareStatements(String sqlBefore,\n ArrayList&lt;Integer&gt; values, String sqlAfter, Connection c, String identifier)\n throws SQLException {\n\n /* First split our potentially big list into lots of lists */\n String stmt = genInClauseSql(sqlBefore, values, sqlAfter, identifier);\n PreparedStatement ps = c.prepareStatement(stmt);\n\n int i = 1;\n for (int val : values)\n {\n\n ps.setInt(i++, val);\n\n }\n return ps;\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 30573323, "author": "Hans-Peter Störr", "author_id": 21499, "author_profile": "https://Stackoverflow.com/users/21499", "pm_score": 2, "selected": false, "text": "<p>Spring allows <a href=\"http://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/jdbc.html#jdbc-in-clause\" rel=\"nofollow\">passing java.util.Lists to NamedParameterJdbcTemplate</a> , which automates the generation of (?, ?, ?, ..., ?), as appropriate for the number of arguments.</p>\n\n<p>For Oracle, <a href=\"https://blogs.itemis.de/kloss/2009/03/05/arrays-preparedstatements-jdbc-and-oracle/\" rel=\"nofollow\">this blog posting</a> discusses the use of oracle.sql.ARRAY (Connection.createArrayOf doesn't work with Oracle). For this you have to modify your SQL statement:</p>\n\n<pre><code>SELECT my_column FROM my_table where search_column IN (select COLUMN_VALUE from table(?))\n</code></pre>\n\n<p>The <a href=\"http://stevenfeuersteinonplsql.blogspot.de/2015/04/table-functions-introduction-and.html\" rel=\"nofollow\">oracle table function</a> transforms the passed array into a table like value usable in the <code>IN</code> statement.</p>\n" }, { "answer_id": 35459827, "author": "Gee Bee", "author_id": 5903395, "author_profile": "https://Stackoverflow.com/users/5903395", "pm_score": 3, "selected": false, "text": "<h2>Limitations of the in() operator is the root of all evil.</h2>\n<p>It works for trivial cases, and you can extend it with &quot;automatic generation of the prepared statement&quot; however it is always having its limits.</p>\n<ul>\n<li>if you're creating a statement with variable number of parameters, that will make an sql parse overhead at each call</li>\n<li>on many platforms, the number of parameters of in() operator are limited</li>\n<li>on all platforms, total SQL text size is limited, making impossible for sending down 2000 placeholders for the in params</li>\n<li>sending down bind variables of 1000-10k is not possible, as the JDBC driver is having its limitations</li>\n</ul>\n<p>The in() approach can be good enough for some cases, but not rocket proof :)</p>\n<p>The rocket-proof solution is to pass the arbitrary number of parameters in a separate call (by passing a clob of params, for example), and then have a view (or any other way) to represent them in SQL and use in your where criteria.</p>\n<p>A brute-force variant is here <a href=\"http://tkyte.blogspot.hu/2006/06/varying-in-lists.html\" rel=\"noreferrer\">http://tkyte.blogspot.hu/2006/06/varying-in-lists.html</a></p>\n<p>However if you can use PL/SQL, this mess can become pretty neat.</p>\n<pre><code>function getCustomers(in_customerIdList clob) return sys_refcursor is \nbegin\n aux_in_list.parse(in_customerIdList);\n open res for\n select * \n from customer c,\n in_list v\n where c.customer_id=v.token;\n return res;\nend;\n</code></pre>\n<p>Then you can pass arbitrary number of comma separated customer ids in the parameter, and:</p>\n<ul>\n<li>will get no parse delay, as the SQL for select is stable</li>\n<li>no pipelined functions complexity - it is just one query</li>\n<li>the SQL is using a simple join, instead of an IN operator, which is quite fast</li>\n<li>after all, it is a good rule of thumb of <em>not</em> hitting the database with any plain select or DML, since it is Oracle, which offers lightyears of more than MySQL or similar simple database engines. PL/SQL allows you to hide the storage model from your application domain model in an effective way.</li>\n</ul>\n<p>The trick here is:</p>\n<ul>\n<li>we need a call which accepts the long string, and store somewhere where the db session can access to it (e.g. simple package variable, or dbms_session.set_context)</li>\n<li>then we need a view which can parse this to rows</li>\n<li>and then you have a view which contains the ids you're querying, so all you need is a simple join to the table queried.</li>\n</ul>\n<p>The view looks like:</p>\n<pre><code>create or replace view in_list\nas\nselect\n trim( substr (txt,\n instr (txt, ',', 1, level ) + 1,\n instr (txt, ',', 1, level+1)\n - instr (txt, ',', 1, level) -1 ) ) as token\n from (select ','||aux_in_list.getpayload||',' txt from dual)\nconnect by level &lt;= length(aux_in_list.getpayload)-length(replace(aux_in_list.getpayload,',',''))+1\n</code></pre>\n<p>where aux_in_list.getpayload refers to the original input string.</p>\n<hr />\n<p>A possible approach would be to pass pl/sql arrays (supported by Oracle only), however you can't use those in pure SQL, therefore a conversion step is always needed. The conversion can not be done in SQL, so after all, passing a clob with all parameters in string and converting it witin a view is the most efficient solution.</p>\n" }, { "answer_id": 36491947, "author": "m.sabouri", "author_id": 3353334, "author_profile": "https://Stackoverflow.com/users/3353334", "pm_score": 3, "selected": false, "text": "<p>Here's how I solved it in my own application. Ideally, you should use a StringBuilder instead of using + for Strings.</p>\n\n<pre><code> String inParenthesis = \"(?\";\n for(int i = 1;i &lt; myList.size();i++) {\n inParenthesis += \", ?\";\n }\n inParenthesis += \")\";\n\n try(PreparedStatement statement = SQLite.connection.prepareStatement(\n String.format(\"UPDATE table SET value='WINNER' WHERE startTime=? AND name=? AND traderIdx=? AND someValue IN %s\", inParenthesis))) {\n int x = 1;\n statement.setLong(x++, race.startTime);\n statement.setString(x++, race.name);\n statement.setInt(x++, traderIdx);\n\n for(String str : race.betFair.winners) {\n statement.setString(x++, str);\n }\n\n int effected = statement.executeUpdate();\n }\n</code></pre>\n\n<p>Using a variable like x above instead of concrete numbers helps a lot if you decide to change the query at a later time.</p>\n" }, { "answer_id": 37734734, "author": "Panky031", "author_id": 5882929, "author_profile": "https://Stackoverflow.com/users/5882929", "pm_score": 2, "selected": false, "text": "<p>You could use setArray method as mentioned in <a href=\"http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setArray(int,%20java.sql.Array)\" rel=\"nofollow\">this javadoc</a>:</p>\n\n<pre><code>PreparedStatement statement = connection.prepareStatement(\"Select * from emp where field in (?)\");\nArray array = statement.getConnection().createArrayOf(\"VARCHAR\", new Object[]{\"E1\", \"E2\",\"E3\"});\nstatement.setArray(1, array);\nResultSet rs = statement.executeQuery();\n</code></pre>\n" }, { "answer_id": 41988063, "author": "smooth_smoothie", "author_id": 373466, "author_profile": "https://Stackoverflow.com/users/373466", "pm_score": -1, "selected": false, "text": "<p>My workaround (JavaScript)</p>\n\n<pre><code> var s1 = \" SELECT \"\n\n + \"FROM table t \"\n\n + \" where t.field in \";\n\n var s3 = '(';\n\n for(var i =0;i&lt;searchTerms.length;i++)\n {\n if(i+1 == searchTerms.length)\n {\n s3 = s3+'?)';\n }\n else\n {\n s3 = s3+'?, ' ;\n }\n }\n var query = s1+s3;\n\n var pstmt = connection.prepareStatement(query);\n\n for(var i =0;i&lt;searchTerms.length;i++)\n {\n pstmt.setString(i+1, searchTerms[i]);\n }\n</code></pre>\n\n<p><code>SearchTerms</code> is the array which contains your input/keys/fields etc</p>\n" }, { "answer_id": 44422748, "author": "pedram bashiri", "author_id": 2695227, "author_profile": "https://Stackoverflow.com/users/2695227", "pm_score": 0, "selected": false, "text": "<p>PreparedStatement doesn't provide any good way to deal with SQL IN clause. Per <a href=\"http://www.javaranch.com/journal/200510/Journal200510.jsp#a2\" rel=\"nofollow noreferrer\">http://www.javaranch.com/journal/200510/Journal200510.jsp#a2</a> \"You can't substitute things that are meant to become part of the SQL statement. This is necessary because if the SQL itself can change, the driver can't precompile the statement. It also has the nice side effect of preventing SQL injection attacks.\" I ended up using following approach:</p>\n\n<pre><code>String query = \"SELECT my_column FROM my_table where search_column IN ($searchColumns)\";\nquery = query.replace(\"$searchColumns\", \"'A', 'B', 'C'\");\nStatement stmt = connection.createStatement();\nboolean hasResults = stmt.execute(query);\ndo {\n if (hasResults)\n return stmt.getResultSet();\n\n hasResults = stmt.getMoreResults();\n\n} while (hasResults || stmt.getUpdateCount() != -1);\n</code></pre>\n" }, { "answer_id": 49035778, "author": "Raheel", "author_id": 1033305, "author_profile": "https://Stackoverflow.com/users/1033305", "pm_score": 1, "selected": false, "text": "<p>SetArray is the best solution but its not available for many older drivers. The following workaround can be used in java8</p>\n\n<pre><code>String baseQuery =\"SELECT my_column FROM my_table where search_column IN (%s)\"\n\nString markersString = inputArray.stream().map(e -&gt; \"?\").collect(joining(\",\"));\nString sqlQuery = String.format(baseSQL, markersString);\n\n//Now create Prepared Statement and use loop to Set entries\nint index=1;\n\nfor (String input : inputArray) {\n preparedStatement.setString(index++, input);\n}\n</code></pre>\n\n<p>This solution is better than other ugly while loop solutions where the query string is built by manual iterations </p>\n" }, { "answer_id": 50085176, "author": "Gurwinder Singh", "author_id": 6348498, "author_profile": "https://Stackoverflow.com/users/6348498", "pm_score": 4, "selected": false, "text": "<p>You can use <code>Collections.nCopies</code> to generate a collection of placeholders and join them using <code>String.join</code>:</p>\n\n<pre><code>List&lt;String&gt; params = getParams();\nString placeHolders = String.join(\",\", Collections.nCopies(params.size(), \"?\"));\nString sql = \"select * from your_table where some_column in (\" + placeHolders + \")\";\ntry ( Connection connection = getConnection();\n PreparedStatement ps = connection.prepareStatement(sql)) {\n int i = 1;\n for (String param : params) {\n ps.setString(i++, param);\n }\n /*\n * Execute query/do stuff\n */\n}\n</code></pre>\n" }, { "answer_id": 54140112, "author": "Joel Fouse", "author_id": 1899071, "author_profile": "https://Stackoverflow.com/users/1899071", "pm_score": 1, "selected": false, "text": "<p>I just worked out a PostgreSQL-specific option for this. It's a bit of a hack, and comes with its own pros and cons and limitations, but it seems to work and isn't limited to a specific development language, platform, or PG driver.</p>\n\n<p>The trick of course is to find a way to pass an arbitrary length collection of values as a single parameter, and have the db recognize it as multiple values. The solution I have working is to construct a delimited string from the values in the collection, pass that string as a single parameter, and use string_to_array() with the requisite casting for PostgreSQL to properly make use of it.</p>\n\n<p>So if you want to search for \"foo\", \"blah\", and \"abc\", you might concatenate them together into a single string as: 'foo,blah,abc'. Here's the straight SQL:</p>\n\n<pre><code>select column from table\nwhere search_column = any (string_to_array('foo,blah,abc', ',')::text[]);\n</code></pre>\n\n<p>You would obviously change the explicit cast to whatever you wanted your resulting value array to be -- int, text, uuid, etc. And because the function is taking a single string value (or two I suppose, if you want to customize the delimiter as well), you can pass it as a parameter in a prepared statement:</p>\n\n<pre><code>select column from table\nwhere search_column = any (string_to_array($1, ',')::text[]);\n</code></pre>\n\n<p>This is even flexible enough to support things like LIKE comparisons:</p>\n\n<pre><code>select column from table\nwhere search_column like any (string_to_array('foo%,blah%,abc%', ',')::text[]);\n</code></pre>\n\n<p>Again, no question it's a hack, but it works and allows you to still use pre-compiled prepared statements that take <em>*ahem*</em> discrete parameters, with the accompanying security and (maybe) performance benefits. Is it advisable and actually performant? Naturally, it depends, as you've got string parsing and possibly casting going on before your query even runs. If you're expecting to send three, five, a few dozen values, sure, it's probably fine. A few thousand? Yeah, maybe not so much. YMMV, limitations and exclusions apply, no warranty express or implied.</p>\n\n<p>But it works.</p>\n" }, { "answer_id": 59746690, "author": "Nikita Shah", "author_id": 1039367, "author_profile": "https://Stackoverflow.com/users/1039367", "pm_score": -1, "selected": false, "text": "<p>This worked for me (psuedocode):</p>\n\n<pre><code>public class SqlHelper\n{\n public static final ArrayList&lt;String&gt;platformList = new ArrayList&lt;&gt;(Arrays.asList(\"iOS\",\"Android\",\"Windows\",\"Mac\"));\n\n public static final String testQuery = \"select * from devices where platform_nm in (:PLATFORM_NAME)\";\n}\n</code></pre>\n\n<p>specicify binding :</p>\n\n<pre><code>public class Test extends NamedParameterJdbcDaoSupport\npublic List&lt;SampleModelClass&gt; runQuery()\n{\n //define rowMapper to insert in object of SampleClass\n final Map&lt;String,Object&gt; map = new HashMap&lt;&gt;();\n map.put(\"PLATFORM_LIST\",DeviceDataSyncQueryConstants.platformList);\n return getNamedParameterJdbcTemplate().query(SqlHelper.testQuery, map, rowMapper)\n}\n</code></pre>\n" }, { "answer_id": 67209550, "author": "Lukas Eder", "author_id": 521799, "author_profile": "https://Stackoverflow.com/users/521799", "pm_score": 1, "selected": false, "text": "<p>No one else seems to have suggested using an off-the-shelf query builder yet, like <a href=\"https://www.jooq.org\" rel=\"nofollow noreferrer\">jOOQ</a> or <a href=\"http://www.querydsl.com\" rel=\"nofollow noreferrer\">QueryDSL</a> or even <a href=\"https://www.baeldung.com/hibernate-criteria-queries\" rel=\"nofollow noreferrer\">Criteria Query</a> that manage <a href=\"https://www.jooq.org/doc/latest/manual/sql-building/conditional-expressions/in-predicate/\" rel=\"nofollow noreferrer\">dynamic <code>IN</code> lists</a> out of the box, possibly including the management of all edge cases that may arise, such as:</p>\n<ul>\n<li>Running into Oracle's maximum of 1000 elements per <code>IN</code> list (irrespective of the number of bind values)</li>\n<li>Running into any driver's maximum number of bind values, <a href=\"https://stackoverflow.com/a/54149292/521799\">which I've documented in this answer</a></li>\n<li>Running into cursor cache contention problems because too many distinct SQL strings are &quot;hard parsed&quot; and execution plans cannot be cached anymore (jOOQ and since recently also Hibernate work around this by offering <a href=\"https://www.jooq.org/doc/latest/manual/sql-building/dsl-context/custom-settings/settings-in-list-padding/\" rel=\"nofollow noreferrer\"><code>IN</code> list padding</a>)</li>\n</ul>\n<p>(Disclaimer: I work for the company behind jOOQ)</p>\n" }, { "answer_id": 68853470, "author": "Rod Meyer", "author_id": 906036, "author_profile": "https://Stackoverflow.com/users/906036", "pm_score": 0, "selected": false, "text": "<p>OK, so I couldn't remember exactly how (or where) I did this before so I came to stack overflow to quickly find the answer. I was surprised I couldn't.</p>\n<p>So, how I got around the IN problem a long time ago was with a statement like this:</p>\n<p><strong>where myColumn in ( select regexp_substr(:myList,'[^,]+', 1, level) from dual connect by regexp_substr(:myList, '[^,]+', 1, level) is not null)</strong></p>\n<p>set the myList parameter as a comma delimited string: A,B,C,D...</p>\n<p>Note: You have to set the parameter twice!</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15816/" ]
What are the best workarounds for using a SQL `IN` clause with instances of `java.sql.PreparedStatement`, which is not supported for multiple values due to SQL injection attack security issues: One `?` placeholder represents one value, rather than a list of values. Consider the following SQL statement: ``` SELECT my_column FROM my_table where search_column IN (?) ``` Using `preparedStatement.setString( 1, "'A', 'B', 'C'" );` is essentially a non-working attempt at a workaround of the reasons for using `?` in the first place. What workarounds are available?
An analysis of the various options available, and the pros and cons of each is available in Jeanne Boyarsky's *[Batching Select Statements in JDBC](http://www.javaranch.com/journal/200510/Journal200510.jsp#a2)* entry on JavaRanch Journal. The suggested options are: * Prepare `SELECT my_column FROM my_table WHERE search_column = ?`, execute it for each value and UNION the results client-side. Requires only one prepared statement. Slow and painful. * Prepare `SELECT my_column FROM my_table WHERE search_column IN (?,?,?)` and execute it. Requires one prepared statement per size-of-IN-list. Fast and obvious. * Prepare `SELECT my_column FROM my_table WHERE search_column = ? ; SELECT my_column FROM my_table WHERE search_column = ? ; ...` and execute it. [Or use `UNION ALL` in place of those semicolons. --ed] Requires one prepared statement per size-of-IN-list. Stupidly slow, strictly worse than `WHERE search_column IN (?,?,?)`, so I don't know why the blogger even suggested it. * Use a stored procedure to construct the result set. * Prepare N different size-of-IN-list queries; say, with 2, 10, and 50 values. To search for an IN-list with 6 different values, populate the size-10 query so that it looks like `SELECT my_column FROM my_table WHERE search_column IN (1,2,3,4,5,6,6,6,6,6)`. Any decent server will optimize out the duplicate values before running the query. None of these options are ideal. The best option if you are using JDBC4 and a server that supports `x = ANY(y)`, is to use `PreparedStatement.setArray` as described in [Boris's anwser](https://stackoverflow.com/questions/178479/preparedstatement-in-clause-alternatives/10240302#10240302). There doesn't seem to be any way to make `setArray` work with IN-lists, though. --- Sometimes SQL statements are loaded at runtime (e.g., from a properties file) but require a variable number of parameters. In such cases, first define the query: ```none query=SELECT * FROM table t WHERE t.column IN (?) ``` Next, load the query. Then determine the number of parameters prior to running it. Once the parameter count is known, run: ```java sql = any( sql, count ); ``` For example: ```java /** * Converts a SQL statement containing exactly one IN clause to an IN clause * using multiple comma-delimited parameters. * * @param sql The SQL statement string with one IN clause. * @param params The number of parameters the SQL statement requires. * @return The SQL statement with (?) replaced with multiple parameter * placeholders. */ public static String any(String sql, final int params) { // Create a comma-delimited list based on the number of parameters. final StringBuilder sb = new StringBuilder( String.join(", ", Collections.nCopies(possibleValue.size(), "?"))); // For more than 1 parameter, replace the single parameter with // multiple parameter placeholders. if (sb.length() > 1) { sql = sql.replace("(?)", "(" + sb + ")"); } // Return the modified comma-delimited list of parameters. return sql; } ``` For certain databases where passing an array via the JDBC 4 specification is unsupported, this method can facilitate transforming the slow `= ?` into the faster `IN (?)` clause condition, which can then be expanded by calling the `any` method.
178,482
<p>For a school project, I need to create a way to create personnalized queries based on end-user choices.<br /> Since the user can choose basically any fields from any combination of tables, I need to find a way to map the tables in order to make a join and not have extraneous data (This may lead to incoherent reports, but we're willing to live with that).</p> <p>For up to two tables, I already managed to design an algorithm that works fine. However, when I add another table, I can't find a way to path through my database. All tables available for the personnalized reports can be linked together so it really all falls down to finding which path to use.</p>
[ { "answer_id": 178505, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 3, "selected": false, "text": "<p>I've never tried it, but would .setArray() do what you're looking for?</p>\n\n<p><strong>Update</strong>: Evidently not. setArray only seems to work with a java.sql.Array that comes from an ARRAY column that you've retrieved from a previous query, or a subquery with an ARRAY column.</p>\n" }, { "answer_id": 178517, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "<p>I suppose you could (using basic string manipulation) generate the query string in the <code>PreparedStatement</code> to have a number of <code>?</code>'s matching the number of items in your list. </p>\n\n<p>Of course if you're doing that you're just a step away from generating a giant chained <code>OR</code> in your query, but without having the right number of <code>?</code> in the query string, I don't see how else you can work around this.</p>\n" }, { "answer_id": 178635, "author": "stjohnroe", "author_id": 2985, "author_profile": "https://Stackoverflow.com/users/2985", "pm_score": 1, "selected": false, "text": "<p>try using the instr function?</p>\n\n<pre><code>select my_column from my_table where instr(?, ','||search_column||',') &gt; 0\n</code></pre>\n\n<p>then</p>\n\n<pre><code>ps.setString(1, \",A,B,C,\"); \n</code></pre>\n\n<p>Admittedly this is a bit of a dirty hack, but it does reduce the opportunities for sql injection. Works in oracle anyway.</p>\n" }, { "answer_id": 178650, "author": "Carl Smotricz", "author_id": 172211, "author_profile": "https://Stackoverflow.com/users/172211", "pm_score": 0, "selected": false, "text": "<p>Just for completeness: So long as the set of values is not too large, you <em>could</em> also simply string-construct a statement like</p>\n\n<pre><code>... WHERE tab.col = ? OR tab.col = ? OR tab.col = ?\n</code></pre>\n\n<p>which you could then pass to prepare(), and then use setXXX() in a loop to set all the values. This looks yucky, but many \"big\" commercial systems routinely do this kind of thing until they hit DB-specific limits, such as 32 KB (I think it is) for statements in Oracle.</p>\n\n<p>Of course you need to ensure that the set will never be unreasonably large, or do error trapping in the event that it is.</p>\n" }, { "answer_id": 179144, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Following Adam's idea. Make your prepared statement sort of select my_column from my_table where search_column in (#)\nCreate a String x and fill it with a number of \"?,?,?\" depending on your list of values\nThen just change the # in the query for your new String x an populate</p>\n" }, { "answer_id": 180872, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 3, "selected": false, "text": "<p>An unpleasant work-around, but certainly feasible is to use a nested query. Create a temporary table MYVALUES with a column in it. Insert your list of values into the MYVALUES table. Then execute </p>\n\n<pre><code>select my_column from my_table where search_column in ( SELECT value FROM MYVALUES )\n</code></pre>\n\n<p>Ugly, but a viable alternative if your list of values is very large.</p>\n\n<p>This technique has the added advantage of potentially better query plans from the optimizer (check a page for multiple values, tablescan only once instead once per value, etc) may save on overhead if your database doesn't cache prepared statements. Your \"INSERTS\" would need to be done in batch and the MYVALUES table may need to be tweaked to have minimal locking or other high-overhead protections.</p>\n" }, { "answer_id": 189347, "author": "Vladimir Dyuzhev", "author_id": 1163802, "author_profile": "https://Stackoverflow.com/users/1163802", "pm_score": 4, "selected": false, "text": "<p>No simple way AFAIK.\nIf the target is to keep statement cache ratio high (i.e to not create a statement per every parameter count), you may do the following:</p>\n\n<ol>\n<li><p>create a statement with a few (e.g. 10) parameters:</p>\n\n<p>... WHERE A IN (?,?,?,?,?,?,?,?,?,?) ...</p></li>\n<li><p>Bind all actuall parameters</p>\n\n<p>setString(1,\"foo\");\nsetString(2,\"bar\");</p></li>\n<li><p>Bind the rest as NULL</p>\n\n<p>setNull(3,Types.VARCHAR)\n...\nsetNull(10,Types.VARCHAR)</p></li>\n</ol>\n\n<p>NULL never matches anything, so it gets optimized out by the SQL plan builder.</p>\n\n<p>The logic is easy to automate when you pass a List into a DAO function:</p>\n\n<pre><code>while( i &lt; param.size() ) {\n ps.setString(i+1,param.get(i));\n i++;\n}\n\nwhile( i &lt; MAX_PARAMS ) {\n ps.setNull(i+1,Types.VARCHAR);\n i++;\n}\n</code></pre>\n" }, { "answer_id": 189399, "author": "Dónal", "author_id": 2648, "author_profile": "https://Stackoverflow.com/users/2648", "pm_score": 9, "selected": true, "text": "<p>An analysis of the various options available, and the pros and cons of each is available in Jeanne Boyarsky's <em><a href=\"http://www.javaranch.com/journal/200510/Journal200510.jsp#a2\" rel=\"nofollow noreferrer\">Batching Select Statements in JDBC</a></em> entry on JavaRanch Journal.</p>\n<p>The suggested options are:</p>\n<ul>\n<li>Prepare <code>SELECT my_column FROM my_table WHERE search_column = ?</code>, execute it for each value and UNION the results client-side. Requires only one prepared statement. Slow and painful.</li>\n<li>Prepare <code>SELECT my_column FROM my_table WHERE search_column IN (?,?,?)</code> and execute it. Requires one prepared statement per size-of-IN-list. Fast and obvious.</li>\n<li>Prepare <code>SELECT my_column FROM my_table WHERE search_column = ? ; SELECT my_column FROM my_table WHERE search_column = ? ; ...</code> and execute it. [Or use <code>UNION ALL</code> in place of those semicolons. --ed] Requires one prepared statement per size-of-IN-list. Stupidly slow, strictly worse than <code>WHERE search_column IN (?,?,?)</code>, so I don't know why the blogger even suggested it.</li>\n<li>Use a stored procedure to construct the result set.</li>\n<li>Prepare N different size-of-IN-list queries; say, with 2, 10, and 50 values. To search for an IN-list with 6 different values, populate the size-10 query so that it looks like <code>SELECT my_column FROM my_table WHERE search_column IN (1,2,3,4,5,6,6,6,6,6)</code>. Any decent server will optimize out the duplicate values before running the query.</li>\n</ul>\n<p>None of these options are ideal.</p>\n<p>The best option if you are using JDBC4 and a server that supports <code>x = ANY(y)</code>, is to use <code>PreparedStatement.setArray</code> as described in <a href=\"https://stackoverflow.com/questions/178479/preparedstatement-in-clause-alternatives/10240302#10240302\">Boris's anwser</a>.</p>\n<p>There doesn't seem to be any way to make <code>setArray</code> work with IN-lists, though.</p>\n<hr />\n<p>Sometimes SQL statements are loaded at runtime (e.g., from a properties file) but require a variable number of parameters. In such cases, first define the query:</p>\n<pre class=\"lang-none prettyprint-override\"><code>query=SELECT * FROM table t WHERE t.column IN (?)\n</code></pre>\n<p>Next, load the query. Then determine the number of parameters prior to running it. Once the parameter count is known, run:</p>\n<pre class=\"lang-java prettyprint-override\"><code>sql = any( sql, count );\n</code></pre>\n<p>For example:</p>\n<pre class=\"lang-java prettyprint-override\"><code>/**\n * Converts a SQL statement containing exactly one IN clause to an IN clause\n * using multiple comma-delimited parameters.\n *\n * @param sql The SQL statement string with one IN clause.\n * @param params The number of parameters the SQL statement requires.\n * @return The SQL statement with (?) replaced with multiple parameter\n * placeholders.\n */\npublic static String any(String sql, final int params) {\n // Create a comma-delimited list based on the number of parameters.\n final StringBuilder sb = new StringBuilder(\n String.join(&quot;, &quot;, Collections.nCopies(possibleValue.size(), &quot;?&quot;)));\n\n // For more than 1 parameter, replace the single parameter with\n // multiple parameter placeholders.\n if (sb.length() &gt; 1) {\n sql = sql.replace(&quot;(?)&quot;, &quot;(&quot; + sb + &quot;)&quot;);\n }\n\n // Return the modified comma-delimited list of parameters.\n return sql;\n}\n</code></pre>\n<p>For certain databases where passing an array via the JDBC 4 specification is unsupported, this method can facilitate transforming the slow <code>= ?</code> into the faster <code>IN (?)</code> clause condition, which can then be expanded by calling the <code>any</code> method.</p>\n" }, { "answer_id": 1914440, "author": "neu242", "author_id": 13365, "author_profile": "https://Stackoverflow.com/users/13365", "pm_score": 1, "selected": false, "text": "<p>Generate the query string in the PreparedStatement to have a number of ?'s matching the number of items in your list. Here's an example:</p>\n\n<pre><code>public void myQuery(List&lt;String&gt; items, int other) {\n ...\n String q4in = generateQsForIn(items.size());\n String sql = \"select * from stuff where foo in ( \" + q4in + \" ) and bar = ?\";\n PreparedStatement ps = connection.prepareStatement(sql);\n int i = 1;\n for (String item : items) {\n ps.setString(i++, item);\n }\n ps.setInt(i++, other);\n ResultSet rs = ps.executeQuery();\n ...\n}\n\nprivate String generateQsForIn(int numQs) {\n String items = \"\";\n for (int i = 0; i &lt; numQs; i++) {\n if (i != 0) items += \", \";\n items += \"?\";\n }\n return items;\n}\n</code></pre>\n" }, { "answer_id": 5104833, "author": "Javier Ibanez", "author_id": 632332, "author_profile": "https://Stackoverflow.com/users/632332", "pm_score": 3, "selected": false, "text": "<p>My workaround is:</p>\n\n<pre><code>create or replace type split_tbl as table of varchar(32767);\n/\n\ncreate or replace function split\n(\n p_list varchar2,\n p_del varchar2 := ','\n) return split_tbl pipelined\nis\n l_idx pls_integer;\n l_list varchar2(32767) := p_list;\n l_value varchar2(32767);\nbegin\n loop\n l_idx := instr(l_list,p_del);\n if l_idx &gt; 0 then\n pipe row(substr(l_list,1,l_idx-1));\n l_list := substr(l_list,l_idx+length(p_del));\n else\n pipe row(l_list);\n exit;\n end if;\n end loop;\n return;\nend split;\n/\n</code></pre>\n\n<p>Now you can use one variable to obtain some values in a table:</p>\n\n<pre><code>select * from table(split('one,two,three'))\n one\n two\n three\n\nselect * from TABLE1 where COL1 in (select * from table(split('value1,value2')))\n value1 AAA\n value2 BBB\n</code></pre>\n\n<p>So, the prepared statement could be:</p>\n\n<pre><code> \"select * from TABLE where COL in (select * from table(split(?)))\"\n</code></pre>\n\n<p>Regards,</p>\n\n<p>Javier Ibanez</p>\n" }, { "answer_id": 8217423, "author": "Jeff Miller", "author_id": 912813, "author_profile": "https://Stackoverflow.com/users/912813", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.sormula.org/\" rel=\"nofollow\">Sormula</a> supports SQL IN operator by allowing you to supply a java.util.Collection object as a parameter. It creates a prepared statement with a ? for each of the elements the collection. See <a href=\"http://www.sormula.org/example4/\" rel=\"nofollow\">Example 4</a> (SQL in example is a comment to clarify what is created but is not used by Sormula).</p>\n" }, { "answer_id": 10240302, "author": "Boris", "author_id": 1345608, "author_profile": "https://Stackoverflow.com/users/1345608", "pm_score": 7, "selected": false, "text": "<p>Solution for PostgreSQL:</p>\n<pre><code>final PreparedStatement statement = connection.prepareStatement(\n &quot;SELECT my_column FROM my_table where search_column = ANY (?)&quot;\n);\nfinal String[] values = getValues();\nstatement.setArray(1, connection.createArrayOf(&quot;text&quot;, values));\n\ntry (ResultSet rs = statement.executeQuery()) {\n while(rs.next()) {\n // do some...\n }\n}\n</code></pre>\n<p>or</p>\n<pre><code>final PreparedStatement statement = connection.prepareStatement(\n &quot;SELECT my_column FROM my_table &quot; + \n &quot;where search_column IN (SELECT * FROM unnest(?))&quot;\n);\nfinal String[] values = getValues();\nstatement.setArray(1, connection.createArrayOf(&quot;text&quot;, values));\n\ntry (ResultSet rs = statement.executeQuery()) {\n while(rs.next()) {\n // do some...\n }\n}\n</code></pre>\n" }, { "answer_id": 18422316, "author": "kapil das", "author_id": 2041542, "author_profile": "https://Stackoverflow.com/users/2041542", "pm_score": 1, "selected": false, "text": "<p>instead of using</p>\n\n<pre><code>SELECT my_column FROM my_table where search_column IN (?)\n</code></pre>\n\n<p>use the Sql Statement as </p>\n\n<pre><code>select id, name from users where id in (?, ?, ?)\n</code></pre>\n\n<p>and</p>\n\n<pre><code>preparedStatement.setString( 1, 'A');\npreparedStatement.setString( 2,'B');\npreparedStatement.setString( 3, 'C');\n</code></pre>\n\n<p>or use a stored procedure this would be the best solution, since the sql statements will be compiled and stored in DataBase server</p>\n" }, { "answer_id": 18757911, "author": "Alexander", "author_id": 1752358, "author_profile": "https://Stackoverflow.com/users/1752358", "pm_score": 1, "selected": false, "text": "<p>I came across a number of limitations related to prepared statement:</p>\n\n<ol>\n<li>The prepared statements are cached only inside the same session (Postgres), so it will really work only with connection pooling</li>\n<li>A lot of different prepared statements as proposed by @BalusC may cause the cache to overfill and previously cached statements will be dropped</li>\n<li>The query has to be optimized and use indices. Sounds obvious, however e.g. the ANY(ARRAY...) statement proposed by @Boris in one of the top answers cannot use indices and query will be slow despite caching</li>\n<li>The prepared statement caches the query plan as well and the actual values of any parameters specified in the statement are unavailable.</li>\n</ol>\n\n<p>Among the proposed solutions I would choose the one that doesn't decrease the query performance and makes the less number of queries. This will be the #4 (batching few queries) from the @Don link or specifying NULL values for unneeded '?' marks as proposed by @Vladimir Dyuzhev </p>\n" }, { "answer_id": 21361828, "author": "Pankaj", "author_id": 926520, "author_profile": "https://Stackoverflow.com/users/926520", "pm_score": 0, "selected": false, "text": "<p>There are different alternative approaches that we can use for IN clause in PreparedStatement.</p>\n\n<ol>\n<li>Using Single Queries - slowest performance and resource intensive</li>\n<li>Using StoredProcedure - Fastest but database specific</li>\n<li>Creating dynamic query for PreparedStatement - Good Performance but doesn't get benefit of caching and PreparedStatement is recompiled every time.</li>\n<li><p>Use NULL in PreparedStatement queries - Optimal performance, works great when you know the limit of IN clause arguments. If there is no limit, then you can execute queries in batch. \nSample code snippet is;</p>\n\n<pre><code> int i = 1;\n for(; i &lt;=ids.length; i++){\n ps.setInt(i, ids[i-1]);\n }\n\n //set null for remaining ones\n for(; i&lt;=PARAM_SIZE;i++){\n ps.setNull(i, java.sql.Types.INTEGER);\n }\n</code></pre></li>\n</ol>\n\n<p>You can check more details about these alternative approaches <a href=\"http://www.journaldev.com/2521/jdbc-preparedstatement-in-clause-alternative-approaches\" rel=\"nofollow\">here</a>.</p>\n" }, { "answer_id": 27738214, "author": "Vasili", "author_id": 446098, "author_profile": "https://Stackoverflow.com/users/446098", "pm_score": 0, "selected": false, "text": "<p>For some situations regexp might help. \nHere is an example I've checked on Oracle, and it works. </p>\n\n<pre><code>select * from my_table where REGEXP_LIKE (search_column, 'value1|value2')\n</code></pre>\n\n<p>But there is a number of drawbacks with it:</p>\n\n<ol>\n<li>Any column it applied should be converted to varchar/char, at least implicitly.</li>\n<li>Need to be careful with special characters.</li>\n<li>It can slow down performance - in my case IN version uses index and range scan, and REGEXP version do full scan.</li>\n</ol>\n" }, { "answer_id": 29062027, "author": "bnsk", "author_id": 1666429, "author_profile": "https://Stackoverflow.com/users/1666429", "pm_score": 0, "selected": false, "text": "<p>After examining various solutions in different forums and not finding a good solution, I feel the below hack I came up with, is the easiest to follow and code:</p>\n\n<p>Example: Suppose you have multiple parameters to pass in the 'IN' clause. Just put a dummy String inside the 'IN' clause, say, \"PARAM\" do denote the list of parameters that will be coming in the place of this dummy String.</p>\n\n<pre><code> select * from TABLE_A where ATTR IN (PARAM);\n</code></pre>\n\n<p>You can collect all the parameters into a single String variable in your Java code. This can be done as follows:</p>\n\n<pre><code> String param1 = \"X\";\n String param2 = \"Y\";\n String param1 = param1.append(\",\").append(param2);\n</code></pre>\n\n<p>You can append all your parameters separated by commas into a single String variable, 'param1', in our case.</p>\n\n<p>After collecting all the parameters into a single String you can just replace the dummy text in your query, i.e., \"PARAM\" in this case, with the parameter String, i.e., param1. Here is what you need to do:</p>\n\n<pre><code> String query = query.replaceFirst(\"PARAM\",param1); where we have the value of query as \n\n query = \"select * from TABLE_A where ATTR IN (PARAM)\";\n</code></pre>\n\n<p>You can now execute your query using the executeQuery() method. Just make sure that you don't have the word \"PARAM\" in your query anywhere. You can use a combination of special characters and alphabets instead of the word \"PARAM\" in order to make sure that there is no possibility of such a word coming in the query. Hope you got the solution.</p>\n\n<p>Note: Though this is not a prepared query, it does the work that I wanted my code to do.</p>\n" }, { "answer_id": 29397855, "author": "epeleg", "author_id": 25412, "author_profile": "https://Stackoverflow.com/users/25412", "pm_score": 0, "selected": false, "text": "<p>Just for completeness and because I did not see anyone else suggest it:</p>\n\n<p>Before implementing any of the complicated suggestions above consider if SQL injection is indeed a problem in your scenario. </p>\n\n<p>In many cases the value provided to IN (...) is a list of ids that have been generated in a way that you can be sure that no injection is possible... (e.g. the results of a previous select some_id from some_table where some_condition.)</p>\n\n<p>If that is the case you might just concatenate this value and not use the services or the prepared statement for it or use them for other parameters of this query. </p>\n\n<pre><code>query=\"select f1,f2 from t1 where f3=? and f2 in (\" + sListOfIds + \");\";\n</code></pre>\n" }, { "answer_id": 29739504, "author": "dwjohnston", "author_id": 1068446, "author_profile": "https://Stackoverflow.com/users/1068446", "pm_score": 2, "selected": false, "text": "<p>Here's a complete solution in Java to create the prepared statement for you:</p>\n\n<pre><code>/*usage:\n\nUtil u = new Util(500); //500 items per bracket. \nString sqlBefore = \"select * from myTable where (\";\nList&lt;Integer&gt; values = new ArrayList&lt;Integer&gt;(Arrays.asList(1,2,4,5)); \nstring sqlAfter = \") and foo = 'bar'\"; \n\nPreparedStatement ps = u.prepareStatements(sqlBefore, values, sqlAfter, connection, \"someId\");\n*/\n\n\n\nimport java.sql.Connection;\nimport java.sql.PreparedStatement;\nimport java.sql.SQLException;\nimport java.util.ArrayList;\nimport java.util.List;\n\npublic class Util {\n\n private int numValuesInClause;\n\n public Util(int numValuesInClause) {\n super();\n this.numValuesInClause = numValuesInClause;\n }\n\n public int getNumValuesInClause() {\n return numValuesInClause;\n }\n\n public void setNumValuesInClause(int numValuesInClause) {\n this.numValuesInClause = numValuesInClause;\n }\n\n /** Split a given list into a list of lists for the given size of numValuesInClause*/\n public List&lt;List&lt;Integer&gt;&gt; splitList(\n List&lt;Integer&gt; values) {\n\n\n List&lt;List&lt;Integer&gt;&gt; newList = new ArrayList&lt;List&lt;Integer&gt;&gt;(); \n while (values.size() &gt; numValuesInClause) {\n List&lt;Integer&gt; sublist = values.subList(0,numValuesInClause);\n List&lt;Integer&gt; values2 = values.subList(numValuesInClause, values.size()); \n values = values2; \n\n newList.add( sublist);\n }\n newList.add(values);\n\n return newList;\n }\n\n /**\n * Generates a series of split out in clause statements. \n * @param sqlBefore \"\"select * from dual where (\"\n * @param values [1,2,3,4,5,6,7,8,9,10]\n * @param \"sqlAfter ) and id = 5\"\n * @return \"select * from dual where (id in (1,2,3) or id in (4,5,6) or id in (7,8,9) or id in (10)\"\n */\n public String genInClauseSql(String sqlBefore, List&lt;Integer&gt; values,\n String sqlAfter, String identifier) \n {\n List&lt;List&lt;Integer&gt;&gt; newLists = splitList(values);\n String stmt = sqlBefore;\n\n /* now generate the in clause for each list */\n int j = 0; /* keep track of list:newLists index */\n for (List&lt;Integer&gt; list : newLists) {\n stmt = stmt + identifier +\" in (\";\n StringBuilder innerBuilder = new StringBuilder();\n\n for (int i = 0; i &lt; list.size(); i++) {\n innerBuilder.append(\"?,\");\n }\n\n\n\n String inClause = innerBuilder.deleteCharAt(\n innerBuilder.length() - 1).toString();\n\n stmt = stmt + inClause;\n stmt = stmt + \")\";\n\n\n if (++j &lt; newLists.size()) {\n stmt = stmt + \" OR \";\n }\n\n }\n\n stmt = stmt + sqlAfter;\n return stmt;\n }\n\n /**\n * Method to convert your SQL and a list of ID into a safe prepared\n * statements\n * \n * @throws SQLException\n */\n public PreparedStatement prepareStatements(String sqlBefore,\n ArrayList&lt;Integer&gt; values, String sqlAfter, Connection c, String identifier)\n throws SQLException {\n\n /* First split our potentially big list into lots of lists */\n String stmt = genInClauseSql(sqlBefore, values, sqlAfter, identifier);\n PreparedStatement ps = c.prepareStatement(stmt);\n\n int i = 1;\n for (int val : values)\n {\n\n ps.setInt(i++, val);\n\n }\n return ps;\n\n }\n\n}\n</code></pre>\n" }, { "answer_id": 30573323, "author": "Hans-Peter Störr", "author_id": 21499, "author_profile": "https://Stackoverflow.com/users/21499", "pm_score": 2, "selected": false, "text": "<p>Spring allows <a href=\"http://docs.spring.io/spring/docs/4.2.x/spring-framework-reference/html/jdbc.html#jdbc-in-clause\" rel=\"nofollow\">passing java.util.Lists to NamedParameterJdbcTemplate</a> , which automates the generation of (?, ?, ?, ..., ?), as appropriate for the number of arguments.</p>\n\n<p>For Oracle, <a href=\"https://blogs.itemis.de/kloss/2009/03/05/arrays-preparedstatements-jdbc-and-oracle/\" rel=\"nofollow\">this blog posting</a> discusses the use of oracle.sql.ARRAY (Connection.createArrayOf doesn't work with Oracle). For this you have to modify your SQL statement:</p>\n\n<pre><code>SELECT my_column FROM my_table where search_column IN (select COLUMN_VALUE from table(?))\n</code></pre>\n\n<p>The <a href=\"http://stevenfeuersteinonplsql.blogspot.de/2015/04/table-functions-introduction-and.html\" rel=\"nofollow\">oracle table function</a> transforms the passed array into a table like value usable in the <code>IN</code> statement.</p>\n" }, { "answer_id": 35459827, "author": "Gee Bee", "author_id": 5903395, "author_profile": "https://Stackoverflow.com/users/5903395", "pm_score": 3, "selected": false, "text": "<h2>Limitations of the in() operator is the root of all evil.</h2>\n<p>It works for trivial cases, and you can extend it with &quot;automatic generation of the prepared statement&quot; however it is always having its limits.</p>\n<ul>\n<li>if you're creating a statement with variable number of parameters, that will make an sql parse overhead at each call</li>\n<li>on many platforms, the number of parameters of in() operator are limited</li>\n<li>on all platforms, total SQL text size is limited, making impossible for sending down 2000 placeholders for the in params</li>\n<li>sending down bind variables of 1000-10k is not possible, as the JDBC driver is having its limitations</li>\n</ul>\n<p>The in() approach can be good enough for some cases, but not rocket proof :)</p>\n<p>The rocket-proof solution is to pass the arbitrary number of parameters in a separate call (by passing a clob of params, for example), and then have a view (or any other way) to represent them in SQL and use in your where criteria.</p>\n<p>A brute-force variant is here <a href=\"http://tkyte.blogspot.hu/2006/06/varying-in-lists.html\" rel=\"noreferrer\">http://tkyte.blogspot.hu/2006/06/varying-in-lists.html</a></p>\n<p>However if you can use PL/SQL, this mess can become pretty neat.</p>\n<pre><code>function getCustomers(in_customerIdList clob) return sys_refcursor is \nbegin\n aux_in_list.parse(in_customerIdList);\n open res for\n select * \n from customer c,\n in_list v\n where c.customer_id=v.token;\n return res;\nend;\n</code></pre>\n<p>Then you can pass arbitrary number of comma separated customer ids in the parameter, and:</p>\n<ul>\n<li>will get no parse delay, as the SQL for select is stable</li>\n<li>no pipelined functions complexity - it is just one query</li>\n<li>the SQL is using a simple join, instead of an IN operator, which is quite fast</li>\n<li>after all, it is a good rule of thumb of <em>not</em> hitting the database with any plain select or DML, since it is Oracle, which offers lightyears of more than MySQL or similar simple database engines. PL/SQL allows you to hide the storage model from your application domain model in an effective way.</li>\n</ul>\n<p>The trick here is:</p>\n<ul>\n<li>we need a call which accepts the long string, and store somewhere where the db session can access to it (e.g. simple package variable, or dbms_session.set_context)</li>\n<li>then we need a view which can parse this to rows</li>\n<li>and then you have a view which contains the ids you're querying, so all you need is a simple join to the table queried.</li>\n</ul>\n<p>The view looks like:</p>\n<pre><code>create or replace view in_list\nas\nselect\n trim( substr (txt,\n instr (txt, ',', 1, level ) + 1,\n instr (txt, ',', 1, level+1)\n - instr (txt, ',', 1, level) -1 ) ) as token\n from (select ','||aux_in_list.getpayload||',' txt from dual)\nconnect by level &lt;= length(aux_in_list.getpayload)-length(replace(aux_in_list.getpayload,',',''))+1\n</code></pre>\n<p>where aux_in_list.getpayload refers to the original input string.</p>\n<hr />\n<p>A possible approach would be to pass pl/sql arrays (supported by Oracle only), however you can't use those in pure SQL, therefore a conversion step is always needed. The conversion can not be done in SQL, so after all, passing a clob with all parameters in string and converting it witin a view is the most efficient solution.</p>\n" }, { "answer_id": 36491947, "author": "m.sabouri", "author_id": 3353334, "author_profile": "https://Stackoverflow.com/users/3353334", "pm_score": 3, "selected": false, "text": "<p>Here's how I solved it in my own application. Ideally, you should use a StringBuilder instead of using + for Strings.</p>\n\n<pre><code> String inParenthesis = \"(?\";\n for(int i = 1;i &lt; myList.size();i++) {\n inParenthesis += \", ?\";\n }\n inParenthesis += \")\";\n\n try(PreparedStatement statement = SQLite.connection.prepareStatement(\n String.format(\"UPDATE table SET value='WINNER' WHERE startTime=? AND name=? AND traderIdx=? AND someValue IN %s\", inParenthesis))) {\n int x = 1;\n statement.setLong(x++, race.startTime);\n statement.setString(x++, race.name);\n statement.setInt(x++, traderIdx);\n\n for(String str : race.betFair.winners) {\n statement.setString(x++, str);\n }\n\n int effected = statement.executeUpdate();\n }\n</code></pre>\n\n<p>Using a variable like x above instead of concrete numbers helps a lot if you decide to change the query at a later time.</p>\n" }, { "answer_id": 37734734, "author": "Panky031", "author_id": 5882929, "author_profile": "https://Stackoverflow.com/users/5882929", "pm_score": 2, "selected": false, "text": "<p>You could use setArray method as mentioned in <a href=\"http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setArray(int,%20java.sql.Array)\" rel=\"nofollow\">this javadoc</a>:</p>\n\n<pre><code>PreparedStatement statement = connection.prepareStatement(\"Select * from emp where field in (?)\");\nArray array = statement.getConnection().createArrayOf(\"VARCHAR\", new Object[]{\"E1\", \"E2\",\"E3\"});\nstatement.setArray(1, array);\nResultSet rs = statement.executeQuery();\n</code></pre>\n" }, { "answer_id": 41988063, "author": "smooth_smoothie", "author_id": 373466, "author_profile": "https://Stackoverflow.com/users/373466", "pm_score": -1, "selected": false, "text": "<p>My workaround (JavaScript)</p>\n\n<pre><code> var s1 = \" SELECT \"\n\n + \"FROM table t \"\n\n + \" where t.field in \";\n\n var s3 = '(';\n\n for(var i =0;i&lt;searchTerms.length;i++)\n {\n if(i+1 == searchTerms.length)\n {\n s3 = s3+'?)';\n }\n else\n {\n s3 = s3+'?, ' ;\n }\n }\n var query = s1+s3;\n\n var pstmt = connection.prepareStatement(query);\n\n for(var i =0;i&lt;searchTerms.length;i++)\n {\n pstmt.setString(i+1, searchTerms[i]);\n }\n</code></pre>\n\n<p><code>SearchTerms</code> is the array which contains your input/keys/fields etc</p>\n" }, { "answer_id": 44422748, "author": "pedram bashiri", "author_id": 2695227, "author_profile": "https://Stackoverflow.com/users/2695227", "pm_score": 0, "selected": false, "text": "<p>PreparedStatement doesn't provide any good way to deal with SQL IN clause. Per <a href=\"http://www.javaranch.com/journal/200510/Journal200510.jsp#a2\" rel=\"nofollow noreferrer\">http://www.javaranch.com/journal/200510/Journal200510.jsp#a2</a> \"You can't substitute things that are meant to become part of the SQL statement. This is necessary because if the SQL itself can change, the driver can't precompile the statement. It also has the nice side effect of preventing SQL injection attacks.\" I ended up using following approach:</p>\n\n<pre><code>String query = \"SELECT my_column FROM my_table where search_column IN ($searchColumns)\";\nquery = query.replace(\"$searchColumns\", \"'A', 'B', 'C'\");\nStatement stmt = connection.createStatement();\nboolean hasResults = stmt.execute(query);\ndo {\n if (hasResults)\n return stmt.getResultSet();\n\n hasResults = stmt.getMoreResults();\n\n} while (hasResults || stmt.getUpdateCount() != -1);\n</code></pre>\n" }, { "answer_id": 49035778, "author": "Raheel", "author_id": 1033305, "author_profile": "https://Stackoverflow.com/users/1033305", "pm_score": 1, "selected": false, "text": "<p>SetArray is the best solution but its not available for many older drivers. The following workaround can be used in java8</p>\n\n<pre><code>String baseQuery =\"SELECT my_column FROM my_table where search_column IN (%s)\"\n\nString markersString = inputArray.stream().map(e -&gt; \"?\").collect(joining(\",\"));\nString sqlQuery = String.format(baseSQL, markersString);\n\n//Now create Prepared Statement and use loop to Set entries\nint index=1;\n\nfor (String input : inputArray) {\n preparedStatement.setString(index++, input);\n}\n</code></pre>\n\n<p>This solution is better than other ugly while loop solutions where the query string is built by manual iterations </p>\n" }, { "answer_id": 50085176, "author": "Gurwinder Singh", "author_id": 6348498, "author_profile": "https://Stackoverflow.com/users/6348498", "pm_score": 4, "selected": false, "text": "<p>You can use <code>Collections.nCopies</code> to generate a collection of placeholders and join them using <code>String.join</code>:</p>\n\n<pre><code>List&lt;String&gt; params = getParams();\nString placeHolders = String.join(\",\", Collections.nCopies(params.size(), \"?\"));\nString sql = \"select * from your_table where some_column in (\" + placeHolders + \")\";\ntry ( Connection connection = getConnection();\n PreparedStatement ps = connection.prepareStatement(sql)) {\n int i = 1;\n for (String param : params) {\n ps.setString(i++, param);\n }\n /*\n * Execute query/do stuff\n */\n}\n</code></pre>\n" }, { "answer_id": 54140112, "author": "Joel Fouse", "author_id": 1899071, "author_profile": "https://Stackoverflow.com/users/1899071", "pm_score": 1, "selected": false, "text": "<p>I just worked out a PostgreSQL-specific option for this. It's a bit of a hack, and comes with its own pros and cons and limitations, but it seems to work and isn't limited to a specific development language, platform, or PG driver.</p>\n\n<p>The trick of course is to find a way to pass an arbitrary length collection of values as a single parameter, and have the db recognize it as multiple values. The solution I have working is to construct a delimited string from the values in the collection, pass that string as a single parameter, and use string_to_array() with the requisite casting for PostgreSQL to properly make use of it.</p>\n\n<p>So if you want to search for \"foo\", \"blah\", and \"abc\", you might concatenate them together into a single string as: 'foo,blah,abc'. Here's the straight SQL:</p>\n\n<pre><code>select column from table\nwhere search_column = any (string_to_array('foo,blah,abc', ',')::text[]);\n</code></pre>\n\n<p>You would obviously change the explicit cast to whatever you wanted your resulting value array to be -- int, text, uuid, etc. And because the function is taking a single string value (or two I suppose, if you want to customize the delimiter as well), you can pass it as a parameter in a prepared statement:</p>\n\n<pre><code>select column from table\nwhere search_column = any (string_to_array($1, ',')::text[]);\n</code></pre>\n\n<p>This is even flexible enough to support things like LIKE comparisons:</p>\n\n<pre><code>select column from table\nwhere search_column like any (string_to_array('foo%,blah%,abc%', ',')::text[]);\n</code></pre>\n\n<p>Again, no question it's a hack, but it works and allows you to still use pre-compiled prepared statements that take <em>*ahem*</em> discrete parameters, with the accompanying security and (maybe) performance benefits. Is it advisable and actually performant? Naturally, it depends, as you've got string parsing and possibly casting going on before your query even runs. If you're expecting to send three, five, a few dozen values, sure, it's probably fine. A few thousand? Yeah, maybe not so much. YMMV, limitations and exclusions apply, no warranty express or implied.</p>\n\n<p>But it works.</p>\n" }, { "answer_id": 59746690, "author": "Nikita Shah", "author_id": 1039367, "author_profile": "https://Stackoverflow.com/users/1039367", "pm_score": -1, "selected": false, "text": "<p>This worked for me (psuedocode):</p>\n\n<pre><code>public class SqlHelper\n{\n public static final ArrayList&lt;String&gt;platformList = new ArrayList&lt;&gt;(Arrays.asList(\"iOS\",\"Android\",\"Windows\",\"Mac\"));\n\n public static final String testQuery = \"select * from devices where platform_nm in (:PLATFORM_NAME)\";\n}\n</code></pre>\n\n<p>specicify binding :</p>\n\n<pre><code>public class Test extends NamedParameterJdbcDaoSupport\npublic List&lt;SampleModelClass&gt; runQuery()\n{\n //define rowMapper to insert in object of SampleClass\n final Map&lt;String,Object&gt; map = new HashMap&lt;&gt;();\n map.put(\"PLATFORM_LIST\",DeviceDataSyncQueryConstants.platformList);\n return getNamedParameterJdbcTemplate().query(SqlHelper.testQuery, map, rowMapper)\n}\n</code></pre>\n" }, { "answer_id": 67209550, "author": "Lukas Eder", "author_id": 521799, "author_profile": "https://Stackoverflow.com/users/521799", "pm_score": 1, "selected": false, "text": "<p>No one else seems to have suggested using an off-the-shelf query builder yet, like <a href=\"https://www.jooq.org\" rel=\"nofollow noreferrer\">jOOQ</a> or <a href=\"http://www.querydsl.com\" rel=\"nofollow noreferrer\">QueryDSL</a> or even <a href=\"https://www.baeldung.com/hibernate-criteria-queries\" rel=\"nofollow noreferrer\">Criteria Query</a> that manage <a href=\"https://www.jooq.org/doc/latest/manual/sql-building/conditional-expressions/in-predicate/\" rel=\"nofollow noreferrer\">dynamic <code>IN</code> lists</a> out of the box, possibly including the management of all edge cases that may arise, such as:</p>\n<ul>\n<li>Running into Oracle's maximum of 1000 elements per <code>IN</code> list (irrespective of the number of bind values)</li>\n<li>Running into any driver's maximum number of bind values, <a href=\"https://stackoverflow.com/a/54149292/521799\">which I've documented in this answer</a></li>\n<li>Running into cursor cache contention problems because too many distinct SQL strings are &quot;hard parsed&quot; and execution plans cannot be cached anymore (jOOQ and since recently also Hibernate work around this by offering <a href=\"https://www.jooq.org/doc/latest/manual/sql-building/dsl-context/custom-settings/settings-in-list-padding/\" rel=\"nofollow noreferrer\"><code>IN</code> list padding</a>)</li>\n</ul>\n<p>(Disclaimer: I work for the company behind jOOQ)</p>\n" }, { "answer_id": 68853470, "author": "Rod Meyer", "author_id": 906036, "author_profile": "https://Stackoverflow.com/users/906036", "pm_score": 0, "selected": false, "text": "<p>OK, so I couldn't remember exactly how (or where) I did this before so I came to stack overflow to quickly find the answer. I was surprised I couldn't.</p>\n<p>So, how I got around the IN problem a long time ago was with a statement like this:</p>\n<p><strong>where myColumn in ( select regexp_substr(:myList,'[^,]+', 1, level) from dual connect by regexp_substr(:myList, '[^,]+', 1, level) is not null)</strong></p>\n<p>set the myList parameter as a comma delimited string: A,B,C,D...</p>\n<p>Note: You have to set the parameter twice!</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25818/" ]
For a school project, I need to create a way to create personnalized queries based on end-user choices. Since the user can choose basically any fields from any combination of tables, I need to find a way to map the tables in order to make a join and not have extraneous data (This may lead to incoherent reports, but we're willing to live with that). For up to two tables, I already managed to design an algorithm that works fine. However, when I add another table, I can't find a way to path through my database. All tables available for the personnalized reports can be linked together so it really all falls down to finding which path to use.
An analysis of the various options available, and the pros and cons of each is available in Jeanne Boyarsky's *[Batching Select Statements in JDBC](http://www.javaranch.com/journal/200510/Journal200510.jsp#a2)* entry on JavaRanch Journal. The suggested options are: * Prepare `SELECT my_column FROM my_table WHERE search_column = ?`, execute it for each value and UNION the results client-side. Requires only one prepared statement. Slow and painful. * Prepare `SELECT my_column FROM my_table WHERE search_column IN (?,?,?)` and execute it. Requires one prepared statement per size-of-IN-list. Fast and obvious. * Prepare `SELECT my_column FROM my_table WHERE search_column = ? ; SELECT my_column FROM my_table WHERE search_column = ? ; ...` and execute it. [Or use `UNION ALL` in place of those semicolons. --ed] Requires one prepared statement per size-of-IN-list. Stupidly slow, strictly worse than `WHERE search_column IN (?,?,?)`, so I don't know why the blogger even suggested it. * Use a stored procedure to construct the result set. * Prepare N different size-of-IN-list queries; say, with 2, 10, and 50 values. To search for an IN-list with 6 different values, populate the size-10 query so that it looks like `SELECT my_column FROM my_table WHERE search_column IN (1,2,3,4,5,6,6,6,6,6)`. Any decent server will optimize out the duplicate values before running the query. None of these options are ideal. The best option if you are using JDBC4 and a server that supports `x = ANY(y)`, is to use `PreparedStatement.setArray` as described in [Boris's anwser](https://stackoverflow.com/questions/178479/preparedstatement-in-clause-alternatives/10240302#10240302). There doesn't seem to be any way to make `setArray` work with IN-lists, though. --- Sometimes SQL statements are loaded at runtime (e.g., from a properties file) but require a variable number of parameters. In such cases, first define the query: ```none query=SELECT * FROM table t WHERE t.column IN (?) ``` Next, load the query. Then determine the number of parameters prior to running it. Once the parameter count is known, run: ```java sql = any( sql, count ); ``` For example: ```java /** * Converts a SQL statement containing exactly one IN clause to an IN clause * using multiple comma-delimited parameters. * * @param sql The SQL statement string with one IN clause. * @param params The number of parameters the SQL statement requires. * @return The SQL statement with (?) replaced with multiple parameter * placeholders. */ public static String any(String sql, final int params) { // Create a comma-delimited list based on the number of parameters. final StringBuilder sb = new StringBuilder( String.join(", ", Collections.nCopies(possibleValue.size(), "?"))); // For more than 1 parameter, replace the single parameter with // multiple parameter placeholders. if (sb.length() > 1) { sql = sql.replace("(?)", "(" + sb + ")"); } // Return the modified comma-delimited list of parameters. return sql; } ``` For certain databases where passing an array via the JDBC 4 specification is unsupported, this method can facilitate transforming the slow `= ?` into the faster `IN (?)` clause condition, which can then be expanded by calling the `any` method.
178,519
<p>I'm just starting with CodeIgniter, and I am not sure where things such as css, js, and images should go. Outside the whole system folder seems ok, but that means everything is seperate. Inside means the filepaths are longer, and I'm worried that it might mess things up. What's the best practice on this issue?</p>
[ { "answer_id": 178534, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": true, "text": "<p>I usually put separate folders at the root level, so I end up with a directory structure like this:</p>\n\n<pre><code>/system\n/css\n/js\n/img\n</code></pre>\n\n<p>Seems to work for me - when you use <code>site_url(url)</code>, the URL it generates is from the root, so you can use <code>site_url('css/file.css')</code> to generate URLs to your stylesheets etc.</p>\n" }, { "answer_id": 179812, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 1, "selected": false, "text": "<p>I hate having so many directories at the root level, so I use /public and use htaccess to rewrite /scripts to /public/scripts and so on.</p>\n" }, { "answer_id": 180835, "author": "Click Online Design", "author_id": 25695, "author_profile": "https://Stackoverflow.com/users/25695", "pm_score": 1, "selected": false, "text": "<p>I find it best to keep the assets on the root level. You can use <code>&lt;?=base_url()?&gt;</code> to echo the full root of the site. In the config file, you set up the root of the website. This statement just echoes that out.</p>\n\n<p>Because of this, you can use includes like this: </p>\n\n<pre><code>&lt;link href=\"&lt;?=base_url()?&gt;/css/style.css\" rel=\"stylesheet\" type=\"text/css\" /&gt;\n</code></pre>\n\n<p>anywhere in your code, and it will still get <a href=\"http://example.com/css/style.css\" rel=\"nofollow noreferrer\">http://example.com/css/style.css</a>.</p>\n" }, { "answer_id": 3657634, "author": "Tejas Patel", "author_id": 441322, "author_profile": "https://Stackoverflow.com/users/441322", "pm_score": 1, "selected": false, "text": "<p>base_url()/css/name.css</p>\n" }, { "answer_id": 5720118, "author": "JBibbs", "author_id": 311099, "author_profile": "https://Stackoverflow.com/users/311099", "pm_score": 1, "selected": false, "text": "<p>In order to use the site_url(url) helper in this way you MUST first configure Apache mod_rewrite (or equivalent) to remove the index.php segment from the URI.</p>\n\n<p>Otherwise the site_url method adds index.php to the URL which will likely screw up the paths to your assets if you've got them in the base directory like above.</p>\n\n<p>Here's the CodeIgniter documentation on removing index.php from the URI:</p>\n\n<p><a href=\"http://codeigniter.com/wiki/mod_rewrite/\" rel=\"nofollow\">http://codeigniter.com/wiki/mod_rewrite/</a></p>\n" }, { "answer_id": 11805029, "author": "Jordan Arseno", "author_id": 568884, "author_profile": "https://Stackoverflow.com/users/568884", "pm_score": 3, "selected": false, "text": "<p>Personally, I rip the <code>application</code> directory out of the <code>system</code> directory and make it a sibling to <code>system</code>. I then create a project directory in <code>public_html (www)</code> where I move index.php and store my public assets.</p>\n\n<p>Let's assume the project you're working on is called <code>projekt</code>. In the parent directory to <code>public_html (www)</code> create a directory called <code>CISYSTEM</code>, and inside that directory create a directory from the version you're using, <code>202</code>, <code>210</code> etc.</p>\n\n<pre><code>/CISYSTEM\n /202\n /210\n /another_CI_version\n/projekt_application\n /models\n /views\n /controllers\n /private_assets\n/public_html\n /projekt\n index.php\n .htaccess\n css\n img\n js\n lib\n</code></pre>\n\n<p>The beauty of this directory structure is it adds another layer of security and makes it dead-easy to upgrade/swap out your CI core. Plus, you're not supposed to make changes to the core - having a single directory where your core is stored and having all projects reference it keeps things DRY.</p>\n\n<p>All this directory shuffling requires you to reroute a few things though. Luckily, CodeIgniter makes it easy -- all changes can be made in the <code>index.php</code> file.</p>\n\n<p>Open <code>index.php</code> and reroute a couple things:</p>\n\n<p>Change: <code>$system_path = 'system';</code> </p>\n\n<p>To: <code>$system_path = '../../CISYSTEM/210';</code></p>\n\n<p>Change: <code>$application_folder = 'application';</code> </p>\n\n<p>To: <code>$application_folder = '../../projekt_application';</code></p>\n\n<hr>\n\n<p>Also, I see a lot of people talking about using <code>site_url()</code> in the other answers. I recommend a less verbose way of using <code>site_url()</code>... you don't have to call it every time if you make use of HTML's <code>&lt;base&gt;</code> element:</p>\n\n<p><code>&lt;base href=\"&lt;?= site_url();?&gt;\"&gt;</code></p>\n\n<p>Just include that in your application's <code>&lt;head&gt;</code> and you can call your controllers directly... as in:</p>\n\n<p><code>&lt;a href='controllername/functionname'&gt;Some Action&lt;/a&gt;</code></p>\n\n<p>Cheers</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16511/" ]
I'm just starting with CodeIgniter, and I am not sure where things such as css, js, and images should go. Outside the whole system folder seems ok, but that means everything is seperate. Inside means the filepaths are longer, and I'm worried that it might mess things up. What's the best practice on this issue?
I usually put separate folders at the root level, so I end up with a directory structure like this: ``` /system /css /js /img ``` Seems to work for me - when you use `site_url(url)`, the URL it generates is from the root, so you can use `site_url('css/file.css')` to generate URLs to your stylesheets etc.
178,524
<p>I recently read this Phil Haack post (<a href="http://haacked.com/archive/2007/06/13/the-most-useful-.net-utility-classes-developers-tend-to-reinvent.aspx" rel="nofollow noreferrer">The Most Useful .NET Utility Classes Developers Tend To Reinvent Rather Than Reuse</a>) from last year, and thought I'd see if anyone has any additions to the list.</p>
[ { "answer_id": 178542, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 5, "selected": false, "text": "<p>Enum.Parse()</p>\n" }, { "answer_id": 178544, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 5, "selected": false, "text": "<p>String.Format.</p>\n\n<p>The number of times I've seen</p>\n\n<pre><code>return \"£\" &amp; iSomeValue\n</code></pre>\n\n<p>rather than</p>\n\n<pre><code>return String.Format (\"{0:c}\", iSomeValue)\n</code></pre>\n\n<p>or people appending percent signs - things like that.</p>\n" }, { "answer_id": 178552, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 5, "selected": false, "text": "<p><code>String.IsNullOrEmpty()</code></p>\n" }, { "answer_id": 178558, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 4, "selected": false, "text": "<p>String.Join() (however, almost everyone knows about string.Split and seems to use it every chance they get...)</p>\n" }, { "answer_id": 178559, "author": "Galwegian", "author_id": 3201, "author_profile": "https://Stackoverflow.com/users/3201", "pm_score": 3, "selected": false, "text": "<p>System.Text.RegularExpressions.Regex</p>\n" }, { "answer_id": 178568, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>Many people seem to like stepping through an XML file manually to find something rather than use XPathNaviagator.</p>\n" }, { "answer_id": 178587, "author": "mmacaulay", "author_id": 22152, "author_profile": "https://Stackoverflow.com/users/22152", "pm_score": 3, "selected": false, "text": "<p><code>input.StartsWith(\"stuff\")</code> instead of <code>Regex.IsMatch(input, @\"^stuff\")</code></p>\n" }, { "answer_id": 178607, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 5, "selected": false, "text": "<pre><code>Path.GetFileNameWithoutExtension(string path)\n</code></pre>\n\n<p>Returns the file name of the specified path string without the extension.</p>\n\n<pre><code>Path.GetTempFileName()\n</code></pre>\n\n<p>Creates a uniquely named, zero-byte temporary file on disk and returns the full path of that file.</p>\n" }, { "answer_id": 178647, "author": "John Chuckran", "author_id": 25511, "author_profile": "https://Stackoverflow.com/users/25511", "pm_score": 4, "selected": false, "text": "<p>Hard coding a / into a directory manipulation string versus using:</p>\n\n<pre><code>IO.Path.DirectorySeparatorChar\n</code></pre>\n" }, { "answer_id": 178659, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 3, "selected": false, "text": "<p>File stuff.</p>\n\n<pre><code>using System.IO;\n\nFile.Exists(FileNamePath)\n\nDirectory.Exists(strDirPath)\n\nFile.Move(currentLocation, newLocation);\n\nFile.Delete(fileToDelete);\n\nDirectory.CreateDirectory(directory)\n\nSystem.IO.FileStream file = System.IO.File.Create(fullFilePath);\n</code></pre>\n" }, { "answer_id": 178683, "author": "torial", "author_id": 13990, "author_profile": "https://Stackoverflow.com/users/13990", "pm_score": 3, "selected": false, "text": "<p><code>System.IO.File.ReadAllText</code> vs writing logic using a StreamReader for small files.</p>\n\n<p><code>System.IO.File.WriteAllText</code> vs writing logic using a StreamWriter for small files.</p>\n" }, { "answer_id": 178691, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 6, "selected": false, "text": "<p>People tend to use the following which is ugly and bound to fail:</p>\n\n<pre><code>string path = basePath + \"\\\\\" + fileName;\n</code></pre>\n\n<p>Better and safer way:</p>\n\n<pre><code>string path = Path.Combine(basePath, fileName);\n</code></pre>\n\n<p>Also I've seen people writing custom method to read all bytes from file.\nThis one comes quite handy:</p>\n\n<pre><code>byte[] fileData = File.ReadAllBytes(path); // use path from Path.Combine\n</code></pre>\n\n<p>As <a href=\"https://stackoverflow.com/users/8543/thexenocide\">TheXenocide</a> pointed out, same applies for <code>File.ReadAllText()</code> and <code>File.ReadAllLines()</code></p>\n" }, { "answer_id": 178713, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>Path.Append is always forgotten in stuff I have seen.</p>\n" }, { "answer_id": 178729, "author": "splattne", "author_id": 6461, "author_profile": "https://Stackoverflow.com/users/6461", "pm_score": 4, "selected": false, "text": "<p>The <strong>StringBuilder</strong> class and especially the Method <strong>AppendFormat</strong>.</p>\n\n<p>P.S.: If you are looking for String Operations performance measurement:\n<a href=\"http://www.codeproject.com/KB/cs/StringBuilder_vs_String.aspx\" rel=\"nofollow noreferrer\">StringBuilder vs. String / Fast String Operations with .NET 2.0</a></p>\n" }, { "answer_id": 178785, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 3, "selected": false, "text": "<p>See <a href=\"https://stackoverflow.com/questions/122784/hidden-net-base-class-library-classes\">Hidden .NET Base Class Library Classes</a></p>\n" }, { "answer_id": 178786, "author": "Peter Walke", "author_id": 12497, "author_profile": "https://Stackoverflow.com/users/12497", "pm_score": 4, "selected": false, "text": "<p>Trying to figure out where My Documents lives on a user's computer. Just use the following:</p>\n\n<pre><code>string directory =\nEnvironment.GetFolderPath(Environment.SpecialFolder.MyDocuments);\n</code></pre>\n" }, { "answer_id": 178804, "author": "Johnno Nolan", "author_id": 1116, "author_profile": "https://Stackoverflow.com/users/1116", "pm_score": 5, "selected": false, "text": "<p>The <code>System.Diagnostics.Stopwatch</code> class.</p>\n" }, { "answer_id": 179187, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "<p>Most people forget that Directory.CreateDirectory() degrades gracefully if the folder already exists, and wrap it with a pointless, if (!Directory.Exists(....)) call.</p>\n" }, { "answer_id": 179270, "author": "Romain Verdier", "author_id": 4687, "author_profile": "https://Stackoverflow.com/users/4687", "pm_score": 4, "selected": false, "text": "<pre><code>Environment.NewLine\n</code></pre>\n" }, { "answer_id": 180079, "author": "Bobby Ortiz", "author_id": 25843, "author_profile": "https://Stackoverflow.com/users/25843", "pm_score": 4, "selected": false, "text": "<p>I needed to download some files recently in a windows application. I found the DownloadFile method on the WebClient object:</p>\n\n<pre><code> WebClient wc = new WebClient();\n wc.DownloadFile(sourceURLAddress, destFileName);\n</code></pre>\n" }, { "answer_id": 180533, "author": "Ed Ball", "author_id": 23818, "author_profile": "https://Stackoverflow.com/users/23818", "pm_score": 4, "selected": false, "text": "<p>Instead of generating a file name with a Guid, just use:</p>\n\n<pre><code>Path.GetRandomFileName()\n</code></pre>\n" }, { "answer_id": 181425, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 3, "selected": false, "text": "<ul>\n<li>Using <a href=\"http://msdn.microsoft.com/en-us/library/x810d419.aspx\" rel=\"nofollow noreferrer\">DebuggerDisplay</a> attribute\ninstead of ToString() to simplify\nthe debugging.</li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx\" rel=\"nofollow noreferrer\">Enumerable.Range</a></li>\n<li><a href=\"http://rabdullin.com/using-tuples-in-c/\" rel=\"nofollow noreferrer\">Tuples</a> from FSharp.Core! </li>\n</ul>\n" }, { "answer_id": 417174, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>myString.Equals(anotherString)</p>\n\n<p>and options including culture-specific ones.</p>\n\n<p>I bet that at least 50% of developers write something like: if (s == \"id\") {...}</p>\n" }, { "answer_id": 417347, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": false, "text": "<p>Lots of the new Linq features seem pretty unknown:</p>\n\n<p><strong><code>Any&lt;T&gt;() &amp; All&lt;T&gt;()</code></strong></p>\n\n<pre><code>if( myCollection.Any( x =&gt; x.IsSomething ) )\n //...\n\nbool allValid = myCollection.All( \n x =&gt; x.IsValid );\n</code></pre>\n\n<p><strong><code>ToList&lt;T&gt;(), ToArray&lt;T&gt;(), ToDictionary&lt;T&gt;()</code></strong></p>\n\n<pre><code>var newDict = myCollection.ToDictionary(\n x =&gt; x.Name,\n x =&gt; x.Value );\n</code></pre>\n\n<p><strong><code>First&lt;T&gt;(), FirstOrDefault&lt;T&gt;()</code></strong></p>\n\n<pre><code>return dbAccessor.GetFromTable( id ).\n FirstOrDefault();\n</code></pre>\n\n<p><strong><code>Where&lt;T&gt;()</code></strong></p>\n\n<pre><code>//instead of\nforeach( Type item in myCollection )\n if( item.IsValid )\n //do stuff\n\n//you can also do\nforeach( var item in myCollection.Where( x =&gt; x.IsValid ) )\n //do stuff\n\n//note only a simple sample - the logic could be a lot more complex\n</code></pre>\n\n<p>All really useful little functions that you can use outside of the Linq syntax.</p>\n" }, { "answer_id": 3066202, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": false, "text": "<p>For all it's hidden away under the Microsoft.VisualBasic namespace, <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx\" rel=\"noreferrer\">TextFieldParser</a> is actually a very nice csv parser. I see a lot of people either roll their own (badly) or use something like the nice <a href=\"http://www.codeproject.com/KB/database/CsvReader.aspx\" rel=\"noreferrer\">Fast CSV</a> library on Code Plex, not even knowing this is already baked into the framework.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6624/" ]
I recently read this Phil Haack post ([The Most Useful .NET Utility Classes Developers Tend To Reinvent Rather Than Reuse](http://haacked.com/archive/2007/06/13/the-most-useful-.net-utility-classes-developers-tend-to-reinvent.aspx)) from last year, and thought I'd see if anyone has any additions to the list.
People tend to use the following which is ugly and bound to fail: ``` string path = basePath + "\\" + fileName; ``` Better and safer way: ``` string path = Path.Combine(basePath, fileName); ``` Also I've seen people writing custom method to read all bytes from file. This one comes quite handy: ``` byte[] fileData = File.ReadAllBytes(path); // use path from Path.Combine ``` As [TheXenocide](https://stackoverflow.com/users/8543/thexenocide) pointed out, same applies for `File.ReadAllText()` and `File.ReadAllLines()`
178,530
<p>In our web-app we use PHP5.2.6 + PDO to connect to a SQL Server 2005 database and store Russian texts.</p> <p>Database collation is <code>Cyrillic_General_CI_AS</code>, table collation is <code>Cyrillic_General_CI_AS</code>, column type is <code>NVARCHAR(MAX)</code>.</p> <p>We tried connecting to a database using two following schemes, both causing different problems.</p> <ol> <li><p><em>PDO mssql:</em></p> <pre><code>$dbh = new PDO ('mssql:host='.$mssql_server.';dbname='.$mssql_db, $mssql_login, $mssql_pwd); </code></pre> <p>in which case a result of a simple query like that:</p> <pre><code>SELECT field1 FROM tbl1 WHERE id=1 </code></pre> <p>shows <code>field1</code> data truncated to 255 bytes.</p></li> <li><p><em>PDO odbc:</em> </p> <pre><code>$dbh = new PDO ('odbc:DSN=myDSN;UID='.$mssql_login.';PWD='.$mssql_pwd); </code></pre> <p>in which case a result of the same query shows full not truncated data but with question marks instead of Russian symbols. </p></li> </ol> <hr> <p>Notes:</p> <ul> <li>In the SQL Management Studio data is not truncated and Russian symbols are displayed properly as well.</li> <li>We have Windows 2003 Enterprise Edition SP2</li> </ul> <p>So what should we choose as a connection method and how to fix corresponding issues?</p>
[ { "answer_id": 178581, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 0, "selected": false, "text": "<p>I've always had the best luck using utf8_general_ci across the board - for connections, collations - everything.</p>\n\n<p>However, I only have that experience with MySQL and PostgreSql - not with SQL Server.</p>\n\n<p>As to your DSN question - I'm not sure.</p>\n\n<p>Good Luck!</p>\n" }, { "answer_id": 197395, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 3, "selected": true, "text": "<p>Try executing <code>SET NAMES \"charset\"</code> after you connect.</p>\n\n<p>I don't know what the charset to match <code>Cyrillic_General_CI_AS</code> is, but try \"Cyrillic\"?</p>\n" }, { "answer_id": 202098, "author": "Till", "author_id": 2859, "author_profile": "https://Stackoverflow.com/users/2859", "pm_score": 0, "selected": false, "text": "<p>If you are not set on PDO, use <a href=\"http://php.net/manual/en/book.mssql.php\" rel=\"nofollow noreferrer\">FreeTDS</a> - aka procedural mssql_* calls. This is one of the recommended work arounds until PDO is <em>fixed</em>. Since PHP 5.1.2, FreeTDS has a <a href=\"http://php.net/manual/en/mssql.configuration.php\" rel=\"nofollow noreferrer\">mssql.charset-option</a>.</p>\n" }, { "answer_id": 898697, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I noticed the same problem too, with an implementation of SQL server 2005 and PHP 5.x using PDO. When I changed nvarchar(MAX) field to nvarchar(255) the odd question mark characters stopped appearing. I definitely believe it has to do with the ODBC drivers in PDO and MS SQL server. When you implicitly specify the max characters in your varchar, it solves the problem. </p>\n" }, { "answer_id": 2344628, "author": "Liam Morland", "author_id": 282357, "author_profile": "https://Stackoverflow.com/users/282357", "pm_score": 1, "selected": false, "text": "<p>I had to do this to get usable data from my NVARCHAR fields in MSSQL:</p>\n\n<pre><code>$_ = iconv('Windows-1252', 'UTF-8', $_);\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6647/" ]
In our web-app we use PHP5.2.6 + PDO to connect to a SQL Server 2005 database and store Russian texts. Database collation is `Cyrillic_General_CI_AS`, table collation is `Cyrillic_General_CI_AS`, column type is `NVARCHAR(MAX)`. We tried connecting to a database using two following schemes, both causing different problems. 1. *PDO mssql:* ``` $dbh = new PDO ('mssql:host='.$mssql_server.';dbname='.$mssql_db, $mssql_login, $mssql_pwd); ``` in which case a result of a simple query like that: ``` SELECT field1 FROM tbl1 WHERE id=1 ``` shows `field1` data truncated to 255 bytes. 2. *PDO odbc:* ``` $dbh = new PDO ('odbc:DSN=myDSN;UID='.$mssql_login.';PWD='.$mssql_pwd); ``` in which case a result of the same query shows full not truncated data but with question marks instead of Russian symbols. --- Notes: * In the SQL Management Studio data is not truncated and Russian symbols are displayed properly as well. * We have Windows 2003 Enterprise Edition SP2 So what should we choose as a connection method and how to fix corresponding issues?
Try executing `SET NAMES "charset"` after you connect. I don't know what the charset to match `Cyrillic_General_CI_AS` is, but try "Cyrillic"?
178,532
<p>I have a rather large and complex set of programs to port from VC8 to VC9. One of the modules has a number of layered typedefs, which cause the compiler to generate a C4503 warning (decorated name truncated). The generated LIB file will not properly link to other modules in the project. VC8 had no trouble with this, leading me to conclude that either the decoration process has changed to generate even longer names, or the internal limit for the length of a decorated name has decreased. What's the best way to get over this?</p> <p>For legacy code reasons, the MSDN suggestion of replacing typedefs with structs is not practical.</p> <p>The typedefs in question are (sanitized code): </p> <pre><code>enum Type{ TYPE_COUNT, TYPE_VALUE }; typedef MyVector&lt; Container*, CriticalSectionLock &gt; Containers; typedef MyVector&lt; MyClassType*, CriticalSectionLock &gt;::const_iterator const_iterator_type; typedef MyVector&lt; stl::pair&lt; string, Type &gt; &gt;::const_iterator const_iterator_def; typedef MyVector&lt; Container** &gt;::const_iterator const_iterator_container; typedef MyVector&lt; stl::pair &lt; MyBase*, MyVector&lt; stl::pair&lt; Container**, Containers* &gt; &gt; &gt; &gt;::const_iterator const_iterator; </code></pre>
[ { "answer_id": 218959, "author": "Howard Lee Harkness", "author_id": 25823, "author_profile": "https://Stackoverflow.com/users/25823", "pm_score": 2, "selected": false, "text": "<p>Since there does not appear to be a way to increase the compiler's internal limitation on the decorated name length, I bit the bullet and made the change suggested in the MSDN. see: <a href=\"http://msdn.microsoft.com/en-us/library/074af4b6.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/074af4b6.aspx</a></p>\n\n<p>I only had to change the first typedef to a struct. This required about 200 other changes in legacy code, which was tedious, but otherwise not difficult. However, I will be spending the next week or so in regression testing to make sure this did not screw something up.</p>\n\n<p>Here is the basic change: (note that I was forced to add some ctors to the struct)</p>\n\n<pre><code>enum Type{\n TYPE_COUNT,\n TYPE_VALUE\n };\n\n struct Containers \n {\n MyVector&lt;Container*, CriticalSectionLock &gt; Element;\n Containers(int num, Container* elem):Element(num, elem){}\n Containers(){}\n };\n typedef MyVector&lt; MyClassType*, CriticalSectionLock &gt;::const_iterator const_iterator_type;\n typedef MyVector&lt; stl::pair&lt; string, Type &gt; &gt;::const_iterator const_iterator_def;\n typedef MyVector&lt; Container** &gt;::const_iterator const_iterator_container;\n typedef MyVector&lt; stl::pair &lt; MyBase*, MyVector&lt; stl::pair&lt; Container**, Containers* &gt; &gt; &gt; &gt;::const_iterator const_iterator;\n</code></pre>\n" }, { "answer_id": 381173, "author": "Roel", "author_id": 11449, "author_profile": "https://Stackoverflow.com/users/11449", "pm_score": 0, "selected": false, "text": "<pre><code>#pragma warning(disable:xxx).\n</code></pre>\n\n<p>Life's too short man.</p>\n" }, { "answer_id": 466976, "author": "Howard Lee Harkness", "author_id": 25823, "author_profile": "https://Stackoverflow.com/users/25823", "pm_score": 0, "selected": false, "text": "<p>@Roel: As I mentioned in the original posting: \"The generated LIB file will not properly link to other modules in the project.\"</p>\n\n<p>IOW, this is more than just a 'warning'. It causes the project NOT TO WORK.</p>\n\n<p>My posted fix is somewhat difficult and tedious to completely implement, but it does work.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25823/" ]
I have a rather large and complex set of programs to port from VC8 to VC9. One of the modules has a number of layered typedefs, which cause the compiler to generate a C4503 warning (decorated name truncated). The generated LIB file will not properly link to other modules in the project. VC8 had no trouble with this, leading me to conclude that either the decoration process has changed to generate even longer names, or the internal limit for the length of a decorated name has decreased. What's the best way to get over this? For legacy code reasons, the MSDN suggestion of replacing typedefs with structs is not practical. The typedefs in question are (sanitized code): ``` enum Type{ TYPE_COUNT, TYPE_VALUE }; typedef MyVector< Container*, CriticalSectionLock > Containers; typedef MyVector< MyClassType*, CriticalSectionLock >::const_iterator const_iterator_type; typedef MyVector< stl::pair< string, Type > >::const_iterator const_iterator_def; typedef MyVector< Container** >::const_iterator const_iterator_container; typedef MyVector< stl::pair < MyBase*, MyVector< stl::pair< Container**, Containers* > > > >::const_iterator const_iterator; ```
Since there does not appear to be a way to increase the compiler's internal limitation on the decorated name length, I bit the bullet and made the change suggested in the MSDN. see: <http://msdn.microsoft.com/en-us/library/074af4b6.aspx> I only had to change the first typedef to a struct. This required about 200 other changes in legacy code, which was tedious, but otherwise not difficult. However, I will be spending the next week or so in regression testing to make sure this did not screw something up. Here is the basic change: (note that I was forced to add some ctors to the struct) ``` enum Type{ TYPE_COUNT, TYPE_VALUE }; struct Containers { MyVector<Container*, CriticalSectionLock > Element; Containers(int num, Container* elem):Element(num, elem){} Containers(){} }; typedef MyVector< MyClassType*, CriticalSectionLock >::const_iterator const_iterator_type; typedef MyVector< stl::pair< string, Type > >::const_iterator const_iterator_def; typedef MyVector< Container** >::const_iterator const_iterator_container; typedef MyVector< stl::pair < MyBase*, MyVector< stl::pair< Container**, Containers* > > > >::const_iterator const_iterator; ```
178,539
<p>How can I round a decimal number (floating point) to the nearest integer? </p> <p>e.g.</p> <pre><code>1.2 = 1 1.7 = 2 </code></pre>
[ { "answer_id": 178550, "author": "EvdB", "author_id": 5349, "author_profile": "https://Stackoverflow.com/users/5349", "pm_score": 6, "selected": false, "text": "<p>You can either use a module like <A href=\"http://search.cpan.org/dist/Math-Round\" rel=\"noreferrer\">Math::Round</a>:</p>\n\n<pre><code>use Math::Round;\nmy $rounded = round( $float );\n</code></pre>\n\n<p>Or you can do it the crude way:</p>\n\n<pre><code>my $rounded = sprintf \"%.0f\", $float;\n</code></pre>\n" }, { "answer_id": 178551, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 9, "selected": true, "text": "<p>Output of <a href=\"http://perldoc.perl.org/perlfaq4.html#Does-Perl-have-a-round%28)-function%3f--What-about-ceil()-and-floor()%3f--Trig-functions%3f\" rel=\"noreferrer\"><code>perldoc -q round</code></a></p>\n\n<blockquote>\nDoes Perl have a round() function? What about ceil() and floor()?\nTrig functions?\n<p>\nRemember that <a href=\"http://perldoc.perl.org/functions/int.html\" rel=\"noreferrer\"><code>int()</code></a> merely truncates toward <code>0</code>. For rounding to a certain number of digits, <a href=\"http://perldoc.perl.org/functions/sprintf.html\" rel=\"noreferrer\"><code>sprintf()</code></a> or <a href=\"http://perldoc.perl.org/functions/printf.html\" rel=\"noreferrer\"><code>printf()</code></a> is usually the easiest\nroute.\n<p>\n<pre><code> printf(\"%.3f\", 3.1415926535); # prints 3.142\n</code></pre>\n<p>\nThe <a href=\"http://perldoc.perl.org/POSIX.html\" rel=\"noreferrer\"><code>POSIX</code></a> module (part of the standard Perl distribution) implements\n<code>ceil()</code>, <code>floor()</code>, and a number of other mathematical and trigonometric\nfunctions.\n<p>\n<pre><code> use POSIX;\n $ceil = ceil(3.5); # 4\n $floor = floor(3.5); # 3\n</code></pre>\n<p>\nIn 5.000 to 5.003 perls, trigonometry was done in the <a href=\"http://perldoc.perl.org/Math/Complex.html\" rel=\"noreferrer\"><code>Math::Complex</code></a>\nmodule. With 5.004, the <a href=\"http://perldoc.perl.org/Math/Trig.html\" rel=\"noreferrer\"><code>Math::Trig</code></a> module (part of the standard Perl\ndistribution) implements the trigonometric functions. Internally it\nuses the <a href=\"http://perldoc.perl.org/Math/Complex.html\" rel=\"noreferrer\"><code>Math::Complex</code></a> module and some functions can break out from the\nreal axis into the complex plane, for example the inverse sine of 2.\n<p>\nRounding in financial applications can have serious implications, and\nthe rounding method used should be specified precisely. In these\ncases, it probably pays not to trust whichever system rounding is being\nused by Perl, but to instead implement the rounding function you need\nyourself.\n<p>\nTo see why, notice how you'll still have an issue on half-way-point\nalternation:\n<p>\n<pre><code> for ($i = 0; $i &lt; 1.01; $i += 0.05) { printf \"%.1f \",$i}\n\n 0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7\n 0.8 0.8 0.9 0.9 1.0 1.0\n</code></pre>\n<p>\nDon't blame Perl. It's the same as in C. IEEE says we have to do\nthis. Perl numbers whose absolute values are integers under <code>2**31</code> (on\n32 bit machines) will work pretty much like mathematical integers.\nOther numbers are not guaranteed.\n</p>\n</blockquote>\n" }, { "answer_id": 178576, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 3, "selected": false, "text": "<p>See <a href=\"http://perldoc.perl.org/perlfaq4.html\" rel=\"nofollow noreferrer\">perldoc/perlfaq</a>:</p>\n\n<blockquote>\n <p>Remember that <code>int()</code> merely truncates toward 0. For rounding to a\n certain number of digits, <code>sprintf()</code> or <code>printf()</code> is usually the\n easiest route.</p>\n\n<pre><code> printf(\"%.3f\",3.1415926535);\n # prints 3.142\n</code></pre>\n \n <p>The <code>POSIX</code> module (part of the standard Perl distribution)\n implements <code>ceil()</code>, <code>floor()</code>, and a number of other mathematical\n and trigonometric functions.</p>\n\n<pre><code>use POSIX;\n$ceil = ceil(3.5); # 4\n$floor = floor(3.5); # 3\n</code></pre>\n \n <p>In 5.000 to 5.003 perls, trigonometry was done in the <code>Math::Complex</code> module.</p>\n \n <p>With 5.004, the <code>Math::Trig</code> module (part of the standard Perl distribution) > implements the trigonometric functions.</p>\n \n <p>Internally it uses the <code>Math::Complex</code> module and some functions can break\n out from the real axis into the complex plane, for example the inverse sine of 2.</p>\n \n <p>Rounding in financial applications can have serious implications, and the rounding\n method used should be specified precisely. In these cases, it probably pays not to\n trust whichever system rounding is being used by Perl, but to instead implement the\n rounding function you need yourself.</p>\n \n <p>To see why, notice how you'll still have an issue on half-way-point alternation:</p>\n\n<pre><code>for ($i = 0; $i &lt; 1.01; $i += 0.05)\n{\n printf \"%.1f \",$i\n}\n\n0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7 0.8 0.8 0.9 0.9 1.0 1.0\n</code></pre>\n \n <p>Don't blame Perl. It's the same as in C. IEEE says we have to do\n this. Perl numbers whose absolute values are integers under 2**31 (on\n 32 bit machines) will work pretty much like mathematical integers.\n Other numbers are not guaranteed.</p>\n</blockquote>\n" }, { "answer_id": 179086, "author": "Kyle", "author_id": 2237619, "author_profile": "https://Stackoverflow.com/users/2237619", "pm_score": 6, "selected": false, "text": "<p><p>If you decide to use printf or sprintf, note that they use the <a href=\"http://en.wikipedia.org/wiki/Rounding#Round_half_to_even\" rel=\"noreferrer\">Round half to even</a> method.</p>\n\n<pre><code>foreach my $i ( 0.5, 1.5, 2.5, 3.5 ) {\n printf \"$i -&gt; %.0f\\n\", $i;\n}\n__END__\n0.5 -&gt; 0\n1.5 -&gt; 2\n2.5 -&gt; 2\n3.5 -&gt; 4\n</code></pre>\n" }, { "answer_id": 1272301, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<pre><code>cat table |\n perl -ne '/\\d+\\s+(\\d+)\\s+(\\S+)/ &amp;&amp; print \"\".**int**(log($1)/log(2)).\"\\t$2\\n\";' \n</code></pre>\n" }, { "answer_id": 1274692, "author": "RET", "author_id": 14750, "author_profile": "https://Stackoverflow.com/users/14750", "pm_score": 7, "selected": false, "text": "<p>Whilst not disagreeing with the complex answers about half-way marks and so on, for the more common (and possibly trivial) use-case:</p>\n\n<p><code>my $rounded = int($float + 0.5);</code></p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>If it's possible for your <code>$float</code> to be negative, the following variation will produce the correct result:</p>\n\n<p><code>my $rounded = int($float + $float/abs($float*2 || 1));</code></p>\n\n<p>With this calculation -1.4 is rounded to -1, and -1.6 to -2, and zero won't explode.</p>\n" }, { "answer_id": 4503906, "author": "David Beckman", "author_id": 127054, "author_profile": "https://Stackoverflow.com/users/127054", "pm_score": 1, "selected": false, "text": "<p>Following is a sample of five different ways to summate values. The first is a naive way to perform the summation (and fails). The second attempts to use <code>sprintf()</code>, but it too fails. The third uses <code>sprintf()</code> successfully while the final two (4th &amp; 5th) use <code>floor($value + 0.5)</code>.</p>\n\n<pre><code> use strict;\n use warnings;\n use POSIX;\n\n my @values = (26.67,62.51,62.51,62.51,68.82,79.39,79.39);\n my $total1 = 0.00;\n my $total2 = 0;\n my $total3 = 0;\n my $total4 = 0.00;\n my $total5 = 0;\n my $value1;\n my $value2;\n my $value3;\n my $value4;\n my $value5;\n\n foreach $value1 (@values)\n {\n $value2 = $value1;\n $value3 = $value1;\n $value4 = $value1;\n $value5 = $value1;\n\n $total1 += $value1;\n\n $total2 += sprintf('%d', $value2 * 100);\n\n $value3 = sprintf('%1.2f', $value3);\n $value3 =~ s/\\.//;\n $total3 += $value3;\n\n $total4 += $value4;\n\n $total5 += floor(($value5 * 100.0) + 0.5);\n }\n\n $total1 *= 100;\n $total4 = floor(($total4 * 100.0) + 0.5);\n\n print '$total1: '.sprintf('%011d', $total1).\"\\n\";\n print '$total2: '.sprintf('%011d', $total2).\"\\n\";\n print '$total3: '.sprintf('%011d', $total3).\"\\n\";\n print '$total4: '.sprintf('%011d', $total4).\"\\n\";\n print '$total5: '.sprintf('%011d', $total5).\"\\n\";\n\n exit(0);\n\n #$total1: 00000044179\n #$total2: 00000044179\n #$total3: 00000044180\n #$total4: 00000044180\n #$total5: 00000044180\n</code></pre>\n\n<p>Note that <code>floor($value + 0.5)</code> can be replaced with <code>int($value + 0.5)</code> to remove the dependency on <code>POSIX</code>.</p>\n" }, { "answer_id": 6336201, "author": "activealexaoki", "author_id": 796622, "author_profile": "https://Stackoverflow.com/users/796622", "pm_score": 2, "selected": false, "text": "<p>You don't need any external module.</p>\n\n<pre><code>$x[0] = 1.2;\n$x[1] = 1.7;\n\nforeach (@x){\n print $_.' = '.( ( ($_-int($_))&lt;0.5) ? int($_) : int($_)+1 );\n print \"\\n\";\n}\n</code></pre>\n\n<p>I may be missing your point, but I thought this was much cleaner way to do the same job.</p>\n\n<p>What this does is to walk through every positive number in the element, print the number and rounded integer in the format you mentioned. The code concatenates respective rounded positive integer only based on the decimals. int($_) basically <em>round-down</em> the number so ($<em>-int($</em>)) captures the decimals. If the decimals are (by definition) strictly less than 0.5, round-down the number. If not, round-up by adding 1.</p>\n" }, { "answer_id": 7154435, "author": "matt", "author_id": 906753, "author_profile": "https://Stackoverflow.com/users/906753", "pm_score": 1, "selected": false, "text": "<p>Negative numbers can add some quirks that people need to be aware of.</p>\n\n<p><code>printf</code>-style approaches give us correct numbers, but they can result in some odd displays. We have discovered that this method (in my opinion, stupidly) puts in a <code>-</code> sign whether or not it should or shouldn't. For example, -0.01 rounded to one decimal place returns a -0.0, rather than just 0. If you are going to do the <code>printf</code> style approach, and you know you want no decimal, use <code>%d</code> and not <code>%f</code> (when you need decimals, it's when the display gets wonky).</p>\n\n<p>While it's correct and for math no big deal, for display it just looks weird showing something like \"-0.0\".</p>\n\n<p>For the int method, negative numbers can change what you want as a result (though there are some arguments that can be made they are correct).</p>\n\n<p>The <code>int + 0.5</code> causes real issues with -negative numbers, unless you want it to work that way, but I imagine most people don't. -0.9 should probably round to -1, not 0. If you know that you want negative to be a ceiling rather than a floor then you can do it in one-liner, otherwise, you might want to use the int method with a minor modification (this obviously only works to get back whole numbers:</p>\n\n<pre><code>my $var = -9.1;\nmy $tmpRounded = int( abs($var) + 0.5));\nmy $finalRounded = $var &gt;= 0 ? 0 + $tmpRounded : 0 - $tmpRounded;\n</code></pre>\n" }, { "answer_id": 8064429, "author": "Akvel", "author_id": 442050, "author_profile": "https://Stackoverflow.com/users/442050", "pm_score": 0, "selected": false, "text": "<p>My solution for sprintf</p>\n\n<pre><code>if ($value =~ m/\\d\\..*5$/){\n $format =~ /.*(\\d)f$/;\n if (defined $1){\n my $coef = \"0.\" . \"0\" x $1 . \"05\"; \n $value = $value + $coef; \n }\n}\n\n$value = sprintf( \"$format\", $value );\n</code></pre>\n" }, { "answer_id": 25810334, "author": "seacoder", "author_id": 3428701, "author_profile": "https://Stackoverflow.com/users/3428701", "pm_score": 2, "selected": false, "text": "<p>The following will round positive or negative numbers to a given decimal position:</p>\n\n<pre><code>sub round ()\n{\n my ($x, $pow10) = @_;\n my $a = 10 ** $pow10;\n\n return (int($x / $a + (($x &lt; 0) ? -0.5 : 0.5)) * $a);\n}\n</code></pre>\n" }, { "answer_id": 39668498, "author": "HoldOffHunger", "author_id": 2430549, "author_profile": "https://Stackoverflow.com/users/2430549", "pm_score": 1, "selected": false, "text": "<p>If you are only concerned with getting an integer value out of a whole floating point number (i.e. 12347.9999 or 54321.0001), this approach (borrowed and modified from above) will do the trick:</p>\n\n<pre><code>my $rounded = floor($float + 0.1); \n</code></pre>\n" }, { "answer_id": 59225239, "author": "Jarett Lloyd", "author_id": 4612801, "author_profile": "https://Stackoverflow.com/users/4612801", "pm_score": 0, "selected": false, "text": "<p>loads of reading documentation on how to round numbers, many experts suggest writing your own rounding routines, as the 'canned' version provided with your language may not be precise enough, or contain errors. i imagine, however, they're talking many decimal places not just one, two, or three. with that in mind, here is my solution (although not EXACTLY as requested as my needs are to display dollars - the process is not much different, though). </p>\n\n<pre><code>sub asDollars($) {\n my ($cost) = @_;\n my $rv = 0;\n\n my $negative = 0;\n if ($cost =~ /^-/) {\n $negative = 1;\n $cost =~ s/^-//;\n }\n\n my @cost = split(/\\./, $cost);\n\n # let's get the first 3 digits of $cost[1]\n my ($digit1, $digit2, $digit3) = split(\"\", $cost[1]);\n # now, is $digit3 &gt;= 5?\n # if yes, plus one to $digit2.\n # is $digit2 &gt; 9 now?\n # if yes, $digit2 = 0, $digit1++\n # is $digit1 &gt; 9 now??\n # if yes, $digit1 = 0, $cost[0]++\n if ($digit3 &gt;= 5) {\n $digit3 = 0;\n $digit2++;\n if ($digit2 &gt; 9) {\n $digit2 = 0;\n $digit1++;\n if ($digit1 &gt; 9) {\n $digit1 = 0;\n $cost[0]++;\n }\n }\n }\n $cost[1] = $digit1 . $digit2;\n if ($digit1 ne \"0\" and $cost[1] &lt; 10) { $cost[1] .= \"0\"; }\n\n # and pretty up the left of decimal\n if ($cost[0] &gt; 999) { $cost[0] = commafied($cost[0]); }\n\n $rv = join(\".\", @cost);\n\n if ($negative) { $rv = \"-\" . $rv; }\n\n return $rv;\n}\n\nsub commafied($) {\n #*\n # to insert commas before every 3rd number (from the right)\n # positive or negative numbers\n #*\n my ($num) = @_; # the number to insert commas into!\n\n my $negative = 0;\n if ($num =~ /^-/) {\n $negative = 1;\n $num =~ s/^-//;\n }\n $num =~ s/^(0)*//; # strip LEADING zeros from given number!\n $num =~ s/0/-/g; # convert zeros to dashes because ... computers!\n\n if ($num) {\n my @digits = reverse split(\"\", $num);\n $num = \"\";\n\n for (my $i = 0; $i &lt; @digits; $i += 3) {\n $num .= $digits[$i];\n if ($digits[$i+1]) { $num .= $digits[$i+1]; }\n if ($digits[$i+2]) { $num .= $digits[$i+2]; }\n if ($i &lt; (@digits - 3)) { $num .= \",\"; }\n if ($i &gt;= @digits) { last; }\n }\n\n #$num =~ s/,$//;\n $num = join(\"\", reverse split(\"\", $num));\n $num =~ s/-/0/g;\n }\n\n if ($negative) { $num = \"-\" . $num; }\n\n return $num; # a number with commas added\n #usage: my $prettyNum = commafied(1234567890);\n}\n</code></pre>\n" }, { "answer_id": 67497204, "author": "A1rPun", "author_id": 1449624, "author_profile": "https://Stackoverflow.com/users/1449624", "pm_score": 0, "selected": false, "text": "<p>Using <a href=\"https://perldoc.perl.org/Math::BigFloat\" rel=\"nofollow noreferrer\"><code>Math::BigFloat</code></a> you can do something like this:</p>\n<pre><code>use Math::BigFloat;\n\nprint Math::BigFloat-&gt;new(1.2)-&gt;bfround(1); ## 1\nprint Math::BigFloat-&gt;new(1.7)-&gt;bfround(1); ## 2\n</code></pre>\n<p>This can be wrapped in a subroutine</p>\n<pre><code>use Math::BigFloat;\n\nsub round {\n Math::BigFloat-&gt;new(shift)-&gt;bfround(1);\n}\n\nprint round(1.2); ## 1\nprint round(1.7); ## 2\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12850/" ]
How can I round a decimal number (floating point) to the nearest integer? e.g. ``` 1.2 = 1 1.7 = 2 ```
Output of [`perldoc -q round`](http://perldoc.perl.org/perlfaq4.html#Does-Perl-have-a-round%28)-function%3f--What-about-ceil()-and-floor()%3f--Trig-functions%3f) > > Does Perl have a round() function? What about ceil() and floor()? > Trig functions? > > Remember that [`int()`](http://perldoc.perl.org/functions/int.html) merely truncates toward `0`. For rounding to a certain number of digits, [`sprintf()`](http://perldoc.perl.org/functions/sprintf.html) or [`printf()`](http://perldoc.perl.org/functions/printf.html) is usually the easiest > route. > > > ``` > printf("%.3f", 3.1415926535); # prints 3.142 > > ``` > > > The [`POSIX`](http://perldoc.perl.org/POSIX.html) module (part of the standard Perl distribution) implements > `ceil()`, `floor()`, and a number of other mathematical and trigonometric > functions. > > > ``` > use POSIX; > $ceil = ceil(3.5); # 4 > $floor = floor(3.5); # 3 > > ``` > > > In 5.000 to 5.003 perls, trigonometry was done in the [`Math::Complex`](http://perldoc.perl.org/Math/Complex.html) > module. With 5.004, the [`Math::Trig`](http://perldoc.perl.org/Math/Trig.html) module (part of the standard Perl > distribution) implements the trigonometric functions. Internally it > uses the [`Math::Complex`](http://perldoc.perl.org/Math/Complex.html) module and some functions can break out from the > real axis into the complex plane, for example the inverse sine of 2. > > Rounding in financial applications can have serious implications, and > the rounding method used should be specified precisely. In these > cases, it probably pays not to trust whichever system rounding is being > used by Perl, but to instead implement the rounding function you need > yourself. > > To see why, notice how you'll still have an issue on half-way-point > alternation: > > > ``` > for ($i = 0; $i < 1.01; $i += 0.05) { printf "%.1f ",$i} > > 0.0 0.1 0.1 0.2 0.2 0.2 0.3 0.3 0.4 0.4 0.5 0.5 0.6 0.7 0.7 > 0.8 0.8 0.9 0.9 1.0 1.0 > > ``` > > > Don't blame Perl. It's the same as in C. IEEE says we have to do > this. Perl numbers whose absolute values are integers under `2**31` (on > 32 bit machines) will work pretty much like mathematical integers. > Other numbers are not guaranteed. > > > > > > > > > > > > > > > > > > > >
178,561
<p>I have the following VB.net interface that I need to port to C#. C# does not allow enumerations in interfaces. How can I port this without changing code that uses this interface?</p> <pre><code>Public Interface MyInterface Enum MyEnum Yes = 0 No = 1 Maybe = 2 End Enum ReadOnly Property Number() As MyEnum End Interface </code></pre>
[ { "answer_id": 178573, "author": "Alexander Kojevnikov", "author_id": 712, "author_profile": "https://Stackoverflow.com/users/712", "pm_score": 4, "selected": false, "text": "<pre><code>public enum MyEnum\n{\n Yes = 0,\n No = 1,\n Maybe = 2\n}\n\npublic interface IMyInterface\n{\n MyEnum Number { get; }\n}\n</code></pre>\n" }, { "answer_id": 178677, "author": "Jeremy Frey", "author_id": 13412, "author_profile": "https://Stackoverflow.com/users/13412", "pm_score": 5, "selected": true, "text": "<p>In short, you can't change that interface without breaking code, because C# can't nest types in interfaces. When you implement the VB.NET versions's interface, you are specifying that Number will return a type of MyInterface.MyEnum:</p>\n\n<pre><code>class TestClass3 : TestInterfaces.MyInterface\n{\n\n TestInterfaces.MyInterface.MyEnum TestInterfaces.MyInterface.Number\n {\n get { throw new Exception(\"The method or operation is not implemented.\"); }\n }\n\n}\n</code></pre>\n\n<p>However, since C# can't nest types inside interfaces, if you break the enumerator out of the interface, you will be returning a different data type: in this case, MyEnum.</p>\n\n<pre><code>class TestClass2 : IMyInterface\n{\n\n MyEnum IMyInterface.Number\n {\n get { throw new Exception(\"The method or operation is not implemented.\"); }\n }\n\n}\n</code></pre>\n\n<p>Think about it using the fully qualified type name. In the VB.NET interface, you have a return type of</p>\n\n<p>MyProject.MyInterface.MyEnum</p>\n\n<p>In the C# interface, you have:</p>\n\n<p>MyProject.MyEnum.</p>\n\n<p>Unfortunately, code that implements the VB.NET interface would have to be changed to support the fact that the type returned by MyInterface.Number has changed.</p>\n\n<p>IL supports nesting types inside interfaces, so it's a mystery why C# doesn't:</p>\n\n<pre><code>.class public interface abstract auto ansi MyInterface\n</code></pre>\n\n<p>{\n .property instance valuetype TestInterfaces.MyInterface/MyEnum Number\n {\n .get instance valuetype TestInterfaces.MyInterface/MyEnum TestInterfaces.MyInterface::get_Number()\n }</p>\n\n<pre><code>.class auto ansi sealed nested public MyEnum\n extends [mscorlib]System.Enum\n</code></pre>\n\n<p>{\n .field public static literal valuetype TestInterfaces.MyInterface/MyEnum Maybe = int32(2)</p>\n\n<pre><code> .field public static literal valuetype TestInterfaces.MyInterface/MyEnum No = int32(1)\n\n .field public specialname rtspecialname int32 value__\n\n .field public static literal valuetype TestInterfaces.MyInterface/MyEnum Yes = int32(0)\n\n}\n</code></pre>\n\n<p>}</p>\n\n<p>If you have lots of code in other assemblies that make use of this interface, your best bet is to keep it inside a separate VB.NET assembly, and reference it from your C# projects. Otherwise, it's safe to convert it, but you'll have to change any code that uses it to return the different type.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25825/" ]
I have the following VB.net interface that I need to port to C#. C# does not allow enumerations in interfaces. How can I port this without changing code that uses this interface? ``` Public Interface MyInterface Enum MyEnum Yes = 0 No = 1 Maybe = 2 End Enum ReadOnly Property Number() As MyEnum End Interface ```
In short, you can't change that interface without breaking code, because C# can't nest types in interfaces. When you implement the VB.NET versions's interface, you are specifying that Number will return a type of MyInterface.MyEnum: ``` class TestClass3 : TestInterfaces.MyInterface { TestInterfaces.MyInterface.MyEnum TestInterfaces.MyInterface.Number { get { throw new Exception("The method or operation is not implemented."); } } } ``` However, since C# can't nest types inside interfaces, if you break the enumerator out of the interface, you will be returning a different data type: in this case, MyEnum. ``` class TestClass2 : IMyInterface { MyEnum IMyInterface.Number { get { throw new Exception("The method or operation is not implemented."); } } } ``` Think about it using the fully qualified type name. In the VB.NET interface, you have a return type of MyProject.MyInterface.MyEnum In the C# interface, you have: MyProject.MyEnum. Unfortunately, code that implements the VB.NET interface would have to be changed to support the fact that the type returned by MyInterface.Number has changed. IL supports nesting types inside interfaces, so it's a mystery why C# doesn't: ``` .class public interface abstract auto ansi MyInterface ``` { .property instance valuetype TestInterfaces.MyInterface/MyEnum Number { .get instance valuetype TestInterfaces.MyInterface/MyEnum TestInterfaces.MyInterface::get\_Number() } ``` .class auto ansi sealed nested public MyEnum extends [mscorlib]System.Enum ``` { .field public static literal valuetype TestInterfaces.MyInterface/MyEnum Maybe = int32(2) ``` .field public static literal valuetype TestInterfaces.MyInterface/MyEnum No = int32(1) .field public specialname rtspecialname int32 value__ .field public static literal valuetype TestInterfaces.MyInterface/MyEnum Yes = int32(0) } ``` } If you have lots of code in other assemblies that make use of this interface, your best bet is to keep it inside a separate VB.NET assembly, and reference it from your C# projects. Otherwise, it's safe to convert it, but you'll have to change any code that uses it to return the different type.
178,578
<p>I'm using Webbrowser control to login to HTTPS site with "untrusted certificate". but I get popup such standart window "Security Alert" about untrusted certificate:</p> <p><img src="https://i.stack.imgur.com/U01dp.jpg" alt="Security Alert window"></p> <p>I have to find this window by title and send it <kbd>Alt</kbd>+<kbd>Y</kbd> to press <em>Yes</em>:</p> <pre><code>int iHandle = NativeWin32.FindWindow(null, "Security Alert"); NativeWin32.SetForegroundWindow(iHandle); System.Windows.Forms.SendKeys.Send("Y%"); </code></pre> <p>but user can see a flickering of this window.</p> <p>How can I ignore this alert?<br> Or disable this "untrusted certificate" check in Webbrowser control?</p>
[ { "answer_id": 178595, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 3, "selected": true, "text": "<p>This should do it:</p>\n\n<pre><code>public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)\n{\n return true;\n}\n\nServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate);\n</code></pre>\n\n<p>Obviously, blindingly allowing certificates is a security risk. Be careful.</p>\n" }, { "answer_id": 11234222, "author": "Daniel Ballinger", "author_id": 54026, "author_profile": "https://Stackoverflow.com/users/54026", "pm_score": 1, "selected": false, "text": "<p>If the certificate isn't from a trusted certifying authority (the first point in the prompt) then you could install the certificate under the Trusted Root Certification Authorities on the PCs in question.</p>\n\n<p>You can do this under View Certificate.</p>\n\n<p>In some ways this could be a simpler solution as it doesn't require any code changes that accept any and all certificates. It does however require the certificate to be installed wherever the application is used.</p>\n" }, { "answer_id": 13178954, "author": "Adil", "author_id": 1472837, "author_profile": "https://Stackoverflow.com/users/1472837", "pm_score": 0, "selected": false, "text": "<p>When I set the WebBrowser.ScriptErrorsSuppressed property to false, I do not get these popups anymore</p>\n" }, { "answer_id": 31160632, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p><a href=\"http://blogs.msdn.com/b/ieinternals/archive/2011/05/04/side-effects-of-setting-the-silent-scripterrorssuppressed-property-for-web-browser-control.aspx\" rel=\"nofollow\">I see this solution.it work for me.It very easy way.</a></p>\n" }, { "answer_id": 35363019, "author": "VCody", "author_id": 4298559, "author_profile": "https://Stackoverflow.com/users/4298559", "pm_score": 1, "selected": false, "text": "<p>Here,we go with the solution:\nI run it on the Browser_Navigated event as the underlying activeX component is null until then.</p>\n\n<p><strong>Ref:</strong><a href=\"https://social.msdn.microsoft.com/Forums/vstudio/en-US/4f686de1-8884-4a8d-8ec5-ae4eff8ce6db/new-wpf-webbrowser-how-do-i-suppress-script-errors?forum=wpf\" rel=\"nofollow\">https://social.msdn.microsoft.com/Forums/vstudio/en-US/4f686de1-8884-4a8d-8ec5-ae4eff8ce6db/new-wpf-webbrowser-how-do-i-suppress-script-errors?forum=wpf</a></p>\n\n<pre><code> private void Browser_Navigating_1(object sender, NavigatingCancelEventArgs e)\n {\n HideScriptErrors(Browser,true);\n\n }\n\n public void HideScriptErrors(WebBrowser wb, bool Hide)\n {\n\n FieldInfo fiComWebBrowser = typeof(WebBrowser).GetField(\"_axIWebBrowser2\", BindingFlags.Instance | BindingFlags.NonPublic);\n if (fiComWebBrowser == null) return;\n object objComWebBrowser = fiComWebBrowser.GetValue(wb);\n\n if (objComWebBrowser == null) return;\n\n objComWebBrowser.GetType().InvokeMember(\n \"Silent\", BindingFlags.SetProperty, null, objComWebBrowser, new object[] { Hide });\n\n }\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25826/" ]
I'm using Webbrowser control to login to HTTPS site with "untrusted certificate". but I get popup such standart window "Security Alert" about untrusted certificate: ![Security Alert window](https://i.stack.imgur.com/U01dp.jpg) I have to find this window by title and send it `Alt`+`Y` to press *Yes*: ``` int iHandle = NativeWin32.FindWindow(null, "Security Alert"); NativeWin32.SetForegroundWindow(iHandle); System.Windows.Forms.SendKeys.Send("Y%"); ``` but user can see a flickering of this window. How can I ignore this alert? Or disable this "untrusted certificate" check in Webbrowser control?
This should do it: ``` public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; } ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); ``` Obviously, blindingly allowing certificates is a security risk. Be careful.
178,580
<p>We are trying to bind a Linux machine (debian 4.0) to W2k3 AD. We have configured kerberos properly so that we can get TGTs. And users authenticate properly. However, PAM seems to be the sticky wicket. For example when we try to SSH to the linux machine as one of the AD users, the authentication succeeds (as per the auth.log) but I never get shell. The default environment is configured properly and PAM even creates the Homedir properly. As a reference we were loosely following:</p> <p><a href="https://help.ubuntu.com/community/ActiveDirectoryHowto" rel="nofollow noreferrer">https://help.ubuntu.com/community/ActiveDirectoryHowto</a></p>
[ { "answer_id": 181906, "author": "Pontus", "author_id": 23483, "author_profile": "https://Stackoverflow.com/users/23483", "pm_score": 1, "selected": false, "text": "<p>If you're confident everything but PAM works correctly, I suggest passing the debug option to pam_krb5.so to see if that gives a clue to what's happening.</p>\n\n<p>I'd also suggest verifying that nss-ldap is set up correctly using </p>\n\n<pre><code>getent passwd avalidusername\n</code></pre>\n" }, { "answer_id": 296169, "author": "csexton", "author_id": 19839, "author_profile": "https://Stackoverflow.com/users/19839", "pm_score": 0, "selected": false, "text": "<p>I have used Likewise to do something similar on our servers. Here is the process we use to configure it:</p>\n\n<p>Install Likewise:</p>\n\n<pre><code>$ sudo apt-get update\n$ sudo apt-get install likewise-open\n</code></pre>\n\n<p>Join the domain (Assuming the domain \"domain.local\")</p>\n\n<pre><code>$ sudo domainjoin-cli join domain.local Administrator\n$ sudo update-rc.d likewise-open defaults\n$ sudo /etc/init.d/likewise-open start\n</code></pre>\n\n<p>Assuming you are using sudo AND want AD users to be able to have sudoer powers, you need to edit the sudoers file. This can be done with following command:</p>\n\n<pre><code>$ sudo visudo\n</code></pre>\n\n<p>then add the following to the end of the file (this assumes the domain \"DOMAIN\" and all the users that should have sudo are in a group called \"linux_admin\" in active directory):</p>\n\n<pre><code>%DOMAIN\\\\linux_admin ALL=(ALL) ALL\n</code></pre>\n" }, { "answer_id": 1844766, "author": "s00th", "author_id": 224478, "author_profile": "https://Stackoverflow.com/users/224478", "pm_score": 0, "selected": false, "text": "<p>POSIX accounts demand that you have a vaild shell set in the user account. When using LDAP, this is referenced by the attribute loginShell. You need to use PAM and map an appropriate attribute to loginShell in your configuration, or active MS services for UNIX on the DC, which will extend the AD schema to include the needed POSIX attributes.</p>\n\n<p>See <a href=\"http://www.ietf.org/rfc/rfc2307.txt\" rel=\"nofollow noreferrer\">http://www.ietf.org/rfc/rfc2307.txt</a> as a reference to RFC2307, which defines this for LDAP.</p>\n" }, { "answer_id": 2495301, "author": "jas", "author_id": 299336, "author_profile": "https://Stackoverflow.com/users/299336", "pm_score": 0, "selected": false, "text": "<p>A simple solution.. <a href=\"http://pam-krb5-ldap.sourceforge.net\" rel=\"nofollow noreferrer\">pam_krb5+ldap project</a></p>\n\n<p>A fork of the pam_krb5 PAM module that provides a very easy to use configuration for utilizing linux client authentication against and existing Active directory domain and/or OpenLDAP server.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
We are trying to bind a Linux machine (debian 4.0) to W2k3 AD. We have configured kerberos properly so that we can get TGTs. And users authenticate properly. However, PAM seems to be the sticky wicket. For example when we try to SSH to the linux machine as one of the AD users, the authentication succeeds (as per the auth.log) but I never get shell. The default environment is configured properly and PAM even creates the Homedir properly. As a reference we were loosely following: <https://help.ubuntu.com/community/ActiveDirectoryHowto>
If you're confident everything but PAM works correctly, I suggest passing the debug option to pam\_krb5.so to see if that gives a clue to what's happening. I'd also suggest verifying that nss-ldap is set up correctly using ``` getent passwd avalidusername ```
178,600
<p>The project is ASP.NET 2.0, I have never been able to reproduce this myself, but I get emails informing me it happens to clients many times a week, often a few times in a row.</p> <p>Here is the full error:</p> <p>Exception Details: </p> <blockquote> <p>Microsoft.Reporting.WebForms.AspNetSessionExpiredException: ASP.NET session has expired</p> </blockquote> <p>Stack Trace: </p> <blockquote> <p>[AspNetSessionExpiredException: ASP.NET session has expired] at Microsoft.Reporting.WebForms.ReportDataOperation..ctor() at Microsoft.Reporting.WebForms.HttpHandler.GetHandler() at Microsoft.Reporting.WebForms.HttpHandler.ProcessRequest(HttpContext context) at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; completedSynchronously) Session Objects:75de8e1d65ff40d1ba666d940af5b118: Microsoft.Reporting.WebForms.ReportHierarchy 5210064be1fa4d6abf5dd5e56b262974: Microsoft.Reporting.WebForms.ReportHierarchy</p> </blockquote>
[ { "answer_id": 178638, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 0, "selected": false, "text": "<p>What is the question? The session expired and they cannot continue.</p>\n\n<p>Check the report process speed. Build in some kind of benchmark or simply ask them to measure the report processing. </p>\n\n<p>Easily can be that it is working for you, but not for them (slower network, more data to handle, slower DB server, and so on).</p>\n\n<p><strong>Edit:</strong> <a href=\"http://social.msdn.microsoft.com/Forums/en-US/vsreportcontrols/thread/94a3b28c-273b-4781-b83c-2265effb96f5/\" rel=\"nofollow noreferrer\">Here is</a> another explanaition and maybe a solution for the problem, but I don't recomment to set the worker process number to 1 on a procudtion environment.</p>\n" }, { "answer_id": 178812, "author": "Jon Adams", "author_id": 2291, "author_profile": "https://Stackoverflow.com/users/2291", "pm_score": 5, "selected": true, "text": "<p>We had the same problem. So far, we only found it when the session expired but they used the back button in a browser that does aggressive caching, which is fine. But the ReportViewer tried to to a refresh even though the main page did not. So, we just added some hacky Global.asax error handling:</p>\n\n<pre><code>protected void Application_Error(object sender, EventArgs e)\n{\n Exception exc = Server.GetLastError().GetBaseException();\n if (exc is Microsoft.Reporting.WebForms.AspNetSessionExpiredException)\n {\n Server.ClearError();\n Response.Redirect(FormsAuthentication.LoginUrl + \"?ReturnUrl=\" + HttpUtility.UrlEncode(Request.Url.PathAndQuery), true);\n }\n}\n</code></pre>\n" }, { "answer_id": 240230, "author": "DrCamel", "author_id": 4168, "author_profile": "https://Stackoverflow.com/users/4168", "pm_score": 2, "selected": false, "text": "<p><strong>Session Timeout</strong></p>\n\n<p>This can be due to your session timeout being too low. Check out the \"sessionState\" section of your Web.Config, e.g. :-</p>\n\n<pre><code>&lt;system.web&gt;&lt;sessionState mode=\"InProc\" timeout=\"60\" /&gt;&lt;/system.web&gt;\n</code></pre>\n\n<p>Which would set a session timeout of 60 minutes.</p>\n\n<p><strong>Application Pool Recycle</strong></p>\n\n<p>Another possible cause, and one which we ran into, is that your application pool is being recycled for some reason.</p>\n\n<p>In out case it was because we were hitting a \"Maximum virtual memory\" setting, I just upped that and everything has been fine since.</p>\n\n<p>Have a look in your System Event Log for 1010, 1011, 1074, 1077, 1078, 1079, 1080 and 1117 events from W3SVC and see if your app pool is being recycled and if so, it should state why.</p>\n" }, { "answer_id": 3762720, "author": "Brilliant Logic", "author_id": 454240, "author_profile": "https://Stackoverflow.com/users/454240", "pm_score": 2, "selected": false, "text": "<p>Here was my fix.</p>\n\n<p>Running IIS on a web farm, and each farm has a web garden count=3 each,</p>\n\n<p>I simply made a seperate application pool just for sql reports and set that web gardern count=1 just for this reporting pool.</p>\n\n<p>then, made a virtual directory in IIS and a seperate project for reporting - using that reporting pool</p>\n\n<p>problem solved.</p>\n" }, { "answer_id": 9615607, "author": "Ron Chong", "author_id": 1256689, "author_profile": "https://Stackoverflow.com/users/1256689", "pm_score": 0, "selected": false, "text": "<p><code>web gardern count=1</code> Works for me</p>\n" }, { "answer_id": 12798878, "author": "Brad Herder", "author_id": 1731570, "author_profile": "https://Stackoverflow.com/users/1731570", "pm_score": 1, "selected": false, "text": "<p>I had this problem when developing on my own PC and could not find an answer anywhere on the net. It turned out that one of my teammates added this to the web.config:</p>\n\n<pre><code>&lt;httpCookies httpOnlyCookies=\"false\" requireSSL=\"true\" /&gt;\n</code></pre>\n\n<p>So the <code>web.config</code> on the developer’s desktop should not have the tag and the DEV/QAS and Prod web.config files should have it.</p>\n\n<p>I also understand it is possible for developers to use IIS Express and then they could use SSL locally. </p>\n" }, { "answer_id": 68271841, "author": "Bleard Berisha", "author_id": 16391918, "author_profile": "https://Stackoverflow.com/users/16391918", "pm_score": 0, "selected": false, "text": "<p>Check number of <strong>Maximum Worker Processes</strong> for Application Pool,\nbecause Asp NET Session is different for Worker Processes.</p>\n<p>If you have more than 1 <strong>Worker Process</strong> and <strong>In-Process Sesion State</strong> then each process will have their own Session.</p>\n<p><strong>Sesion State Types</strong></p>\n<ol>\n<li>In-process: Session state is stored in the worker process where the\nASP.NET application runs.</li>\n<li>State Server: Session state is stored\noutside the worker process where the ASP.NET application runs.</li>\n<li>SQL Server: Session state is stored in a SQL Server database.</li>\n</ol>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21367/" ]
The project is ASP.NET 2.0, I have never been able to reproduce this myself, but I get emails informing me it happens to clients many times a week, often a few times in a row. Here is the full error: Exception Details: > > Microsoft.Reporting.WebForms.AspNetSessionExpiredException: ASP.NET session has expired > > > Stack Trace: > > [AspNetSessionExpiredException: ASP.NET session has expired] > at Microsoft.Reporting.WebForms.ReportDataOperation..ctor() > at Microsoft.Reporting.WebForms.HttpHandler.GetHandler() > at Microsoft.Reporting.WebForms.HttpHandler.ProcessRequest(HttpContext context) > at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() > at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) > Session Objects:75de8e1d65ff40d1ba666d940af5b118: Microsoft.Reporting.WebForms.ReportHierarchy > 5210064be1fa4d6abf5dd5e56b262974: Microsoft.Reporting.WebForms.ReportHierarchy > > >
We had the same problem. So far, we only found it when the session expired but they used the back button in a browser that does aggressive caching, which is fine. But the ReportViewer tried to to a refresh even though the main page did not. So, we just added some hacky Global.asax error handling: ``` protected void Application_Error(object sender, EventArgs e) { Exception exc = Server.GetLastError().GetBaseException(); if (exc is Microsoft.Reporting.WebForms.AspNetSessionExpiredException) { Server.ClearError(); Response.Redirect(FormsAuthentication.LoginUrl + "?ReturnUrl=" + HttpUtility.UrlEncode(Request.Url.PathAndQuery), true); } } ```
178,601
<pre><code>&lt;div spry:region="ds1" spry:repeatchildren="ds1"&gt; &lt;b spry:if=" '{title}'!='' "&gt; &lt;!-- this is the first if --&gt; &lt;a href="#" spry:if=" '{author}'!='' "&gt;{author} &lt;!-- this is the second if --&gt; &lt;/a&gt; &lt;/b&gt; &lt;/div&gt; </code></pre> <p><br><br> I wonder if there is any method as simple as </p> <pre><code>if(x==y &amp;&amp; i&gt;j) </code></pre> <p>in </p> <pre><code>&lt;b&gt;spry&lt;/b&gt; </code></pre> <p>region. I can't find any information in spry docs (labs.adobe.com/technologies/spry/)</p>
[ { "answer_id": 2810735, "author": "porges", "author_id": 10311, "author_profile": "https://Stackoverflow.com/users/10311", "pm_score": 1, "selected": false, "text": "<p>The syntax inside the <code>spry:if</code> attribute is Javascript, so you can use <code>&amp;&amp;</code>:</p>\n\n<pre><code>&lt;b spry:if=\"'{title}' != '' &amp;&amp; '{author}' != ''\"&gt;\n&lt;!-- ... --&gt;\n&lt;/b&gt;\n</code></pre>\n" }, { "answer_id": 3352414, "author": "loali", "author_id": 404265, "author_profile": "https://Stackoverflow.com/users/404265", "pm_score": 1, "selected": false, "text": "<p>also you can call a function instead</p>\n\n<pre><code>spry:if=\"myFunc();\"\n</code></pre>\n\n<p>and in your function return Boolean value as result </p>\n\n<pre><code>function myfunc()\n{\n//do somethings ;\nif(...)\nreturn true;\nelse\nreturn false;\n}\n</code></pre>\n" }, { "answer_id": 17003176, "author": "Narayan Yerrabachu", "author_id": 2379046, "author_profile": "https://Stackoverflow.com/users/2379046", "pm_score": 0, "selected": false, "text": "<p>Normally I do like this </p>\n\n<pre><code>&lt;div spry:region=\"ds1\" spry:repeatchildren=\"ds1\"&gt;\n &lt;b spry:if=\" '{ds1::title}'!='' &amp;&amp; '{ds1::author}'!=''\"&gt;\n &lt;a href=\"#\"&gt;{author}&lt;/a&gt;\n &lt;/b&gt;\n&lt;/div&gt;\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24439/" ]
``` <div spry:region="ds1" spry:repeatchildren="ds1"> <b spry:if=" '{title}'!='' "> <!-- this is the first if --> <a href="#" spry:if=" '{author}'!='' ">{author} <!-- this is the second if --> </a> </b> </div> ``` I wonder if there is any method as simple as ``` if(x==y && i>j) ``` in ``` <b>spry</b> ``` region. I can't find any information in spry docs (labs.adobe.com/technologies/spry/)
The syntax inside the `spry:if` attribute is Javascript, so you can use `&&`: ``` <b spry:if="'{title}' != '' && '{author}' != ''"> <!-- ... --> </b> ```
178,619
<p>Hi I get an System.InvalidProgramException while trying to run the Example Project called "C# Example.WorkItemBrowser". The Exception also apears when I try to execute these lines:</p> <pre><code>TeamFoundationServer tfserver = new TeamFoundationServer("http://localhost:8085"); tfserver.EnsureAuthenticated(); WorkItemStore store = new WorkItemStore(tfserver); Console.WriteLine(store.Projects.Count); </code></pre> <p>I'm using the 2008 Visual Studio SDK for that.</p> <p>PEverify for the assembly Microsoft.TeamFoundation.WorkItemTracking.Client.dll</p> <p>got this otuput:</p> <pre><code>[MD]: Error: Value class has neither fields nor size parameter. [token:0x020000B3] [MD]: Error: Value class has neither fields nor size parameter. [token:0x020000BF] [MD]: Error: Value class has neither fields nor size parameter. [token:0x020000C4] 3 Error(s) Verifying Microsoft.TeamFoundation.WorkItemTracking.Client.dll </code></pre> <p>A fresh download and install of the SDK as well as deinstall and install as well as installing .net 3.5 sp1 again didn't help.</p> <p>Is something wrong with the description of my problem or did it just not happen anywhere else?</p>
[ { "answer_id": 1015728, "author": "joshua.ewer", "author_id": 28664, "author_profile": "https://Stackoverflow.com/users/28664", "pm_score": 0, "selected": false, "text": "<p>I just a very similar question <a href=\"https://stackoverflow.com/questions/1015648/how-do-i-distribute-a-service-that-uses-the-team-foundation-server-api\">here</a>. </p>\n\n<p>Turns out, you have to have Team Explorer installed on the machine you are executing this code on. Are you deploying this to another machine or trying this on a machine that doesn't have Team Explorer installed on it?</p>\n" }, { "answer_id": 3226474, "author": "Joao Silva", "author_id": 131130, "author_profile": "https://Stackoverflow.com/users/131130", "pm_score": 2, "selected": false, "text": "<p>This solved my problem: <a href=\"http://blogs.msdn.com/b/jianges/archive/2008/03/28/tfs-sdk-will-cause-invalidprogramexception-while-running-as-64-bit.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/b/jianges/archive/2008/03/28/tfs-sdk-will-cause-invalidprogramexception-while-running-as-64-bit.aspx</a></p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1168/" ]
Hi I get an System.InvalidProgramException while trying to run the Example Project called "C# Example.WorkItemBrowser". The Exception also apears when I try to execute these lines: ``` TeamFoundationServer tfserver = new TeamFoundationServer("http://localhost:8085"); tfserver.EnsureAuthenticated(); WorkItemStore store = new WorkItemStore(tfserver); Console.WriteLine(store.Projects.Count); ``` I'm using the 2008 Visual Studio SDK for that. PEverify for the assembly Microsoft.TeamFoundation.WorkItemTracking.Client.dll got this otuput: ``` [MD]: Error: Value class has neither fields nor size parameter. [token:0x020000B3] [MD]: Error: Value class has neither fields nor size parameter. [token:0x020000BF] [MD]: Error: Value class has neither fields nor size parameter. [token:0x020000C4] 3 Error(s) Verifying Microsoft.TeamFoundation.WorkItemTracking.Client.dll ``` A fresh download and install of the SDK as well as deinstall and install as well as installing .net 3.5 sp1 again didn't help. Is something wrong with the description of my problem or did it just not happen anywhere else?
This solved my problem: <http://blogs.msdn.com/b/jianges/archive/2008/03/28/tfs-sdk-will-cause-invalidprogramexception-while-running-as-64-bit.aspx>
178,645
<p>There is some magic going on with WCF deserialization. How does it instantiate an instance of the data contract type without calling its constructor?</p> <p>For example, consider this data contract:</p> <pre><code>[DataContract] public sealed class CreateMe { [DataMember] private readonly string _name; [DataMember] private readonly int _age; private readonly bool _wasConstructorCalled; public CreateMe() { _wasConstructorCalled = true; } // ... other members here } </code></pre> <p>When obtaining an instance of this object via <code>DataContractSerializer</code> you will see that the field <code>_wasConstructorCalled</code> is <code>false</code>.</p> <p>So, how does WCF do this? Is this a technique that others can use too, or is it hidden away from us?</p>
[ { "answer_id": 179486, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 8, "selected": true, "text": "<p><code>FormatterServices.GetUninitializedObject()</code> will create an instance without calling a constructor. I found this class by using <a href=\"http://www.red-gate.com/products/reflector/index.htm\" rel=\"noreferrer\">Reflector</a> and digging through some of the core .Net serialization classes. </p>\n\n<p>I tested it using the sample code below and it looks like it works great:</p>\n\n<pre><code>using System;\nusing System.Reflection;\nusing System.Runtime.Serialization;\n\nnamespace NoConstructorThingy\n{\n class Program\n {\n static void Main()\n {\n // does not call ctor\n var myClass = (MyClass)FormatterServices.GetUninitializedObject(typeof(MyClass));\n\n Console.WriteLine(myClass.One); // writes \"0\", constructor not called\n Console.WriteLine(myClass.Two); // writes \"0\", field initializer not called\n }\n }\n\n public class MyClass\n {\n public MyClass()\n {\n Console.WriteLine(\"MyClass ctor called.\");\n One = 1;\n }\n\n public int One { get; private set; }\n public readonly int Two = 2;\n }\n}\n</code></pre>\n\n<p><a href=\"http://d3j5vwomefv46c.cloudfront.net/photos/large/687556261.png\" rel=\"noreferrer\">http://d3j5vwomefv46c.cloudfront.net/photos/large/687556261.png</a></p>\n" }, { "answer_id": 2568181, "author": "AaronM", "author_id": 307837, "author_profile": "https://Stackoverflow.com/users/307837", "pm_score": 4, "selected": false, "text": "<p>Yes, FormatterServices.GetUninitializedObject() is the source of the magic.</p>\n\n<p>If you want to do any special initialization, see this.\n<a href=\"http://blogs.msdn.com/drnick/archive/2007/11/19/serialization-and-types.aspx\" rel=\"noreferrer\">http://blogs.msdn.com/drnick/archive/2007/11/19/serialization-and-types.aspx</a></p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24874/" ]
There is some magic going on with WCF deserialization. How does it instantiate an instance of the data contract type without calling its constructor? For example, consider this data contract: ``` [DataContract] public sealed class CreateMe { [DataMember] private readonly string _name; [DataMember] private readonly int _age; private readonly bool _wasConstructorCalled; public CreateMe() { _wasConstructorCalled = true; } // ... other members here } ``` When obtaining an instance of this object via `DataContractSerializer` you will see that the field `_wasConstructorCalled` is `false`. So, how does WCF do this? Is this a technique that others can use too, or is it hidden away from us?
`FormatterServices.GetUninitializedObject()` will create an instance without calling a constructor. I found this class by using [Reflector](http://www.red-gate.com/products/reflector/index.htm) and digging through some of the core .Net serialization classes. I tested it using the sample code below and it looks like it works great: ``` using System; using System.Reflection; using System.Runtime.Serialization; namespace NoConstructorThingy { class Program { static void Main() { // does not call ctor var myClass = (MyClass)FormatterServices.GetUninitializedObject(typeof(MyClass)); Console.WriteLine(myClass.One); // writes "0", constructor not called Console.WriteLine(myClass.Two); // writes "0", field initializer not called } } public class MyClass { public MyClass() { Console.WriteLine("MyClass ctor called."); One = 1; } public int One { get; private set; } public readonly int Two = 2; } } ``` <http://d3j5vwomefv46c.cloudfront.net/photos/large/687556261.png>
178,667
<p>I have the following code:</p> <pre><code>import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.ScrollPaneConstants; public class ScratchPad { public static void main(String args[]) throws Exception { String html ="&lt;html&gt;"+ "&lt;head&gt;"+ "&lt;meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"/&gt;"+ // this is the problem right here "&lt;title&gt;Error 400 BAD_REQUEST&lt;/title&gt;"+ "&lt;/head&gt;"+ "&lt;body&gt;"+ "&lt;h2&gt;HTTP ERROR: 400&lt;/h2&gt;&lt;pre&gt;BAD_REQUEST&lt;/pre&gt;"+ "&lt;p&gt;RequestURI=null&lt;/p&gt;"+ "&lt;p&gt;&lt;i&gt;&lt;small&gt;&lt;a href=\"http://jetty.mortbay.org\"&gt;Powered by jetty://&lt;/a&gt;&lt;/small&gt;&lt;/i&gt;&lt;/p&gt;"+ "&lt;/body&gt;"+ "&lt;/html&gt;"; JFrame f = new JFrame(); JEditorPane editor = new JEditorPane(); editor.setEditable( false ); editor.getDocument().putProperty( "Ignore-Charset", "true" ); // this line makes no difference either way editor.setContentType( "text/html" ); editor.setText( html ); f.add( new JScrollPane(editor, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) ); f.pack(); f.setVisible( true ); } } </code></pre> <p>If you run it, you'll notice the frame is blank. However, if I remove the "; charset=ISO-8859-1" from the meta tag, the HTML shows up. Any ideas why and what I can do to prevent this (other than manually hacking the HTML string over which I have no control...).</p> <p><strong>Edit #1</strong> - putProperty( "Ignore-Charset", "true" ) makes no difference unfortunately.</p>
[ { "answer_id": 270105, "author": "micro", "author_id": 23275, "author_profile": "https://Stackoverflow.com/users/23275", "pm_score": 1, "selected": false, "text": "<p>When I run the code, I can only see the HTML text when I delete the <strong><em>meta</em></strong> line. Maybe it has something to do with character settings of the system it runs on.</p>\n" }, { "answer_id": 1421097, "author": "Horcrux7", "author_id": 12631, "author_profile": "https://Stackoverflow.com/users/12631", "pm_score": 5, "selected": true, "text": "<p>Use the follow line before setText and after setContentType.</p>\n\n<pre><code>editor.getDocument().putProperty(\"IgnoreCharsetDirective\", Boolean.TRUE);\n</code></pre>\n\n<p>This is one of the mystic undocumented features. setContentType create a new Document that it has no effect if you set it before.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
I have the following code: ``` import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.ScrollPaneConstants; public class ScratchPad { public static void main(String args[]) throws Exception { String html ="<html>"+ "<head>"+ "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=ISO-8859-1\"/>"+ // this is the problem right here "<title>Error 400 BAD_REQUEST</title>"+ "</head>"+ "<body>"+ "<h2>HTTP ERROR: 400</h2><pre>BAD_REQUEST</pre>"+ "<p>RequestURI=null</p>"+ "<p><i><small><a href=\"http://jetty.mortbay.org\">Powered by jetty://</a></small></i></p>"+ "</body>"+ "</html>"; JFrame f = new JFrame(); JEditorPane editor = new JEditorPane(); editor.setEditable( false ); editor.getDocument().putProperty( "Ignore-Charset", "true" ); // this line makes no difference either way editor.setContentType( "text/html" ); editor.setText( html ); f.add( new JScrollPane(editor, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER) ); f.pack(); f.setVisible( true ); } } ``` If you run it, you'll notice the frame is blank. However, if I remove the "; charset=ISO-8859-1" from the meta tag, the HTML shows up. Any ideas why and what I can do to prevent this (other than manually hacking the HTML string over which I have no control...). **Edit #1** - putProperty( "Ignore-Charset", "true" ) makes no difference unfortunately.
Use the follow line before setText and after setContentType. ``` editor.getDocument().putProperty("IgnoreCharsetDirective", Boolean.TRUE); ``` This is one of the mystic undocumented features. setContentType create a new Document that it has no effect if you set it before.
178,669
<p>How can i make my flash applications in a browser in full screen mode? I know that the stage can be put in that mode, but when i run the application in any browser this doesn't work. So, this can be done, but how?</p>
[ { "answer_id": 178709, "author": "John Chuckran", "author_id": 25511, "author_profile": "https://Stackoverflow.com/users/25511", "pm_score": -1, "selected": false, "text": "<p>I believe it is a simple actionscript command. <a href=\"http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary372.html\" rel=\"nofollow noreferrer\" title=\"Source\">Source</a></p>\n\n<pre><code> fscommand( \"fullscreen\" , \"true\" ) \n</code></pre>\n" }, { "answer_id": 178892, "author": "Raleigh Buckner", "author_id": 1153, "author_profile": "https://Stackoverflow.com/users/1153", "pm_score": 5, "selected": true, "text": "<p>In the HTML including the Flash SWF, add the following parameter to your &lt;object&gt; tag:</p>\n\n<pre><code>&lt;param name=\"allowFullScreen\" value=\"true\" /&gt;\n</code></pre>\n\n<p>and the following attribute to your &lt;embed&gt; tag:</p>\n\n<pre><code>allowFullScreen=\"true\"\n</code></pre>\n\n<p>Or, if you are using <a href=\"http://code.google.com/p/swfobject/\" rel=\"nofollow noreferrer\">SWFObject</a> (as you should be), add the allowFullscreen parameter to your embed code. See the <a href=\"http://code.google.com/p/swfobject/wiki/documentation\" rel=\"nofollow noreferrer\">SWFObject documentation</a> for the various ways to this.</p>\n\n<p>In your Flash/Flex file, you need to provide the user a way to initiate fullscreen mode - <strong>you cannot force fullscreen without the user initiating it</strong>. Whatever you have the user do, include this code as a response to it:</p>\n\n<pre><code>stage.displayState = StageDisplayState.FULL_SCREEN; //Flash\nsystemManager.stage.displayState = StageDisplayState.FULL_SCREEN; // Flex\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20601/" ]
How can i make my flash applications in a browser in full screen mode? I know that the stage can be put in that mode, but when i run the application in any browser this doesn't work. So, this can be done, but how?
In the HTML including the Flash SWF, add the following parameter to your <object> tag: ``` <param name="allowFullScreen" value="true" /> ``` and the following attribute to your <embed> tag: ``` allowFullScreen="true" ``` Or, if you are using [SWFObject](http://code.google.com/p/swfobject/) (as you should be), add the allowFullscreen parameter to your embed code. See the [SWFObject documentation](http://code.google.com/p/swfobject/wiki/documentation) for the various ways to this. In your Flash/Flex file, you need to provide the user a way to initiate fullscreen mode - **you cannot force fullscreen without the user initiating it**. Whatever you have the user do, include this code as a response to it: ``` stage.displayState = StageDisplayState.FULL_SCREEN; //Flash systemManager.stage.displayState = StageDisplayState.FULL_SCREEN; // Flex ```
178,675
<p>Is it possible to split large ASP.NET-pages into pieces? JSP has the <a href="http://java.sun.com/products/jsp/tags/11/syntaxref1112.html" rel="nofollow noreferrer">jsp:include</a> directive. Is there any equivivalent in ASP.NET</p> <p>I'm not interested in reusing the pieces. I just want to organize the HTML/ASP code.</p> <p>Isn't User Controls and Master Pages overkill for doing this?</p>
[ { "answer_id": 178682, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/wtxbf3hh.aspx\" rel=\"noreferrer\">MasterPage model</a> and <a href=\"http://msdn.microsoft.com/en-us/library/y6wb1a0e.aspx\" rel=\"noreferrer\">UserControls</a> are the two out-of-box solutions to this. </p>\n" }, { "answer_id": 178697, "author": "Ryan", "author_id": 17917, "author_profile": "https://Stackoverflow.com/users/17917", "pm_score": 2, "selected": false, "text": "<p>If it's only ASP.net, then User Controls are an excellent way of splitting up pages and reusing code, as John Rudy suggests. </p>\n\n<p>If any of your user controls use Javascript, one big gotcha to watch out for is to use the <a href=\"http://blogs.telerik.com/AtanasKorchev/Posts/08-06-06/The_difference_between_ID_ClientID_and_UniqueID.aspx\" rel=\"nofollow noreferrer\">ClientID</a> to refer to that control. When you add a user control to a page, ASP.NET mangles the ID to prevent collisions. The client ID is guaranteed unique. </p>\n" }, { "answer_id": 178703, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 0, "selected": false, "text": "<p>You should take a look at ASP.NET User Controls which allow you to encapsulate UI functionality into smaller more manageable chunks.</p>\n\n<p><a href=\"http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/userctrl/default.aspx\" rel=\"nofollow noreferrer\">http://quickstarts.asp.net/QuickStartv20/aspnet/doc/ctrlref/userctrl/default.aspx</a></p>\n" }, { "answer_id": 178724, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 0, "selected": false, "text": "<p>If you are talking about specific pages (as opposed to User Controls which are more intended for multi-page reuse than anything else), you could also use <a href=\"http://msdn.microsoft.com/en-us/library/wa80x488(VS.80).aspx\" rel=\"nofollow noreferrer\">Partial Classes</a>. </p>\n\n<p>AFAIK in ASP.NET 2.0 and above ASPX pages are already Partial Classes by default (with all control declaration in the designer.aspx file).</p>\n" }, { "answer_id": 178779, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 3, "selected": true, "text": "<pre><code>&lt;!--#include file=\"inc_footer.aspx\"--&gt;\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25833/" ]
Is it possible to split large ASP.NET-pages into pieces? JSP has the [jsp:include](http://java.sun.com/products/jsp/tags/11/syntaxref1112.html) directive. Is there any equivivalent in ASP.NET I'm not interested in reusing the pieces. I just want to organize the HTML/ASP code. Isn't User Controls and Master Pages overkill for doing this?
``` <!--#include file="inc_footer.aspx"--> ```
178,696
<p>I've got the following JavaScript on my web page...</p> <pre><code>64 var description = new Array(); 65 description[0] = "..." 66 description[1] = "..." ... 78 function init() { 79 document.getElementById('somedivid').innerHTML = description[0]; 80 } 81 82 window.onload = init(); </code></pre> <p>In Microsoft Internet Explorer it causes the following error...</p> <blockquote> <p>A Runtime Error has occurred.<br> Do you wish to debug?</p> <p>Line: 81<br> Error: Not implemented</p> </blockquote> <p><img src="https://i.stack.imgur.com/n06sz.gif" alt="javascript runtime error"></p> <p>Line 79 executes as expected.</p> <p>If line 79 is commented out, it still throws the error.</p> <p>If I comment out line 82, then the function does not execute and there is no error.</p>
[ { "answer_id": 178719, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "<p>Try to add an envent listener for 'load' instead, or use the declarative syntax <code>&lt;body onload=\"init()\"&gt;</code>.</p>\n\n<p>EDIT: Additionally, saying <code>window.onload = init();</code> sets window.onload to the result of calling <code>init()</code>. What you mean is <code>window.onload = init;</code> (a lambda expression). This is bad practice still, as it overwrites other things that might be bound to <code>window.onload</code>.</p>\n" }, { "answer_id": 178727, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 5, "selected": true, "text": "<p>Shouldn't line 82 read:</p>\n\n<pre><code>window.onload = init;\n</code></pre>\n\n<p>When you do \"init()\" it's a call to a function that returns void. You end up calling that function before the page loads.</p>\n" }, { "answer_id": 178742, "author": "J c", "author_id": 25837, "author_profile": "https://Stackoverflow.com/users/25837", "pm_score": 0, "selected": false, "text": "<p>In addition to the onload fixes proposed here, also check to see if there are multiple elements with that ID, I believe IE will return a collection of all elements with that ID, in which case you would need to select the intended item out of the collection before accessing that property or ensure you are using unique IDs.</p>\n" }, { "answer_id": 178765, "author": "Jacob", "author_id": 8119, "author_profile": "https://Stackoverflow.com/users/8119", "pm_score": 2, "selected": false, "text": "<p>To preserve any previously set onload functions try this</p>\n\n<pre><code>var prevload = window.onload;\nwindow.onload = function(){\n prevload();\n init();\n}\n</code></pre>\n" }, { "answer_id": 178769, "author": "edosoft", "author_id": 6399, "author_profile": "https://Stackoverflow.com/users/6399", "pm_score": 0, "selected": false, "text": "<p>Try running it in FireFox with the <a href=\"https://addons.mozilla.org/en-US/firefox/addon/1843\" rel=\"nofollow noreferrer\">FireBug</a> plugin enabled. This will allow you to debug the javascript</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/83/" ]
I've got the following JavaScript on my web page... ``` 64 var description = new Array(); 65 description[0] = "..." 66 description[1] = "..." ... 78 function init() { 79 document.getElementById('somedivid').innerHTML = description[0]; 80 } 81 82 window.onload = init(); ``` In Microsoft Internet Explorer it causes the following error... > > A Runtime Error has occurred. > > Do you wish to debug? > > > Line: 81 > > Error: Not implemented > > > ![javascript runtime error](https://i.stack.imgur.com/n06sz.gif) Line 79 executes as expected. If line 79 is commented out, it still throws the error. If I comment out line 82, then the function does not execute and there is no error.
Shouldn't line 82 read: ``` window.onload = init; ``` When you do "init()" it's a call to a function that returns void. You end up calling that function before the page loads.
178,700
<p>While simple, interface-driven event notification frameworks in Java have been around since pre-Cambrian times (e.g. java.beans.PropertyChangeSupport), it is becoming increasingly popular for frameworks to use annotation-driven event notification instead. </p> <p>For an example, see <a href="http://www.jboss.org/file-access/default/members/jbosscache/freezone/docs/2.2.0.GA/userguide_en/html_single/index.html#api.listener" rel="noreferrer">JBossCache 2.2</a>. The listener class has its listener methods annotated, rather than conforming to a rigid interface. This is rather easier to program to, and easier to read, since you don't have to write empty implementations of listener callbacks that you're not interested in (and yes, I know about listener adapter superclasses).</p> <p>Here's a sample from the JBossCache docs:</p> <pre><code>@CacheListener public class MyListener { @CacheStarted @CacheStopped public void cacheStartStopEvent(Event e) { switch (e.getType()) { case Event.Type.CACHE_STARTED: System.out.println("Cache has started"); break; case Event.Type.CACHE_STOPPED: System.out.println("Cache has stopped"); break; } } @NodeCreated @NodeRemoved @NodeVisited @NodeModified @NodeMoved public void logNodeEvent(NodeEvent ne) { log("An event on node " + ne.getFqn() + " has occured"); } </code></pre> <p>}</p> <p>The problem with this, is that it's very much more of an involved process writing the framework to support this sort of thing, due to the annotation-reflection nature of it.</p> <p>So, before I charge off down the road of writing a generic framework, I was hoping someone had done it already. Has anyone come across such a thing?</p>
[ { "answer_id": 179056, "author": "oxbow_lakes", "author_id": 16853, "author_profile": "https://Stackoverflow.com/users/16853", "pm_score": 2, "selected": false, "text": "<p>Don't mistake complicated for clever. It seems to me that this would be:</p>\n\n<ol>\n<li>A nightmare to debug</li>\n<li>Difficult to follow (from a maintenance perspective, or someone attempting to change something 6 months down the line)</li>\n<li>Full of <code>if (event instanceof NodeCreatedEvent)</code> like code. Why this is better than subclassing an <code>adapter</code> I have no idea!</li>\n</ol>\n" }, { "answer_id": 179156, "author": "Scott Stanchfield", "author_id": 12541, "author_profile": "https://Stackoverflow.com/users/12541", "pm_score": 2, "selected": false, "text": "<p>The main problem I see here are the method parameters, which restrict which methods can actually be used for which events, and there's no compile-time help for that.</p>\n\n<p>This is what makes interfaces attractive to me for observer pattern implementations like the Java event model. Tools like eclipse can autogen method stubs so you can't get the signatures wrong. In your example, it's very easy to use the wrong parameter type and never know it until an event occurs (which might be an error case several months down the line) </p>\n\n<p>One thing you might try are my annotations &amp; processor for implementing observers and null object implementations. Suppose you have</p>\n\n<pre><code>package a.b.c;\n\npublic interface SomeListener {\n void fee();\n void fie();\n void fo();\n void fum();\n}\n</code></pre>\n\n<p>and wanted to create a listener instance. You could write</p>\n\n<pre><code>package x.y.z;\n\nimport a.b.c.SomeListener;\nimport com.javadude.annotation.Bean;\nimport com.javadude.annotation.NullObject;\n\n@Bean(nullObjectImplementations = {@NullObject(type = SomeListener.class) })\npublic class Foo extends FooGen implements SomeListener {\n @Override\n public void fie() {\n // whatever code you need here\n }\n}\n</code></pre>\n\n<p>To create a source for these events, you can write</p>\n\n<pre><code>package a.b.c;\n\nimport com.javadude.annotation.Bean;\nimport com.javadude.annotation.Observer;\n\n@Bean(observers = {@Observer(type = SomeListener.class)})\npublic class Source extends SourceGen {\n // SourceGen will have add/remove listener and fire methods\n // for each method in SomeListener\n}\n</code></pre>\n\n<p>See <a href=\"http://code.google.com/p/javadude/wiki/Annotations\" rel=\"nofollow noreferrer\">http://code.google.com/p/javadude/wiki/Annotations</a> if you're interested. Might give you some other ideas as well.</p>\n" }, { "answer_id": 857223, "author": "Jim Hurne", "author_id": 106189, "author_profile": "https://Stackoverflow.com/users/106189", "pm_score": 1, "selected": false, "text": "<p>I've been thinking about a generic annotation-driven event framework as well. I like the benefits provided by static typing, but the current interface-driven event model is painful to use (ugly code). Would it be possible to use a custom annotation processor to do some compile-time checking? That might help add some of the missing \"safety\" that we've all grown used to.</p>\n\n<p>A lot of the error checking can also be done at the time that the listeners are \"registered\" with the event producers. Thus, the application would fail early (when the listeners are registered), possibly even at at startup-time.</p>\n\n<p>Here's an example of what the generic framework I've been toying with might look like:</p>\n\n<pre><code>public class ExampleProducer {\n\n private EventSupport&lt;ActionEvent&gt; eventSupport;\n\n public ExampleProducer() {\n eventSupport = new EventSupport&lt;ActionEvent&gt;(this);\n }\n\n @AddListenersFor(ActionEvent.class)\n public void addActionListener(Object listener)\n {\n eventSupport.addListener(listener);\n }\n\n @RemoveListenersFor(ActionEvent.class)\n public void removeActionListener(Object listener)\n {\n eventSupport.removeListener(listener);\n }\n\n public void buttonClicked() {\n eventSupport.fire(new ActionEvent(this, \n ActionEvent.ACTION_PERFORMED, \"Click\"));\n }\n }\n</code></pre>\n\n<p>The producer uses <code>EventSupport</code>, which uses reflection to invoke the events. As mentioned before, <code>EventSupport</code> could preform some initial checks when the events listeners are registered.</p>\n\n<pre><code>public class ExampleListener\n{ \n private ExampleProducer submitButton;\n\n public ExampleListener()\n {\n submitButton = new ExampleProducer();\n EventSupport.autoRegisterEvents(this);\n }\n\n @HandlesEventFor(\"submitButton\")\n public void handleSubmitButtonClick(ActionEvent event)\n {\n //...some code to handle the event here\n }\n}\n</code></pre>\n\n<p>Here, <code>EventSupport</code> has a static method that uses reflection to auto-register the listener with the event producer. This eliminates the need to manually register with the event source. A custom annotation processor could be used to validate that the <code>@HandlesEventFor</code> annotation refers to an actual field of the <code>ExampleListener</code>. The annotation processor could do other checks as well, such as ensuring that the event handler method signature matches up with one of the registration methods on the <code>ExampleProducer</code> (basically, the same check that could be performed at registration-time).</p>\n\n<p>What do you think? Is this worth putting some time into fully developing?</p>\n" }, { "answer_id": 1980181, "author": "Hendy Irawan", "author_id": 122441, "author_profile": "https://Stackoverflow.com/users/122441", "pm_score": 4, "selected": true, "text": "<p>You can already do this today with <a href=\"http://eventbus.org\" rel=\"noreferrer\" title=\"EventBus\">EventBus</a>.</p>\n\n<p>Following example is from <a href=\"http://eventbus.org/confluence/display/EventBus/Getting+Started\" rel=\"noreferrer\">EventBus Getting Started guide</a>. Statusbar that updates based on published events, and no need to register statusbar control/widget as listener of publisher(s). Without EventBus, statusbar will need to be added as listener to many classes. Statusbar can also be created and destroyed at any time.</p>\n\n<pre><code>public StatusBar extends JLabel {\n public StatusBar() {\n AnnotationProcessor.process(this);\n }\n @EventSubscriber(eventClass=StatusEvent.class)\n public void updateStatus(StatusEvent statusEvent) {\n this.setText(statusEvent.getStatusText();\n }\n}\n</code></pre>\n\n<p>A similar project is <a href=\"https://elf.dev.java.net/\" rel=\"noreferrer\">ELF (Event Listener Framework)</a> but it seems to be less mature.</p>\n\n<p>I'm currently researching about event notification frameworks on <a href=\"http://spring-java-ee.blogspot.com/2009/12/publish-subscribe-event-driven.html\" rel=\"noreferrer\">Publish-Subscribe Event Driven Programming | Kev's Spring vs Java EE Dev</a> and the followup articles.</p>\n" }, { "answer_id": 2039003, "author": "eric", "author_id": 222289, "author_profile": "https://Stackoverflow.com/users/222289", "pm_score": 2, "selected": false, "text": "<p>I've made <a href=\"http://neoevents.googlecode.com\" rel=\"nofollow noreferrer\">http://neoevents.googlecode.com</a> to handle this kind of annotation based event handler.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@actionPerformed\nprivate void onClick() {\n //do something\n}\n\nprotected void initComponents() {\n JButton button = new JButton(\"Click me!!!\");\n button.addActionListener(new ActionListener(this) );\n}\n</code></pre>\n\n<p>It looks as simple as I was expecting it to be. Annotations are available for every single listener in J2SE.</p>\n" }, { "answer_id": 2759614, "author": "Nitramz", "author_id": 319643, "author_profile": "https://Stackoverflow.com/users/319643", "pm_score": 1, "selected": false, "text": "<p>Here's a similar project called <a href=\"http://code.google.com/p/sjes/\" rel=\"nofollow noreferrer\">SJES</a>.</p>\n\n<pre><code>public class SomeController {\n\nprivate Calculator c1 = new Calculator();\nprivate Calculator c2 = new Calculator();\n\npublic SomeController() {\n c1.registerReceiver(this);\n c2.registerReceiver(this);\n c1.add(10, 10);\n c2.add(20, 20);\n}\n\n@EventReceiver(handleFor=\"c1\")\npublic void onResultC1(Calculator.Event e) {\n System.out.println(\"Calculator 1 got: \" + e.result);\n}\n\n@EventReceiver(handleFor=\"c2\")\npublic void onResultC2(Calculator.Event e) {\n System.out.println(\"Calculator 2 got: \" + e.result);\n}\n\n@EventReceiver\npublic void onResultAll(Calculator.Event e) {\n System.out.println(\"Calculator got: \" + e.result);\n}\n}\n\npublic class Calculator {\n\nprivate EventHelper eventHelper = new EventHelper(this);\n\npublic class Event {\n\n long result;\n\n public Event(long result) {\n this.result = result;\n }\n}\n\npublic class AddEvent extends Event {\n\n public AddEvent(long result) {\n super(result);\n }\n}\n\npublic class SubEvent extends Event {\n\n public SubEvent(long result) {\n super(result);\n }\n}\n\npublic void unregisterReceiver(Object o) {\n eventHelper.unregisterReceiver(o);\n}\n\npublic void registerReceiver(Object o) {\n eventHelper.registerReceiver(o);\n}\n\npublic void add(long a, long b) {\n eventHelper.fireEvent(new AddEvent(a + b));\n}\n\npublic void sub(long a, long b) {\n eventHelper.fireEvent(new SubEvent(a - b));\n}\n\npublic void pass(long a) {\n eventHelper.fireEvent(new Event(a));\n}\n}\n</code></pre>\n\n<p>I think this is very easy to use.</p>\n" }, { "answer_id": 8985987, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://code.google.com/p/guava-libraries/\" rel=\"nofollow\">Google Guava v11</a> has added an <a href=\"http://code.google.com/p/guava-libraries/wiki/EventBusExplained\" rel=\"nofollow\">EventBus component that uses this style</a>. They also <a href=\"http://code.google.com/p/guava-libraries/wiki/EventBusExplained#Why_use_an_annotation_to_mark_handler_methods,_rather_than_requi\" rel=\"nofollow\">explain why they decided to use annotations rather than interfaces</a>.</p>\n" }, { "answer_id": 13027513, "author": "bennidi", "author_id": 1047493, "author_profile": "https://Stackoverflow.com/users/1047493", "pm_score": 0, "selected": false, "text": "<p>You can also check out <a href=\"https://github.com/bennidi/mbassador\" rel=\"nofollow\">MBassador</a> It is annotation driven, very light-weight and uses weak references (thus easy to integrate in environments where objects lifecycle management is done by a framework like spring or guice or somethign). </p>\n\n<p>It provides an object filtering mechanism (thus you could subscribe to NodeEvent and attach some filters to restrict message handling to a set of specific types only). \nYou can also define your own annotations to have customized declaration of your handlers.</p>\n\n<p>And it's very fast and resource efficient. Check out this <a href=\"https://github.com/bennidi/eventbus-performance\" rel=\"nofollow\">benchmark</a> showing a performance graph for different scenarios using Guava or mbassador.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21234/" ]
While simple, interface-driven event notification frameworks in Java have been around since pre-Cambrian times (e.g. java.beans.PropertyChangeSupport), it is becoming increasingly popular for frameworks to use annotation-driven event notification instead. For an example, see [JBossCache 2.2](http://www.jboss.org/file-access/default/members/jbosscache/freezone/docs/2.2.0.GA/userguide_en/html_single/index.html#api.listener). The listener class has its listener methods annotated, rather than conforming to a rigid interface. This is rather easier to program to, and easier to read, since you don't have to write empty implementations of listener callbacks that you're not interested in (and yes, I know about listener adapter superclasses). Here's a sample from the JBossCache docs: ``` @CacheListener public class MyListener { @CacheStarted @CacheStopped public void cacheStartStopEvent(Event e) { switch (e.getType()) { case Event.Type.CACHE_STARTED: System.out.println("Cache has started"); break; case Event.Type.CACHE_STOPPED: System.out.println("Cache has stopped"); break; } } @NodeCreated @NodeRemoved @NodeVisited @NodeModified @NodeMoved public void logNodeEvent(NodeEvent ne) { log("An event on node " + ne.getFqn() + " has occured"); } ``` } The problem with this, is that it's very much more of an involved process writing the framework to support this sort of thing, due to the annotation-reflection nature of it. So, before I charge off down the road of writing a generic framework, I was hoping someone had done it already. Has anyone come across such a thing?
You can already do this today with [EventBus](http://eventbus.org "EventBus"). Following example is from [EventBus Getting Started guide](http://eventbus.org/confluence/display/EventBus/Getting+Started). Statusbar that updates based on published events, and no need to register statusbar control/widget as listener of publisher(s). Without EventBus, statusbar will need to be added as listener to many classes. Statusbar can also be created and destroyed at any time. ``` public StatusBar extends JLabel { public StatusBar() { AnnotationProcessor.process(this); } @EventSubscriber(eventClass=StatusEvent.class) public void updateStatus(StatusEvent statusEvent) { this.setText(statusEvent.getStatusText(); } } ``` A similar project is [ELF (Event Listener Framework)](https://elf.dev.java.net/) but it seems to be less mature. I'm currently researching about event notification frameworks on [Publish-Subscribe Event Driven Programming | Kev's Spring vs Java EE Dev](http://spring-java-ee.blogspot.com/2009/12/publish-subscribe-event-driven.html) and the followup articles.
178,712
<p>I am reading an XML file into a DataSet and need to get the data out of the DataSet. Since it is a user-editable config file the fields may or may not be there. To handle missing fields well I'd like to make sure each column in the DataRow exists and is not DBNull. </p> <p>I already check for DBNull but I don't know how to make sure the column exists without having it throw an exception or using a function that loops over all the column names. What is the best method to do this?</p>
[ { "answer_id": 178725, "author": "Anders", "author_id": 25515, "author_profile": "https://Stackoverflow.com/users/25515", "pm_score": -1, "selected": false, "text": "<p>You can encapsulate your block of code with a try ... catch statement, and when you run your code, if the column doesn't exist it will throw an exception. You can then figure out what specific exception it throws and have it handle that specific exception in a different way if you so desire, such as returning \"Column Not Found\".</p>\n" }, { "answer_id": 178755, "author": "Phillip Wells", "author_id": 3012, "author_profile": "https://Stackoverflow.com/users/3012", "pm_score": 5, "selected": false, "text": "<p>You can use <code>DataSet.Tables(0).Columns.Contains(name)</code> to check whether the <code>DataTable</code> contains a column with a particular name.</p>\n" }, { "answer_id": 178766, "author": "John Chuckran", "author_id": 25511, "author_profile": "https://Stackoverflow.com/users/25511", "pm_score": 8, "selected": true, "text": "<p>DataRow's are nice in the way that they have their underlying table linked to them. With the underlying table you can verify that a specific row has a specific column in it.</p>\n\n<pre><code> If DataRow.Table.Columns.Contains(\"column\") Then\n MsgBox(\"YAY\")\n End If\n</code></pre>\n" }, { "answer_id": 34077498, "author": "Alexander Abakumov", "author_id": 3345644, "author_profile": "https://Stackoverflow.com/users/3345644", "pm_score": 2, "selected": false, "text": "<p>Another way to find out if a column exists is to check for <code>Nothing</code> the value returned from the <code>Columns</code> collection indexer when passing the column name to it:</p>\n\n<pre><code>If dataRow.Table.Columns(\"ColumnName\") IsNot Nothing Then\n MsgBox(\"YAY\")\nEnd If\n</code></pre>\n\n<p>This approach might be preferred over the one that uses the <code>Contains(\"ColumnName\")</code> method when the following code will subsequently need to get that <code>DataColumn</code> for further usage. For example, you may want to know which type has a value stored in the column:</p>\n\n<pre><code>Dim column = DataRow.Table.Columns(\"ColumnName\")\nIf column IsNot Nothing Then\n Dim type = column.DataType\nEnd If\n</code></pre>\n\n<p>In this case this approach saves you a call to the <code>Contains(\"ColumnName\")</code> at the same time making your code a bit cleaner.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21186/" ]
I am reading an XML file into a DataSet and need to get the data out of the DataSet. Since it is a user-editable config file the fields may or may not be there. To handle missing fields well I'd like to make sure each column in the DataRow exists and is not DBNull. I already check for DBNull but I don't know how to make sure the column exists without having it throw an exception or using a function that loops over all the column names. What is the best method to do this?
DataRow's are nice in the way that they have their underlying table linked to them. With the underlying table you can verify that a specific row has a specific column in it. ``` If DataRow.Table.Columns.Contains("column") Then MsgBox("YAY") End If ```
178,730
<p>I have to lock user accounts in Active Directory programmatically in C#. </p> <p>Unfortunately it doesn't work via the userAccountControl attribute. Every time I set userAccountControl to 528 (=normal account w/ lockout flag), Active Directory won't accept the value and resets it without further notice to 512 (=normal account).</p> <p>Now I tried to lock the account by providing incorrect credentials (see below), but this doesn't work either.</p> <pre><code>int retries = 0; while (!adsUser.IsAccountLocked &amp;&amp; retries &lt; MAX_LOCK_RETRIES) { retries++; try { new DirectoryEntry(userPath, logonName, incorrectPassword).RefreshCache(); } catch (Exception) { /* ... */ } adsUser.GetInfo(); } </code></pre> <p>Any ideas?</p>
[ { "answer_id": 178768, "author": "Nick DeVore", "author_id": 1380, "author_profile": "https://Stackoverflow.com/users/1380", "pm_score": 3, "selected": true, "text": "<p>Make sure the account you're using to disable the account has sufficient privileges to disable accounts. See <a href=\"http://msdn.microsoft.com/en-us/library/ms696026(VS.85).aspx\" rel=\"nofollow noreferrer\">this example</a> from Microsoft.</p>\n" }, { "answer_id": 6389998, "author": "Robert Seitz", "author_id": 803729, "author_profile": "https://Stackoverflow.com/users/803729", "pm_score": 0, "selected": false, "text": "<p>This will work once you have the directory entry object.</p>\n\n<pre><code>DirectoryEntry de = result.GetDirectoryEntry();\nint val = (int)de.Properties[\"userAccountControl\"].Value;\nde.Properties[\"userAccountControl\"].Value = val | 0x0002;\n</code></pre>\n" }, { "answer_id": 7930946, "author": "user489041", "author_id": 489041, "author_profile": "https://Stackoverflow.com/users/489041", "pm_score": 2, "selected": false, "text": "<p>This code will work to lock a user in AD</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Locks a user account\n/// &lt;/summary&gt;\n/// &lt;param name=\"userName\"&gt;The name of the user whose account you want to unlock&lt;/param&gt;\n/// &lt;remarks&gt;\n/// This actually trys to log the user in with a wrong password. \n/// This in turn will lock the user out\n/// &lt;/remarks&gt;\npublic void LockAccount(string userName)\n{\n DirectoryEntry user = GetUser(userName);\n string path = user.Path;\n string badPassword = \"SomeBadPassword\";\n int maxLoginAttempts = 10;\n\n for (int i = 0; i &amp;lt maxLoginAttempts; i++)\n {\n try\n {\n new DirectoryEntry(path, userName, badPassword).RefreshCache();\n }\n catch (Exception e)\n {\n\n }\n }\n user.Close();\n}\n</code></pre>\n" }, { "answer_id": 28565650, "author": "obsoleter", "author_id": 982237, "author_profile": "https://Stackoverflow.com/users/982237", "pm_score": 1, "selected": false, "text": "<p>Depending on your Active Directory policies, interactive login attempts may be required to lock an account. You can simulate those using the <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa378184%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\"><code>LogonUser</code> method of advapi32.dll</a>. In my tests, I have seen that running this loop 100 times does not guarantee 100 bad password attempts at the domain controller, so you should <a href=\"https://stackoverflow.com/a/12992684/982237\">check the user is locked out</a> and make more attempts if necessary.</p>\n\n<p>The bottom line for this is that you should be disabling the account instead of trying to lock it. There is <a href=\"http://www.windows-active-directory.com/difference-between-disabled-expired-and-locked-account.html\" rel=\"nofollow noreferrer\">no functional difference between locked and disabled accounts</a>. The code below is a hack.</p>\n\n<pre><code>using System;\nusing System.Runtime.InteropServices;\n\nnamespace Test\n{\n class Program\n {\n static void Main(string[] args)\n {\n IntPtr token = IntPtr.Zero;\n string userPrincipalName = \"[email protected]\";\n string authority = null; // Can be null when using UPN (user principal name)\n string badPassword = \"bad\";\n\n int maxTries = 100;\n bool res = false;\n\n for (var i = 0; i &lt; maxTries; i++)\n {\n res = LogonUser(userPrincipalName, authority, badPassword, LogonSessionType.Interactive, LogonProvider.Default, out token);\n CloseHandle(token);\n }\n }\n\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n static extern bool LogonUser(\n string principal,\n string authority,\n string password,\n LogonSessionType logonType,\n LogonProvider logonProvider,\n out IntPtr token);\n\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n static extern bool CloseHandle(IntPtr handle);\n enum LogonSessionType : uint\n {\n Interactive = 2,\n Network,\n Batch,\n Service,\n NetworkCleartext = 8,\n NewCredentials\n }\n\n enum LogonProvider : uint\n {\n Default = 0, // default for platform (use this!)\n WinNT35, // sends smoke signals to authority\n WinNT40, // uses NTLM\n WinNT50 // negotiates Kerb or NTLM\n }\n }\n}\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/830/" ]
I have to lock user accounts in Active Directory programmatically in C#. Unfortunately it doesn't work via the userAccountControl attribute. Every time I set userAccountControl to 528 (=normal account w/ lockout flag), Active Directory won't accept the value and resets it without further notice to 512 (=normal account). Now I tried to lock the account by providing incorrect credentials (see below), but this doesn't work either. ``` int retries = 0; while (!adsUser.IsAccountLocked && retries < MAX_LOCK_RETRIES) { retries++; try { new DirectoryEntry(userPath, logonName, incorrectPassword).RefreshCache(); } catch (Exception) { /* ... */ } adsUser.GetInfo(); } ``` Any ideas?
Make sure the account you're using to disable the account has sufficient privileges to disable accounts. See [this example](http://msdn.microsoft.com/en-us/library/ms696026(VS.85).aspx) from Microsoft.
178,738
<p>Is there a way to catch a click on a cell in VBA with Excel? I am not referring to the <code>Worksheet_SelectionChange</code> event, as that will not trigger multiple times if the cell is clicked multiple times. <code>BeforeDoubleClick</code> does not solve my problem either, as I do not want to require the user to double click that frequently.</p> <p>My current solution does work with the <code>SelectionChange</code> event, but it appears to require the use of global variables and other suboptimal coding practices. It also seems prone to error.</p>
[ { "answer_id": 178780, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 0, "selected": false, "text": "<p>I don't think so. But you can create a shape object ( or wordart or something similiar ) hook Click event and place the object to position of the specified cell.</p>\n" }, { "answer_id": 179739, "author": "Mike Rosenblum", "author_id": 10429, "author_profile": "https://Stackoverflow.com/users/10429", "pm_score": 1, "selected": false, "text": "<p>SelectionChange is the event built into the Excel Object model for this. It should do exactly as you want, firing any time the user clicks anywhere... </p>\n\n<p>I'm not sure that I understand your objections to global variables here, you would only need 1 if you use the Application.SelectionChange event. However, you wouldn't need any if you utilize the Workbook class code behind (to trap the Workbook.SelectionChange event) or the Worksheet class code behind (to trap the Worksheet.SelectionChange) event. (Unless your issue is the \"global variable reset\" problem in VBA, for which there is only one solution: error handling everywhere. Do not allow any unhandled errors, instead log them and/or \"soft-report\" an error as a message box to the user.)</p>\n\n<p>You might also need to trap the Worksheet.Activate() and Worksheet.Deactivate() events (or the equivalent in the Workbook class) and/or the Workbook.Activate and Workbook.Deactivate() events so that you know when the user has switched worksheets and/or workbooks. The Window activate and deactivate events should make this approach complete. They could all call the same exact procedure, however, they all denote the same thing: the user changed the \"focus\", if you will.</p>\n\n<p>If you don't like VBA, btw, you can do the same using VB.NET or C#.</p>\n\n<p><em>[Edit: Dbb makes a very good point about the SelectionChange event not picking up a click when the user clicks within the currently selected cell. If you need to pick that up, then you would need to use subclassing.]</em></p>\n" }, { "answer_id": 180695, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>In order to trap repeated clicks on the same cell, you need to move the focus to a different cell, so that each time you click, you are in fact moving the selection. </p>\n\n<p>The code below will select the top left cell visible on the screen, when you click on any cell. Obviously, it has the flaw that it won't trap a click on the top left cell, but that can be managed (eg by selecting the top right cell if the activecell is the top left).</p>\n\n<pre><code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)\n 'put your code here to process the selection, then..\n ActiveWindow.VisibleRange.Cells(1, 1).Select\nEnd Sub\n</code></pre>\n" }, { "answer_id": 181698, "author": "dbb", "author_id": 25675, "author_profile": "https://Stackoverflow.com/users/25675", "pm_score": 6, "selected": true, "text": "<p>Clearly, there is no perfect answer. However, if you want to allow the user to </p>\n\n<ol>\n<li>select certain cells </li>\n<li>allow them to change those cells,\nand</li>\n<li>trap each click,even repeated clicks\non the same cell,</li>\n</ol>\n\n<p>then the easiest way seems to be to move the focus off the selected cell, so that clicking it will trigger a Select event.</p>\n\n<p>One option is to move the focus as I suggested above, but this prevents cell editing. Another option is to extend the selection by one cell (left/right/up/down),because this permits editing of the original cell, but will trigger a Select event if that cell is clicked again on its own. </p>\n\n<p>If you only wanted to trap selection of a single column of cells, you could insert a hidden column to the right, extend the selection to include the hidden cell to the right when the user clicked,and this gives you an editable cell which can be trapped every time it is clicked. The code is as follows </p>\n\n<pre><code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)\n 'prevent Select event triggering again when we extend the selection below\n Application.EnableEvents = False\n Target.Resize(1, 2).Select\n Application.EnableEvents = True\nEnd Sub\n</code></pre>\n" }, { "answer_id": 199095, "author": "Joe", "author_id": 26883, "author_profile": "https://Stackoverflow.com/users/26883", "pm_score": 0, "selected": false, "text": "<p>This has worked for me.....</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)\n\n If Mid(Target.Address, 3, 1) = \"$\" And Mid(Target.Address, 2, 1) &lt; \"E\" Then\n ' The logic in the if condition will filter for a specific cell or block of cells\n Application.ScreenUpdating = False\n 'MsgBox \"You just changed \" &amp; Target.Address\n\n 'all conditions are true .... DO THE FUNCTION NEEDED \n Application.ScreenUpdating = True\n End If\n ' if clicked cell is not in the range then do nothing (if condttion is not run) \nEnd Sub\n</code></pre>\n\n<p>NOTE: this function in actual use recalculated a pivot table if a user added a item in a data range of A4 to D500. The there were protected and unprotected sections in the sheet so the actual check for the click is if the column is less that \"E\" The logic can get as complex as you want to include or exclude any number of areas</p>\n\n<pre><code>block1 = row &gt; 3 and row &lt; 5 and column column &gt;\"b\" and &lt; \"d\" \nblock2 = row &gt; 7 and row &lt; 12 and column column &gt;\"b\" and &lt; \"d\" \nblock3 = row &gt; 10 and row &lt; 15 and column column &gt;\"e\" and &lt; \"g\"\n\nIf block1 or block2 or block 3 then\n do function .....\nend if \n</code></pre>\n" }, { "answer_id": 50528978, "author": "Dumitru Daniel", "author_id": 7251685, "author_profile": "https://Stackoverflow.com/users/7251685", "pm_score": 0, "selected": false, "text": "<p>I had a similar issue, and I fixed by running the macro \"onTime\", and by using some global variables to only run once the user has stopped clicking.</p>\n\n<pre><code>Public macroIsOnQueue As Boolean\nPrivate Sub Worksheet_SelectionChange(ByVal Target As Range)\n macroIsOnQueue = False\n Application.OnTime (Now() + TimeValue(\"00:00:02\")), \"addBordersOnRow\"\n macroIsOnQueue = True\nEnd sub\nSub addBordersOnRow()\n If macroIsOnQueue Then \n macroIsOnQueue = False\n ' add code here\n End if\nEnd sub\n</code></pre>\n\n<p>This way, whenever the user changes selection within 2 seconds, the macroIsOnQueue variable is set to false, but the last time selection is changed, macroIsOnQueue is set to true, and the macro will run.</p>\n\n<p>Hope this helps,\nHave fun with VBA !!</p>\n" }, { "answer_id": 61377786, "author": "Super Symmetry", "author_id": 13386420, "author_profile": "https://Stackoverflow.com/users/13386420", "pm_score": 0, "selected": false, "text": "<p>Just a follow-up to dbb's accepted answer: Rather than adding the immediate cell on the right to the selection, why not select a cell way off the working range (i.e. a dummy cell that you know the user will never need). In the following code cell <code>ZZ1</code> is the dummy cell</p>\n\n<pre><code>Private Sub Worksheet_SelectionChange(ByVal Target As Range)\n Application.EnableEvents = False\n Union(Target, Me.Range(\"ZZ1\")).Select\n Application.EnableEvents = True\n\n ' Respond to click/selection-change here\n\nEnd Sub\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12002/" ]
Is there a way to catch a click on a cell in VBA with Excel? I am not referring to the `Worksheet_SelectionChange` event, as that will not trigger multiple times if the cell is clicked multiple times. `BeforeDoubleClick` does not solve my problem either, as I do not want to require the user to double click that frequently. My current solution does work with the `SelectionChange` event, but it appears to require the use of global variables and other suboptimal coding practices. It also seems prone to error.
Clearly, there is no perfect answer. However, if you want to allow the user to 1. select certain cells 2. allow them to change those cells, and 3. trap each click,even repeated clicks on the same cell, then the easiest way seems to be to move the focus off the selected cell, so that clicking it will trigger a Select event. One option is to move the focus as I suggested above, but this prevents cell editing. Another option is to extend the selection by one cell (left/right/up/down),because this permits editing of the original cell, but will trigger a Select event if that cell is clicked again on its own. If you only wanted to trap selection of a single column of cells, you could insert a hidden column to the right, extend the selection to include the hidden cell to the right when the user clicked,and this gives you an editable cell which can be trapped every time it is clicked. The code is as follows ``` Private Sub Worksheet_SelectionChange(ByVal Target As Range) 'prevent Select event triggering again when we extend the selection below Application.EnableEvents = False Target.Resize(1, 2).Select Application.EnableEvents = True End Sub ```
178,740
<p>Trying to use an excpetion class which could provide location reference for XML parsing, found an interesting behavior - compiler could not choose between overload which consumes an interface and one which needs System.Exception when I trying to pass XmlReader as a parameter.</p> <p>Detais are following:</p> <pre><code>//exception overloads: public FilterXmlParseException(string message, Exception innerException) : base(message, innerException) { } public FilterXmlParseException(string message, IXmlLineInfo lineInfo) {...} //Usage: XmlReader reader = ... IXmlLineInfo lineinfo = (IXmlLineInfo)reader; //fails throw new FilterXmlParseException("&lt;Filter&gt; element expected", reader); //ok throw new FilterXmlParseException("&lt;Filter&gt; element expected", lineinfo); </code></pre> <p>And it fails since it could not select correct overload.But why? We see that XmlReader supports an interface and it is not inherited from System.Exception</p>
[ { "answer_id": 178764, "author": "Grzenio", "author_id": 5363, "author_profile": "https://Stackoverflow.com/users/5363", "pm_score": 2, "selected": true, "text": "<p>The line:</p>\n\n<pre><code>//fails\nthrow new FilterXmlParseException(\"&lt;Filter&gt; element expected\", reader);\n</code></pre>\n\n<p>because XmlReader doesn't implement IXmlLineInfo. I am not sure if your cast works, but the casts are not checked statically. If it actually works, it is because the concrete class (that inherits from XmlReader) implements this interface, but the compiler has no way to know it.</p>\n" }, { "answer_id": 178775, "author": "Nick", "author_id": 22407, "author_profile": "https://Stackoverflow.com/users/22407", "pm_score": 0, "selected": false, "text": "<p>It couldn't choose an overload for the XmlReader call because <em>neither</em> overload is acceptable. XmlReader does not inherit from Exception, so the first call is invalid. XmlReader also does not Implement IXmlLineInfo.</p>\n\n<p>The reason why it works in the second case is that you are forcing the cast. However, I believe that if you were to actually run that code, it would throw an InvalidCastException. Read the documentation on XmlReader, and you'll see that the only interface it implements is IDispoable.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.aspx</a></p>\n" }, { "answer_id": 178787, "author": "Davy8", "author_id": 23822, "author_profile": "https://Stackoverflow.com/users/23822", "pm_score": 0, "selected": false, "text": "<p>It looks like it's XmlTextReader that implements IXmlLineInfo, not XmlReader</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.xml.ixmllineinfo(VS.71).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.xml.ixmllineinfo(VS.71).aspx</a></p>\n" }, { "answer_id": 178798, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 0, "selected": false, "text": "<p>You left out the critical part:</p>\n\n<pre><code>XmlReader reader = XmlTextReader.Create(sreader, readerSettings);\n</code></pre>\n\n<p>You call a method which returns an <code>XmlTextReader</code>, but the type of your variable is <code>XmlReader</code>.</p>\n\n<p>Casting happens at runtime, so the runtime value of <code>reader</code> can be cast to <code>IXmlLineInfo</code>, because <code>XmlTextReader</code> supports that interface, even though <code>XmlReader</code> doesnt.</p>\n\n<p>Overload resoution happens at compile time though, so because <code>XmlReader</code> doesnt support <code>IXmlLineInfo</code>, it cant be matched to the signature.</p>\n\n<p>You can fix it by writing:</p>\n\n<pre><code>XmlTextReader reader = (XmlTextReader)XmlTextReader.Create(sreader, readerSettings);\n</code></pre>\n\n<p>Note that you need a cast because the return type of <code>Create</code> is <code>XmlReader</code>, even if it actually returns a <code>XmlTextReader</code>.</p>\n" }, { "answer_id": 178817, "author": "Ilya Komakhin", "author_id": 21603, "author_profile": "https://Stackoverflow.com/users/21603", "pm_score": 0, "selected": false, "text": "<p>Thanks for the answers.</p>\n\n<p>I understood that base class does not implement IXmlLineInfo.</p>\n\n<p>But really i was using XmlTextReader.Create to get an instance of the actual reader.</p>\n\n<p>So I suppose actual solution is to use XmlTextReader constructor instead of factory method to prevent such confusion</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21603/" ]
Trying to use an excpetion class which could provide location reference for XML parsing, found an interesting behavior - compiler could not choose between overload which consumes an interface and one which needs System.Exception when I trying to pass XmlReader as a parameter. Detais are following: ``` //exception overloads: public FilterXmlParseException(string message, Exception innerException) : base(message, innerException) { } public FilterXmlParseException(string message, IXmlLineInfo lineInfo) {...} //Usage: XmlReader reader = ... IXmlLineInfo lineinfo = (IXmlLineInfo)reader; //fails throw new FilterXmlParseException("<Filter> element expected", reader); //ok throw new FilterXmlParseException("<Filter> element expected", lineinfo); ``` And it fails since it could not select correct overload.But why? We see that XmlReader supports an interface and it is not inherited from System.Exception
The line: ``` //fails throw new FilterXmlParseException("<Filter> element expected", reader); ``` because XmlReader doesn't implement IXmlLineInfo. I am not sure if your cast works, but the casts are not checked statically. If it actually works, it is because the concrete class (that inherits from XmlReader) implements this interface, but the compiler has no way to know it.
178,751
<p>Here is the sample:</p> <pre><code> Dim TestString As String = "Hello," &amp; Chr(0) &amp; "World" MsgBox(TestString, , "TestString.Length=" &amp; TestString.Length.ToString) </code></pre> <p>Result - Messagebox shows "Hello," with title says TestString.Length=12 </p> <p>I guess the chr(0) is treated as the end of zero terminated string, but it's not what i want. </p> <p>What the right method to operate with Chr(0) ?</p> <hr> <p>I've also tried this in asp.net with no avail. I'm sending the string over a socket. My problem is that when I'm debugging it the whole string doesn't add up. I need to send them a rather large string for it. What comes up really on the message window doesn't bother me. I used the above as an example. I just need when putting the multiple variables that it adds correctly to the string. Another example of it would be </p> <pre><code>"SCORE".ToString.PadRight(8, chr(0)) &amp; "3.0".ToString.PadRight(10, chr(0)) &amp; "0".ToString.PadRight(1, "0") </code></pre> <p>the expected value would score3.00</p> <p>What I get though is score3.0</p>
[ { "answer_id": 178777, "author": "Nick DeVore", "author_id": 1380, "author_profile": "https://Stackoverflow.com/users/1380", "pm_score": 0, "selected": false, "text": "<p>chr(0) is null. Are you after a single space chr(32) or just type vblf or after Enter(Return) chr(13) or type vbcrlf</p>\n" }, { "answer_id": 178778, "author": "Alonso", "author_id": 24927, "author_profile": "https://Stackoverflow.com/users/24927", "pm_score": 0, "selected": false, "text": "<p>Indeed Chr(0) is used to terminate a string, if you want a newline character you can use Environment.NewLine() in VB.NET or vbNewLine in VB6</p>\n" }, { "answer_id": 178784, "author": "Ryan", "author_id": 17917, "author_profile": "https://Stackoverflow.com/users/17917", "pm_score": 1, "selected": false, "text": "<p>You are absolutely right that Chr(0) is treated as a control character that means \"this is the end of this string.\" How would you prefer this character be represented? A space? A newline? Do you only need to print the string in its entirety, or are there other things about the string that are significant?</p>\n\n<p>I'd just call <code>TestString.Replace(chr(0), \" \")</code> or whatever the equivalent is in VB.NET</p>\n" }, { "answer_id": 178811, "author": "CrashCodes", "author_id": 16260, "author_profile": "https://Stackoverflow.com/users/16260", "pm_score": 1, "selected": false, "text": "<p>I don't think the problem is with the vb string as evidenced by your length output. I think it's with the MsgBox function that probably still uses the windows api that treats char(0) as a terminator. </p>\n\n<p>If your debugging or something and you want to represent that there is a char(0) you should replace it with a printable set of characters that you understand represents the char(0). </p>\n" }, { "answer_id": 178816, "author": "jeffm", "author_id": 1544, "author_profile": "https://Stackoverflow.com/users/1544", "pm_score": 0, "selected": false, "text": "<p>Seems like VB is handling the string correctly because it knows the correct length (12), so the problem is just when you display the string. Can you replace chr(0) with a space just when you want to display it?</p>\n" }, { "answer_id": 178852, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 1, "selected": false, "text": "<p>MsgBox most likly uses the windows API function <a href=\"http://msdn.microsoft.com/en-us/library/ms645505(VS.85).aspx\" rel=\"nofollow noreferrer\">MessageBox</a>, which uses a null terminated string, and thus will only display up to the first null. Most of the windows api works(if not all?) with null terminated string so you may have to find a diffrent way to display the string.</p>\n\n<p>Your debugging tools (eg visual studio) may also treat strings as null terminated, which again will only display up to the first null (however I'm not sure on this, and am not currently at a computer I can test it on for vs08).</p>\n" }, { "answer_id": 178901, "author": "jeffm", "author_id": 1544, "author_profile": "https://Stackoverflow.com/users/1544", "pm_score": 2, "selected": true, "text": "<p>The sample code in the questioner's example (\"SCORE\".ToString...) works fine for me in a console application. The VS2005 debugger does not show the string correctly, but it outputs to the console just fine. So, my feeling is either that you think it's incorrect because the debugger wrongly says so or your output string is not long enough to include all the padding.</p>\n" }, { "answer_id": 179557, "author": "pro3carp3", "author_id": 7899, "author_profile": "https://Stackoverflow.com/users/7899", "pm_score": 0, "selected": false, "text": "<p>Take a look at <a href=\"http://www.yoda.arachsys.com/csharp/strings.html\" rel=\"nofollow noreferrer\">Jon Skeet's article</a> in regard to strings. It appears that the TestString would contains all of the characters, including the embeded \\0, but it is not displayed correclty. The article includes a function (in c#) that displays the string properly. </p>\n" }, { "answer_id": 67020757, "author": "UnhandledException-InvalidChar", "author_id": 11975130, "author_profile": "https://Stackoverflow.com/users/11975130", "pm_score": 0, "selected": false, "text": "<p>Use <em>MarshalAs</em> attribute in procedure declarations, the ones which return strings that contain chr(0) as shown below</p>\n<pre><code>&lt;DllImport(&quot;my.dll&quot;, ... )&gt; _\nSub modifyStr(&lt;MarshalAs(UnmanagedType.BStr)&gt; ByRef stringContainingNullChars as String) \n\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12369/" ]
Here is the sample: ``` Dim TestString As String = "Hello," & Chr(0) & "World" MsgBox(TestString, , "TestString.Length=" & TestString.Length.ToString) ``` Result - Messagebox shows "Hello," with title says TestString.Length=12 I guess the chr(0) is treated as the end of zero terminated string, but it's not what i want. What the right method to operate with Chr(0) ? --- I've also tried this in asp.net with no avail. I'm sending the string over a socket. My problem is that when I'm debugging it the whole string doesn't add up. I need to send them a rather large string for it. What comes up really on the message window doesn't bother me. I used the above as an example. I just need when putting the multiple variables that it adds correctly to the string. Another example of it would be ``` "SCORE".ToString.PadRight(8, chr(0)) & "3.0".ToString.PadRight(10, chr(0)) & "0".ToString.PadRight(1, "0") ``` the expected value would score3.00 What I get though is score3.0
The sample code in the questioner's example ("SCORE".ToString...) works fine for me in a console application. The VS2005 debugger does not show the string correctly, but it outputs to the console just fine. So, my feeling is either that you think it's incorrect because the debugger wrongly says so or your output string is not long enough to include all the padding.
178,762
<p>Sorry, I couldn't figure out a good way to phrase my real question.</p> <p>I run a high-traffic ASP.NET site on a 64-bit machine. I have IIS running in 32-bit mode, however, due to some legacy components of the app. I am running this particular web app inside an application pool that has the web garden option on (running 6 processes inside an 8 core machine).</p> <p>Once or twice a week one of the processes will skyrocket into 100% CPU utilization, causing a giant slowdown for the site, so my plan was to wait until that happens, memory dump the offending process, then poke around WinDbg to zero in on the thread that's spiking to see where the code is spinning its wheels.</p> <p>I've debugged using WinDbg before to figure out what was causing a deadlock on the site, but that was several months ago and I can't remember how I got it working. (As a side note, this is a lesson to document everything you do.)</p> <p>I'm running WinDbg on the Windows 2003 server that's running the site, so as to prevent any DLL version problems. Here have been my steps so far, please let me know where I'm going wrong to get the error message that I'm getting.</p> <ol> <li><p>I first memory dump the spiking process using UserDump, with the following command, where 3389 is the ID of the process:</p> <p><code>userdump -k 3389</code></p></li> <li><p>I load the dump into the x86 edition of WinDbg.</p></li> <li><p>Since I'm running 32-bit on a 64-bit machine, I first load the memory dump and then:</p> <p><code>.load wow64exts</code></p> <p><code>.effmach x86</code></p></li> <li><p>I make sure that my symbol path includes the directory that contains my apps PDB files:</p> <p><code>.sympath+ c:\inetpub\myapp\bin</code></p></li> <li><p>Running just `.load SOS' fails with an error of "The system cannot find the file specified", so I go the fully qualified route of the following, which works:</p> <p><code>.load c:\windows\microsoft.net\framework\v2.0.50727\sos</code></p></li> </ol> <p>From here, I'm lost. I try any of the SOS commands, like <code>!threads</code>, only to get this error:</p> <pre><code>Failed to load data access DLL, 0x80004005 </code></pre> <p>That error is also accompanied by the numbered list of items that I should be verifying. I have verified that I am running the most current version of the debugger, mscordacwks.dll is in fact in the same directory as the mscorwks.dll file, and I'm debugging on the same architecture as the dump file. </p> <p>I've also run the magical "<code>.cordll -ve -u -l</code>" command, but that doesn't solve anything. I'm always greeted with "<code>CLR DLL status: No load attempts</code>" when I execute that. Then I try "<code>.reload</code>", which yields a handful of warnings like "<code>WARNING: wldap32 overlaps dnsapi</code>". I <em>wish</em> it said something like "<code>CLRDLL: Loaded DLL C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscordacwks.dll</code>". But it doesn't.</p>
[ { "answer_id": 178776, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 2, "selected": false, "text": "<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/ms979205.aspx\" rel=\"nofollow noreferrer\">(MSDN) How To: Use CLR Profiler</a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/magazine/cc163528.aspx\" rel=\"nofollow noreferrer\">(MSDN Magazine) Investigating Memory Issues</a></li>\n</ul>\n" }, { "answer_id": 178796, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "<p>Try executing !sw before running the sos commands. See this <a href=\"http://blogs.msdn.com/alejacma/archive/2008/07/18/How-to-use-Windbg-to-debug-a-dump-of-a-32bit-.NET-app-running-on-a-x64-machine.aspx\" rel=\"nofollow noreferrer\">blog post</a>.</p>\n" }, { "answer_id": 178980, "author": "Dave R", "author_id": 6969, "author_profile": "https://Stackoverflow.com/users/6969", "pm_score": 2, "selected": false, "text": "<p>In my experience, spiking app pool can be due to it being recycled. Have you tried IIS Crash / Hang agent and IIS Dump ?</p>\n\n<p><a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyID=01c4f89d-cc68-42ba-98d2-0c580437efcf&amp;DisplayLang=en\" rel=\"nofollow noreferrer\">http://www.microsoft.com/downloads/details.aspx?FamilyID=01c4f89d-cc68-42ba-98d2-0c580437efcf&amp;DisplayLang=en</a></p>\n\n<p>Also included with them is a dumpfile analyzer which will tell you about memory leaks and even suggest areas of your code that need fixing (complete with links to the applicable MSKB articles!)</p>\n" }, { "answer_id": 250065, "author": "Pure.Krome", "author_id": 30674, "author_profile": "https://Stackoverflow.com/users/30674", "pm_score": 1, "selected": false, "text": "<p>Dude - not sure if this helps, but maybe try this.</p>\n\n<ol>\n<li>Copy c:\\windows\\microsoft.net\\framework\\v2.0.50727\\sos.dll to the same directory where windbg is installed to (eg. c:\\program files\\Debugging Tools for Windows\\ ). Why? make it easy to load the sos file</li>\n<li>run windbg</li>\n<li>load the memory dump file. for me, i use ctrl-D or File -> open crash dump</li>\n<li>.load sos &lt;-- take note of the fullstop BEFORE the load command</li>\n<li>.symfix c:\\temp\\debug_symbols</li>\n<li>.reload</li>\n</ol>\n\n<p>Ok.. take note of the commandline. this tells me the current THREAD that the dump was in. That might be useless for a HIGH CPU scenario .. because we could be in any thread.</p>\n\n<p>so from here i look at the threads that were running and check out the <em>busiest</em> thread</p>\n\n<p>8 !threadpool &lt;-- this is so i can see the cpu utilization to check we are in a crap (busy) state... eg 100% cpu or what not.</p>\n\n<p>9 !runaway &lt;-- list the threads that have ben around the longest...\neg.</p>\n\n<pre><code>0:027 !runaway\nUser Mode Time\nThread Time\n18:704 0 days 0:00:17.843 &lt;-- Thread #18\n19:9f4 0 days 0:00:13.328 &lt;-- Thread #19\n16:1948 0 days 0:00:10.718\n26:a7c 0 days 0:00:01.375\n24:114 0 days 0:00:01.093\n27:d54 0 days 0:00:00.390\n28:1b70 0 days 0:00:00.328\n0:b7c 0 days 0:00:00.171\n25:3f8 0 days 0:00:00.000\n23:1968 0 days 0:00:00.000\n</code></pre>\n\n<p>thread 18 and 19 have been hanging around awhile.. hmm.... are they stuck in a loop? </p>\n\n<ol start=\"10\">\n<li>~18s &lt;-- goto thread 18.</li>\n<li>!clrstack &lt;-- clr call stack .. which is just like debugging in windows.</li>\n</ol>\n\n<p>.. and from here u can dump objects and stuff by giving the address references and stuff.</p>\n\n<p>check out !help to list some commands to try and use .. i think !help.sos also works?</p>\n\n<p>HTH .. if u still get stuck, ask away at what worked and what didn't.</p>\n" }, { "answer_id": 1236207, "author": "Chris Ostler", "author_id": 91472, "author_profile": "https://Stackoverflow.com/users/91472", "pm_score": 1, "selected": false, "text": "<p>I just had to deal with a similar problem. In my case, it turned out that WinDbg wasn't able to find the correct version of mscorwks.dll. In addition to the Framework version, there is also a revision of the DLL which can be different between the same framework version.</p>\n<p>In theory, the Microsoft symbol servers should be able to supply the necessary DLL, but it wasn't happening for me. To solve it, I used <code>!sym noisy</code> to get additional information on symbol loading. When I did <code>!dumpstack</code>, I got the error message:</p>\n<p><code>SYMSRV: http://msdl.microsoft.com/download/symbols/mscorwks.dll/492B82C1590000/mscorwks.dll not found</code></p>\n<p>To fix this, I created the appropriate folders in my local symbol cache, and copied mscorwks.dll from the machine the dump came from. After a <code>.reload</code>, WinDbg found the necessary DLL in the local symbol cache, and continued on happily.</p>\n<p>Alternatively, you can find the exact version of mscorwks being used with <code>lm v m mscorwks</code>. You can then find the update that contains the version you need from <a href=\"https://learn.microsoft.com/en-us/archive/blogs/dougste/version-history-of-the-clr-2-0\" rel=\"nofollow noreferrer\">this list</a>. You will need to extract the necessary DLLs from the particular update to the right location.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22299/" ]
Sorry, I couldn't figure out a good way to phrase my real question. I run a high-traffic ASP.NET site on a 64-bit machine. I have IIS running in 32-bit mode, however, due to some legacy components of the app. I am running this particular web app inside an application pool that has the web garden option on (running 6 processes inside an 8 core machine). Once or twice a week one of the processes will skyrocket into 100% CPU utilization, causing a giant slowdown for the site, so my plan was to wait until that happens, memory dump the offending process, then poke around WinDbg to zero in on the thread that's spiking to see where the code is spinning its wheels. I've debugged using WinDbg before to figure out what was causing a deadlock on the site, but that was several months ago and I can't remember how I got it working. (As a side note, this is a lesson to document everything you do.) I'm running WinDbg on the Windows 2003 server that's running the site, so as to prevent any DLL version problems. Here have been my steps so far, please let me know where I'm going wrong to get the error message that I'm getting. 1. I first memory dump the spiking process using UserDump, with the following command, where 3389 is the ID of the process: `userdump -k 3389` 2. I load the dump into the x86 edition of WinDbg. 3. Since I'm running 32-bit on a 64-bit machine, I first load the memory dump and then: `.load wow64exts` `.effmach x86` 4. I make sure that my symbol path includes the directory that contains my apps PDB files: `.sympath+ c:\inetpub\myapp\bin` 5. Running just `.load SOS' fails with an error of "The system cannot find the file specified", so I go the fully qualified route of the following, which works: `.load c:\windows\microsoft.net\framework\v2.0.50727\sos` From here, I'm lost. I try any of the SOS commands, like `!threads`, only to get this error: ``` Failed to load data access DLL, 0x80004005 ``` That error is also accompanied by the numbered list of items that I should be verifying. I have verified that I am running the most current version of the debugger, mscordacwks.dll is in fact in the same directory as the mscorwks.dll file, and I'm debugging on the same architecture as the dump file. I've also run the magical "`.cordll -ve -u -l`" command, but that doesn't solve anything. I'm always greeted with "`CLR DLL status: No load attempts`" when I execute that. Then I try "`.reload`", which yields a handful of warnings like "`WARNING: wldap32 overlaps dnsapi`". I *wish* it said something like "`CLRDLL: Loaded DLL C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscordacwks.dll`". But it doesn't.
* [(MSDN) How To: Use CLR Profiler](http://msdn.microsoft.com/en-us/library/ms979205.aspx) * [(MSDN Magazine) Investigating Memory Issues](http://msdn.microsoft.com/en-us/magazine/cc163528.aspx)
178,809
<p>I am trying to fix some bugs in a product I inherited, and I have this snippet of javascript that is supposed to hilight a couple of boxes and pop up a confirm box. What currently happens is I see the boxes change color and there is a 5 or so second delay, then it's as if the missing confirm just accepts itself. Does anyone smarter than I see anything amiss in this code?</p> <pre><code>function lastCheckInv() { document.getElementById("ctl00$ContentPlaceHolderMain$INDet$txtInvNumber").style.background = "yellow"; document.getElementById("ctl00$ContentPlaceHolderMain$INDet$txtInvNumber").focus(); document.getElementById("ctl00_ContentPlaceHolderMain_INDet_AddCharges").style.background = "yellow"; document.getElementById("ctl00_ContentPlaceHolderMain_INDet_lblFreight").style.background = "yellow"; bRetVal = confirm("Are you sure the information associated with this invoice is correct?"); return bRetVal; } </code></pre>
[ { "answer_id": 178820, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 3, "selected": false, "text": "<p>The only thing I can think of is if one of the lines before the confirm is throwing an exception and you're never actually getting to the confirm.</p>\n\n<p>If you're using IE, make sure script debugging is enabled. If you're using Firefox, install the Firebug add-on and enable it for your website.</p>\n\n<p>Or, for very primitive debugging, just put alerts after each statement and figure out where it's bombing.</p>\n" }, { "answer_id": 178825, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 1, "selected": false, "text": "<p>A few thoughts: Could be the <code>.focus()</code> call is hiding your confirm behind the page? Or could it be that one of your control id's is not correct causing, the <code>.style.background</code> references to fail?</p>\n\n<ol>\n<li>You should set the focus <em>after</em> showing the confirm box, otherwise the confirm box will grab focus away, making that line meaningless.</li>\n<li>Don't hard-code ASP.Net id's like that. While they typically are consistent, a future version of ASP.net won't guarantee the same scheme, meaning your setting yourself up for pain when it comes time to update this code at some point in the future. Use the server-side .ClientID property for the controls to write those values into the javascript somewhere as variables that you can reference.</li>\n</ol>\n\n<p>Update:<br>\nBased on your comment to another response, this code will result in a postback if the function returns true. In that case, there's not point in running the <code>.focus()</code> line at all unless you are going to return false.</p>\n" }, { "answer_id": 178832, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 3, "selected": false, "text": "<p>You should use the following method to reference your controls from JavaScript:</p>\n\n<pre><code>document.getElementById(&lt;%= txtInvNumber.ClientID %&gt;).style.background = \"yellow\"\n</code></pre>\n\n<p>If that doesn't help, try setting a breakpoint in your JavaScript and stepping through it to see where it's failing.</p>\n" }, { "answer_id": 178981, "author": "Soldarnal", "author_id": 3420, "author_profile": "https://Stackoverflow.com/users/3420", "pm_score": 2, "selected": false, "text": "<p>This test script ran fine for me in IE, Firefox, and Opera. So there doesn't seem to be anything wrong with your basic syntax. The problem is either in the ID's (which doesn't fit with the fact that it acts as if confirmed after 5 seconds) or in some other conflicting JavaScript on the page. It will be difficult to help you without seeing more of the page.</p>\n\n<pre><code>&lt;script language=\"javascript\"&gt;\nfunction lastCheckInv() {\n\n document.getElementById(\"test1\").style.background = \"yellow\";\n document.getElementById(\"test1\").focus();\n document.getElementById(\"test2\").style.background = \"yellow\";\n document.getElementById(\"test3\").style.background = \"yellow\";\n bRetVal = confirm(\"Are you sure?\");\n\n return bRetVal;\n\n}\n&lt;/script&gt;\n\n&lt;form method=\"get\" onsubmit=\"return lastCheckInv();\"&gt;\n &lt;input id=\"test1\" name=\"test1\" value=\"Hello\"&gt;\n &lt;input id=\"test2\" name=\"test2\" value=\"Hi\"&gt;\n &lt;input id=\"test3\" name=\"test3\" value=\"Bye\"&gt;\n &lt;input type=\"submit\" name=\"Save\" value=\"Save\"&gt;\n&lt;/form&gt;\n</code></pre>\n" }, { "answer_id": 179135, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 0, "selected": false, "text": "<p>I do not like accesing objects directly by</p>\n\n<pre><code>document.getElementById(\"ctl00_ContentPlaceHolderMain_INDet_lblFreight\").style.background = \"yellow\"; \n</code></pre>\n\n<p>If the object is not returned JavaScript will error out. I prefer the method of</p>\n\n<pre><code>var obj = document.getElementById(\"ctl00_ContentPlaceHolderMain_INDet_lblFreight\");\n\nif(obj)\n{\n obj.style.background = \"yellow\";\n}\n</code></pre>\n\n<p>My guess is you are trying to access an object that is not on the DOM, so it never gets to the confirm call.</p>\n" }, { "answer_id": 179359, "author": "Odilon Redo", "author_id": 21166, "author_profile": "https://Stackoverflow.com/users/21166", "pm_score": 0, "selected": false, "text": "<p>It might be worth checking that the elements actually exist. Also,try delaying the focus until after the confirm():</p>\n\n<pre><code>function lastCheckInv() {\n\n var myObjs,bRetVal;\n\n myObjs=[\n \"ctl00_ContentPlaceHolderMain_INDet_AddCharges\",\n \"ctl00_ContentPlaceHolderMain_INDet_lblFreight\",\n \"ctl00$ContentPlaceHolderMain$INDet$txtInvNumber\"\n ];\n\n\n bRetVal = confirm(\"Are you sure the information associated with this invoice is correct?\");\n\n for (var i=0, j=myObjs.length, myElement; i&lt;j; i++){\n\n myElement=document.getElementById(myObjs[i]);\n\n if (!myElement){\n // this element is missing\n continue;\n }\n\n else {\n\n // apply colour\n myElement.style.background = \"yellow\";\n\n // focus the last object in the array\n\n if (i == (j-1) ){\n myObj.focus();\n }\n\n\n }\n\n }\n\n\n return bRetVal;\n\n}\n</code></pre>\n" }, { "answer_id": 181039, "author": "KristoferA", "author_id": 11241, "author_profile": "https://Stackoverflow.com/users/11241", "pm_score": 0, "selected": false, "text": "<p>Is bRetVal actually declared anywhere?</p>\n\n<p>If not, \"<em>var bRetVal = confirm</em>....\" is a friendly way of telling jscript that it is a variable.</p>\n" }, { "answer_id": 240641, "author": "Georg", "author_id": 30776, "author_profile": "https://Stackoverflow.com/users/30776", "pm_score": 0, "selected": false, "text": "<pre><code>function lastCheckInv()\n\n{ \n document.getElementById(\"ctl00_ContentPlaceHolderMain_INDet_txtInvNumber\").style.background = \"yellow\"; \n document.getElementById(\"ctl00_ContentPlaceHolderMain_INDet_txtInvNumber\").focus(); \n document.getElementById(\"ctl00_ContentPlaceHolderMain_INDet_AddCharges\").style.background = \"yellow\"; \n document.getElementById(\"ctl00_ContentPlaceHolderMain_INDet_lblFreight\").style.background = \"yellow\"; \n return confirm(\"Are you sure the information associated with this invoice is correct?\"); \n}\n</code></pre>\n\n<p>The first two lines in your function are wrong, $ are in the UniqueID of an ASP.Net Control.</p>\n\n<p>On Clientside you have to use the ClientID, replace $ with _ . </p>\n\n<p>If you are sure that the Controls exists, the \ncode above might work.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13593/" ]
I am trying to fix some bugs in a product I inherited, and I have this snippet of javascript that is supposed to hilight a couple of boxes and pop up a confirm box. What currently happens is I see the boxes change color and there is a 5 or so second delay, then it's as if the missing confirm just accepts itself. Does anyone smarter than I see anything amiss in this code? ``` function lastCheckInv() { document.getElementById("ctl00$ContentPlaceHolderMain$INDet$txtInvNumber").style.background = "yellow"; document.getElementById("ctl00$ContentPlaceHolderMain$INDet$txtInvNumber").focus(); document.getElementById("ctl00_ContentPlaceHolderMain_INDet_AddCharges").style.background = "yellow"; document.getElementById("ctl00_ContentPlaceHolderMain_INDet_lblFreight").style.background = "yellow"; bRetVal = confirm("Are you sure the information associated with this invoice is correct?"); return bRetVal; } ```
The only thing I can think of is if one of the lines before the confirm is throwing an exception and you're never actually getting to the confirm. If you're using IE, make sure script debugging is enabled. If you're using Firefox, install the Firebug add-on and enable it for your website. Or, for very primitive debugging, just put alerts after each statement and figure out where it's bombing.
178,821
<p>I have seen arguments for using explicit interfaces as a method of locking a classes usage to that interface. The argument seems to be that by forcing others to program to the interface you can ensure better decoupling of the classes and allow easier testing.</p> <p>Example:</p> <pre><code>public interface ICut { void Cut(); } public class Knife : ICut { void ICut.Cut() { //Cut Something } } </code></pre> <p>And to use the Knife object:</p> <pre><code>ICut obj = new Knife(); obj.Cut(); </code></pre> <p>Would you recommend this method of interface implementation? Why or why not?</p> <p>EDIT: Also, given that I am using an explicit interface the following would NOT work.</p> <pre><code>Knife obj = new Knife(); obj.Cut(); </code></pre>
[ { "answer_id": 178830, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 0, "selected": false, "text": "<p>If the client code doesn't care about anything other than the fact that it can use the object to <code>Cut()</code> things, then use <code>ICut</code>. </p>\n" }, { "answer_id": 178831, "author": "Steve g", "author_id": 12092, "author_profile": "https://Stackoverflow.com/users/12092", "pm_score": 1, "selected": false, "text": "<p>Well there is an organizational advantage. You can encapsulate your ICuttingSurface, ICut and related functionality into an Assembly that is self-contained and unit testable. Any implementations of the ICut interface are easily Mockable and can be made to be dependant upon only the ICut interface and not actual implementations which makes for a more modular and clean system.</p>\n\n<p>Also this helps keep the inheritance more simplified and gives you more flexibility to use polymoprhism.</p>\n" }, { "answer_id": 178840, "author": "Jeff", "author_id": 23902, "author_profile": "https://Stackoverflow.com/users/23902", "pm_score": 0, "selected": false, "text": "<p>Yes, but not necessarily for the given reasons.</p>\n\n<p>An example:</p>\n\n<p>On my current project, we are building a tool for data entry. We have certain functions that are used by all (or almost all) tabs, and we are coding a single page (the project is web-based) to contain all of the data entry controls.</p>\n\n<p>This page has navigation on it, and buttons to interact with all the common actions.</p>\n\n<p>By defining an interface (IDataEntry) that implements methods for each of the functions, and implementing that interface on each of the controls, we can have the aspx page fire public methods on the user controls which do the actual data entry.</p>\n\n<p>By defining a strict set of interaction methods (such as your 'cut' method in the example) Interfaces allow you to take an object (be it a business object, a web control, or what have you) and work with it in a defined way.</p>\n\n<p>For your example, you could call cut on any ICut object, be it a knife, a saw, a blowtorch, or mono filament wire.</p>\n\n<p>For testing purposes, I think interfaces are also good. If you define tests based around the expected functionality of the interface, you can define objects as described and test them. This is a very high-level test, but it still ensures functionality. HOWEVER, this should not replace unit testing of the individual object methods...it does no good to know that 'obj.Cut' resulted in a cutting if it resulted in the wrong thing being cut, or in the wrong place.</p>\n" }, { "answer_id": 178843, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 2, "selected": false, "text": "<p>Yes. And not just for testing. It makes sense to factor common behaviour into an interface (or abstract class); that way you can make use of polymorphism.</p>\n\n<pre><code>public class Sword: ICut\n{ \n void ICut.Cut() \n { \n //Cut Something \n }\n}\n</code></pre>\n\n<p>Factory could return a type of sharp implement!:</p>\n\n<pre><code>ICut obj = SharpImplementFactory();\n\nobj.Cut();\n</code></pre>\n" }, { "answer_id": 178844, "author": "Nick", "author_id": 22407, "author_profile": "https://Stackoverflow.com/users/22407", "pm_score": 1, "selected": false, "text": "<p>Using interfaces in this method does not, in and of itself, lead to decoupled code. If this is all you do, it just adds another layer of obfuscation and probably makes this more confusing later on.</p>\n\n<p>However, if you combine interface based programming with Inversion of Control and Dependency Injection, then you are really getting somewhere. You can also make use of Mock Objects for Unit Testing with this type of setup if you are into Test Driven Development.</p>\n\n<p>However, IOC, DI and TDD are all major topics in and of themselves, and entire books have been written on each of those subjects. Hopefully this will give you a jumping off point of things you can research.</p>\n" }, { "answer_id": 178871, "author": "erlando", "author_id": 4192, "author_profile": "https://Stackoverflow.com/users/4192", "pm_score": 3, "selected": true, "text": "<p>To quote GoF chapter 1:</p>\n\n<ul>\n<li>\"Program to an interface, not an implementation\".</li>\n<li>\"Favor object composition over class inheritance\".</li>\n</ul>\n\n<p>As C# does not have multiple inheritance, object composition and programming to interfaces are the way to go.</p>\n\n<p>ETA: And you should never use multiple inheritance anyway but that's another topic altogether.. :-)</p>\n\n<p>ETA2: I'm not so sure about the explicit interface. That doesn't seem constructive. Why would I want to have a Knife that can only Cut() if instansiated as a ICut?</p>\n" }, { "answer_id": 178996, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 2, "selected": false, "text": "<p>I've only used it in scenarios where I want to restrict access to certain methods.</p>\n\n<pre><code>public interface IWriter\n{\n void Write(string message);\n}\n\npublic interface IReader\n{\n string Read();\n}\n\npublic class MessageLog : IReader, IWriter\n{\n public string Read()\n {\n // Implementation\n\n return \"\";\n }\n\n void IWriter.Write(string message)\n {\n // Implementation\n }\n}\n\npublic class Foo\n{\n readonly MessageLog _messageLog;\n IWriter _messageWriter;\n\n public Foo()\n {\n _messageLog = new MessageLog();\n _messageWriter = _messageLog;\n }\n\n public IReader Messages\n {\n get { return _messageLog; }\n }\n}\n</code></pre>\n\n<p>Now Foo can write messages to it's message log using _messageWriter, but clients can only read. This is especially beneficial in a scenario where your classes are ComVisible. Your client can't cast to the Writer type and alter the information inside the message log.</p>\n" }, { "answer_id": 234570, "author": "Krypes", "author_id": 31260, "author_profile": "https://Stackoverflow.com/users/31260", "pm_score": 1, "selected": false, "text": "<p>Allowing only callers expecting to explicit interface type ensures methods are only visible in the context they are needed in.</p>\n\n<p>Consider a logical entity in a game and u decide that instead of a class responsibile for drawing/ticking the entities you want the code for tick/draw to be in the entity.</p>\n\n<p>implement IDrawable.draw() and ITickable.tick() ensures an entity can only ever be drawn/ticked when the game expects it to. Otherwise these methods wont ever be visible.</p>\n\n<p>Lesser bonus is when implementing multiple interfaces, explicit implementations let you work around cases where two interface method names collide.</p>\n" }, { "answer_id": 234647, "author": "dpurrington", "author_id": 5573, "author_profile": "https://Stackoverflow.com/users/5573", "pm_score": 2, "selected": false, "text": "<p>This is a bad idea because their usage breaks polymorphism. The type of the reference used should NOT vary the behavior of the object. If you want to ensure loose coupling, make the classes internal and use a DI technology (such as Spring.Net).</p>\n" }, { "answer_id": 238059, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 2, "selected": false, "text": "<p>There are no doubt certain advantages to forcing the users of your code to cast your objects to the interface types you want them to be using.</p>\n\n<p>But, on the whole, programming to an interface is a methodology or process issue. Programming to an interface is not going to be achieved merely by making your code annoying to the user.</p>\n" }, { "answer_id": 987796, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Another potential scenario for explicitly implementing an interface is when dealing with an existing class that already implements the functionality, but uses a different method name. For example, if your Knife class already had a method called Slice, you could implement the interface this way:</p>\n\n<pre><code>public class Knife : ICut\n{\n public void Slice()\n {\n // slice something\n }\n\n void ICut.Cut()\n {\n Slice();\n }\n}\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23855/" ]
I have seen arguments for using explicit interfaces as a method of locking a classes usage to that interface. The argument seems to be that by forcing others to program to the interface you can ensure better decoupling of the classes and allow easier testing. Example: ``` public interface ICut { void Cut(); } public class Knife : ICut { void ICut.Cut() { //Cut Something } } ``` And to use the Knife object: ``` ICut obj = new Knife(); obj.Cut(); ``` Would you recommend this method of interface implementation? Why or why not? EDIT: Also, given that I am using an explicit interface the following would NOT work. ``` Knife obj = new Knife(); obj.Cut(); ```
To quote GoF chapter 1: * "Program to an interface, not an implementation". * "Favor object composition over class inheritance". As C# does not have multiple inheritance, object composition and programming to interfaces are the way to go. ETA: And you should never use multiple inheritance anyway but that's another topic altogether.. :-) ETA2: I'm not so sure about the explicit interface. That doesn't seem constructive. Why would I want to have a Knife that can only Cut() if instansiated as a ICut?
178,837
<p>I am looking for a regex that will find repeating letters. So any letter twice or more, for example:</p> <pre><code>booooooot or abbott </code></pre> <p>I won't know the letter I am looking for ahead of time. </p> <p>This is a question I was asked in interviews and then asked in interviews. Not so many people get it correct.</p>
[ { "answer_id": 178851, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 3, "selected": false, "text": "<p>Use \\N to refer to previous groups:</p>\n\n<pre><code>/(\\w)\\1+/g\n</code></pre>\n" }, { "answer_id": 178854, "author": "Joseph Pecoraro", "author_id": 792, "author_profile": "https://Stackoverflow.com/users/792", "pm_score": 0, "selected": false, "text": "<p>How about:</p>\n\n<pre><code>(\\w)\\1+\n</code></pre>\n\n<p>The first part makes an unnamed group around a character, then the back-reference looks for that same character.</p>\n" }, { "answer_id": 178856, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 3, "selected": false, "text": "<p>I Think using a backreference would work:</p>\n\n<pre><code>(\\w)\\1+\n</code></pre>\n\n<p><code>\\w</code> is basically <code>[a-zA-Z_0-9]</code> so if you only want to match letters between A and Z (case insensitively), use <code>[a-zA-Z]</code> instead.</p>\n\n<p><em>(EDIT: or, like Tanktalus mentioned in his comment (and as others have answered as well),</em> <code>[[:alpha:]]</code><em>, which is locale-sensitive)</em></p>\n" }, { "answer_id": 178861, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 7, "selected": true, "text": "<p>You can find any letter, then use <code>\\1</code> to find that same letter a second time (or more). If you only need to know the letter, then <code>$1</code> will contain it. Otherwise you can concatenate the second match onto the first.</p>\n\n<pre><code>my $str = \"Foooooobar\";\n\n$str =~ /(\\w)(\\1+)/;\n\nprint $1;\n# prints 'o'\nprint $1 . $2;\n# prints 'oooooo'\n</code></pre>\n" }, { "answer_id": 178879, "author": "Keng", "author_id": 730, "author_profile": "https://Stackoverflow.com/users/730", "pm_score": 4, "selected": false, "text": "<p>I think you actually want this rather than the \"\\w\" as that includes numbers and the underscore.</p>\n\n<pre><code>([a-zA-Z])\\1+\n</code></pre>\n\n<p>Ok, ok, I can take a hint Leon. Use this for the unicode-world or for posix stuff.</p>\n\n<pre><code>([[:alpha:]])\\1+\n</code></pre>\n" }, { "answer_id": 179166, "author": "dland", "author_id": 18625, "author_profile": "https://Stackoverflow.com/users/18625", "pm_score": 2, "selected": false, "text": "<p>You might want to take care as to what is considered to be a letter, and this depends on your locale. Using ISO Latin-1 will allow accented Western language characters to be matched as letters. In the following program, the default locale doesn't recognise é, and thus <em>créé</em> fails to match. Uncomment the locale setting code, and then it begins to match.</p>\n\n<p>Also note that \\w includes digits and the underscore character along with all the letters. To get just the letters, you need to take the complement of the non-alphanum, digits and underscore characters. This leaves only letters.</p>\n\n<p>That might be easier to understand by framing it as the question: </p>\n\n<blockquote>\n <p>\"What regular expression matches any digit except 3?\"<br>\n The answer is:<br>\n <code>/[^\\D3]/</code></p>\n</blockquote>\n\n<pre><code>#! /usr/local/bin/perl\n\nuse strict;\nuse warnings;\n\n# uncomment the following three lines:\n# use locale;\n# use POSIX;\n# setlocale(LC_CTYPE, 'fr_FR.ISO8859-1');\n\nwhile (&lt;DATA&gt;) {\n chomp;\n if (/([^\\W_0-9])\\1+/) {\n print \"$_: dup [$1]\\n\";\n }\n else {\n print \"$_: nope\\n\";\n }\n}\n\n__DATA__\n100\nfood\ncréé\na::b\n</code></pre>\n" }, { "answer_id": 179679, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>The following code will return all the characters, that repeat two or more times:</p>\n\n<pre><code>my $str = \"SSSannnkaaarsss\";\n\nprint $str =~ /(\\w)\\1+/g;\n</code></pre>\n" }, { "answer_id": 179959, "author": "b w", "author_id": 4126, "author_profile": "https://Stackoverflow.com/users/4126", "pm_score": 1, "selected": false, "text": "<p>FYI, aside from RegExBuddy, a real handy free site for testing regular expressions is <a href=\"http://www.gskinner.com/RegExr/\" rel=\"nofollow noreferrer\">RegExr at gskinner.com</a>. Handles <code>([[:alpha:]])(\\1+)</code> nicely.</p>\n" }, { "answer_id": 181288, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 2, "selected": false, "text": "<p>Just for kicks, a completely different approach:</p>\n\n<pre><code>if ( ($str ^ substr($str,1) ) =~ /\\0+/ ) {\n print \"found \", substr($str, $-[0], $+[0]-$-[0]+1), \" at offset \", $-[0];\n}\n</code></pre>\n" }, { "answer_id": 6989255, "author": "karakays", "author_id": 877668, "author_profile": "https://Stackoverflow.com/users/877668", "pm_score": 0, "selected": false, "text": "<p>I think this should also work:</p>\n\n<p><code>((\\w)(?=\\2))+\\2</code></p>\n" }, { "answer_id": 10728308, "author": "Abdullah", "author_id": 605399, "author_profile": "https://Stackoverflow.com/users/605399", "pm_score": 0, "selected": false, "text": "<pre><code>/(.)\\\\1{2,}+/u\n</code></pre>\n\n<p>'u' modifier matching with unicode</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
I am looking for a regex that will find repeating letters. So any letter twice or more, for example: ``` booooooot or abbott ``` I won't know the letter I am looking for ahead of time. This is a question I was asked in interviews and then asked in interviews. Not so many people get it correct.
You can find any letter, then use `\1` to find that same letter a second time (or more). If you only need to know the letter, then `$1` will contain it. Otherwise you can concatenate the second match onto the first. ``` my $str = "Foooooobar"; $str =~ /(\w)(\1+)/; print $1; # prints 'o' print $1 . $2; # prints 'oooooo' ```
178,838
<p>Structs seem like a useful way to parse a binary blob of data (ie a file or network packet). This is fine and dandy until you have variable size arrays in the blob. For instance:</p> <pre><code>struct nodeheader{ int flags; int data_size; char data[]; }; </code></pre> <p>This allows me to find the last data character:</p> <pre><code>nodeheader b; cout &lt;&lt; b.data[b.data_size-1]; </code></pre> <p>Problem being, I want to have multiple variable length arrays:</p> <pre><code>struct nodeheader{ int friend_size; int data_size; char data[]; char friend[]; }; </code></pre> <p>I'm not manually allocating these structures. I have a file like so:</p> <pre><code>char file_data[1024]; nodeheader* node = &amp;(file_data[10]); </code></pre> <p>As I'm trying to parse a binary file (more specifically a class file). I've written an implementation in Java (which was my class assignment), no I'm doing a personal version in C++ and was hoping to get away without having to write 100 lines of code. Any ideas?</p> <p>Thanks, Stefan</p>
[ { "answer_id": 178877, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 3, "selected": true, "text": "<p>You cannot have multiple variable sized arrays. How should the compiler at compile time know where friend[] is located? The location of friend depends on the size of data[] and the size of data is unknown at compile time.</p>\n" }, { "answer_id": 178886, "author": "Douglas Leeder", "author_id": 3978, "author_profile": "https://Stackoverflow.com/users/3978", "pm_score": 1, "selected": false, "text": "<p>You can't - at least not in the simple way that you're attempting. The unsized array at the end of a structure is basically an offset to the end of the structure, with no build-in way to find the end.</p>\n\n<p>All the fields are converted to numeric offsets at compile time, so they need to be calculable at that time.</p>\n" }, { "answer_id": 178896, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "<p>This is a very dangerous construct, and I'd advise against it. You can only include a variable-length array in a struct when it is the LAST element, and when you do so, you have to make sure you allocate enough memory, e.g.:</p>\n\n<pre><code>nodeheader *nh = (nodeheader *)malloc(sizeof(nodeheader) + max_data_size);\n</code></pre>\n\n<p>What you want to do is just use regular dynamically allocated arrays:</p>\n\n<pre><code>struct nodeheader\n{\n char *data;\n size_t data_size;\n char *friend;\n size_t friend_size;\n};\n\nnodeheader AllocNodeHeader(size_t data_size, size_t friend_size)\n{\n nodeheader nh;\n nh.data = (char *)malloc(data_size); // check for NULL return\n nh.data_size = data_size;\n nh.friend = (char *)malloc(friend_size); // check for NULL return\n nh.friend_size = friend_size;\n\n return nh;\n}\n\nvoid FreeNodeHeader(nodeheader *nh)\n{\n free(nh-&gt;data);\n nh-&gt;data = NULL;\n free(nh-&gt;friend);\n nh-&gt;friend = NULL;\n}\n</code></pre>\n" }, { "answer_id": 178917, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": -1, "selected": false, "text": "<p>(Was 'Use std::vector')</p>\n\n<p>Edit: </p>\n\n<p>On reading feedback, I suppose I should expand my answer. You can effectively fit two variable length arrays in your structure as follows, and the storage will be freed for you automatically when file_data goes out of scope:</p>\n\n<pre><code>struct nodeheader {\n std::vector&lt;unsigned char&gt; data;\n std::vector&lt;unsigned char&gt; friend_buf; // 'friend' is a keyword!\n // etc...\n};\n\nnodeheader file_data;\n</code></pre>\n\n<p>Now file_data.data.size(), etc gives you the length and and &amp;file_data.data[0] gives you a raw pointer to the data if you need it.</p>\n\n<p>You'll have to fill file data from the file piecemeal - read the length of each buffer, call resize() on the destination vector, then read in the data. (There are ways to do this slightly more efficiently. In the context of disk file I/O, I'm assuming it doesn't matter).</p>\n\n<p>Incidentally OP's technique is incorrect even for his 'fine and dandy' cases, e.g. with only one VLA at the end.</p>\n\n<pre><code>char file_data[1024];\nnodeheader* node = &amp;(file_data[10]);\n</code></pre>\n\n<p>There's no guarantee that file_data is properly aligned for the nodeheader type. Prefer to obtain file_data by malloc() - which guarantees to return a pointer aligned for any type - or else (better) declare the buffer to be of the correct type in the first place:</p>\n\n<pre><code>struct biggestnodeheader {\n int flags;\n int data_size;\n char data[ENOUGH_SPACE_FOR_LARGEST_HEADER_I_EVER_NEED];\n};\n\nbiggestnodeheader file_data;\n// etc...\n</code></pre>\n" }, { "answer_id": 178998, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 0, "selected": false, "text": "<p>For what you are doing you need an encoder/decoder for the format. The decoder takes the raw data and fills out your structure (in your case allocating space for the copy of each section of the data), and the decoder writes raw binary. </p>\n" }, { "answer_id": 186263, "author": "Jim Buck", "author_id": 2666, "author_profile": "https://Stackoverflow.com/users/2666", "pm_score": 1, "selected": false, "text": "<p>The answers so far are seriously over-complicating a simple problem. Mecki is right about why it can't be done the way you are trying to do it, however you can do it very similarly:</p>\n\n<pre><code>struct nodeheader\n{\n int friend_size;\n int data_size;\n};\n\nstruct nodefile\n{\n nodeheader *header;\n char *data;\n char *friend;\n};\n\nchar file_data[1024];\n\n// .. file in file_data ..\n\nnodefile file;\nfile.header = (nodeheader *)&amp;file_data[0];\nfile.data = (char *)&amp;file.header[1];\nfile.friend = &amp;file.data[file-&gt;header.data_size];\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13257/" ]
Structs seem like a useful way to parse a binary blob of data (ie a file or network packet). This is fine and dandy until you have variable size arrays in the blob. For instance: ``` struct nodeheader{ int flags; int data_size; char data[]; }; ``` This allows me to find the last data character: ``` nodeheader b; cout << b.data[b.data_size-1]; ``` Problem being, I want to have multiple variable length arrays: ``` struct nodeheader{ int friend_size; int data_size; char data[]; char friend[]; }; ``` I'm not manually allocating these structures. I have a file like so: ``` char file_data[1024]; nodeheader* node = &(file_data[10]); ``` As I'm trying to parse a binary file (more specifically a class file). I've written an implementation in Java (which was my class assignment), no I'm doing a personal version in C++ and was hoping to get away without having to write 100 lines of code. Any ideas? Thanks, Stefan
You cannot have multiple variable sized arrays. How should the compiler at compile time know where friend[] is located? The location of friend depends on the size of data[] and the size of data is unknown at compile time.
178,846
<p>I installed the ReSharper evaluation version and uninstalled it. Afterwards Visual Studio's Intellisense stopped working. I have restarted computer but I still have this problem. </p> <p>Can anyone please help me here?</p> <p>I am using Visual Studio 2005. Thanks.</p>
[ { "answer_id": 178874, "author": "Matt Price", "author_id": 852, "author_profile": "https://Stackoverflow.com/users/852", "pm_score": 3, "selected": false, "text": "<p>Sometimes deleting the ncb file helps. Go to your solution directory and find the sln file, there will also be a file with the same name and the extension ncb. Make sure Visual Studio is closed (at least don't have that project open) and then delete that file. Don't worry Visual Studio will rebuild it for you.</p>\n" }, { "answer_id": 178893, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 6, "selected": true, "text": "<p>Try opening Visual Studio Command Prompt and entering:</p>\n\n<pre><code>devenv.exe /ResetSettings\n</code></pre>\n" }, { "answer_id": 178895, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 4, "selected": false, "text": "<p>Try going to Tools > Options > Text Editor > C# and checking all of the options under Statement completion. I think Resharper disables these upon installation.</p>\n" }, { "answer_id": 178951, "author": "Guy Starbuck", "author_id": 2194, "author_profile": "https://Stackoverflow.com/users/2194", "pm_score": 0, "selected": false, "text": "<p>I would try a \"repair\" on the installation first. Control Panel, Add/Remove Programs, select Microsoft Visual Studio 2005, click \"Change/Remove\". It will load up the install dialog and give you the option to do a \"repair\".</p>\n\n<p>YMMV, but at least it should reset a lot of the VS resources to their \"fresh\" state.</p>\n" }, { "answer_id": 1614916, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>devenv /ResetSettings worked after uninstalling ReSharper. I did not have to do a repair. I did verify that the settings were checked under Text Editor > C#, but ResetSettings was the only thing that worked.</p>\n" }, { "answer_id": 5961325, "author": "Simon", "author_id": 466704, "author_profile": "https://Stackoverflow.com/users/466704", "pm_score": 2, "selected": false, "text": "<p>The devenv.exe /ResetSettings was the only thing that worked for me. The full path in command prompt is as follows (for VS 2008)</p>\n\n<p>C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE>devenv.exe /ResetSettings</p>\n\n<p>took me a while to find so I thought I'd post this to help</p>\n" }, { "answer_id": 7568299, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>You could try to reset your Visual Studio setting by</p>\n\n<ol>\n<li>End Process devenv.exe from Tast Manager if it is running .(It can close your Browser and Visual Studio)</li>\n<li>Run devenv /resetuserdata from Start -> Run</li>\n</ol>\n\n<p>Hope It can help you.</p>\n" }, { "answer_id": 10261516, "author": "ivan40", "author_id": 891787, "author_profile": "https://Stackoverflow.com/users/891787", "pm_score": 1, "selected": false, "text": "<p>Disable updating intelliSense like in this article:\n<a href=\"http://amastaneh.blogspot.com/2007/11/disable-updating-intellisense.html\" rel=\"nofollow\">http://amastaneh.blogspot.com/2007/11/disable-updating-intellisense.html</a>\nEventhough for old version seems to work for me.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20933/" ]
I installed the ReSharper evaluation version and uninstalled it. Afterwards Visual Studio's Intellisense stopped working. I have restarted computer but I still have this problem. Can anyone please help me here? I am using Visual Studio 2005. Thanks.
Try opening Visual Studio Command Prompt and entering: ``` devenv.exe /ResetSettings ```
178,857
<p>Is it possible to get the text of an <code>OleDbCommand</code> with all parameters replaced with their values? E.g. in the code below I'm looking for a way to get the query text </p> <pre><code>SELECT * FROM my_table WHERE c1 = 'hello' and c2 = 'world' </code></pre> <p>after I finished assigning the parameters.</p> <pre><code>var query = "SELECT * FROM my_table WHERE c1 = ? and c2 = ?"; var cmd = new OleDbCommand(query, connection); cmd.Parameters.Add("@p1", OleDbType.WChar).Value = "hello"; cmd.Parameters.Add("@p2", OleDbType.WChar).Value = "world"; </code></pre>
[ { "answer_id": 178883, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": true, "text": "<p>No: you have to iterate through the parameters collection yourself, doing a string.Replace() to get the equivalent. It's particularly painful when you have to use the <code>?</code> syntax rather than the <code>@parametername</code> syntax.</p>\n\n<p>The reason for this is that the full string is <em>never</em> assembled. The parameters and sent to the server and treated as data, and are never included in the string.</p>\n\n<p>All the same, I for one understand your pain. It would have been nice if they included some kind of <code>.ComposeSQL()</code> method you could call <em>for debugging purposes</em>, that perhaps also produces a compiler warning to help avoid use in production.</p>\n" }, { "answer_id": 178900, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 2, "selected": false, "text": "<p>If you just need to see what query was executed and dont need to work with it programmatically, you can use SQL Profiler.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11387/" ]
Is it possible to get the text of an `OleDbCommand` with all parameters replaced with their values? E.g. in the code below I'm looking for a way to get the query text ``` SELECT * FROM my_table WHERE c1 = 'hello' and c2 = 'world' ``` after I finished assigning the parameters. ``` var query = "SELECT * FROM my_table WHERE c1 = ? and c2 = ?"; var cmd = new OleDbCommand(query, connection); cmd.Parameters.Add("@p1", OleDbType.WChar).Value = "hello"; cmd.Parameters.Add("@p2", OleDbType.WChar).Value = "world"; ```
No: you have to iterate through the parameters collection yourself, doing a string.Replace() to get the equivalent. It's particularly painful when you have to use the `?` syntax rather than the `@parametername` syntax. The reason for this is that the full string is *never* assembled. The parameters and sent to the server and treated as data, and are never included in the string. All the same, I for one understand your pain. It would have been nice if they included some kind of `.ComposeSQL()` method you could call *for debugging purposes*, that perhaps also produces a compiler warning to help avoid use in production.
178,860
<p>I'm trying to use a Microsoft Access database for a demo project that I'm thinking of doing in either CodeIgniter or CakePHP. Ignoring the possible folly of using Microsoft Access, I haven't been able to figure out precisely how the connection string corresponds to the frameworks' database settings. In straight PHP, I can use this code to connect to an Access database:</p> <pre><code>$db_connection = odbc_connect( "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=\\path\\to\\db.mdb", "ADODB.Connection", "", "SQL_CUR_USE_ODBC" ); </code></pre> <p>How do those strings correspond to the Code Igniter db settings? This doesn't seem to be quite working:</p> <pre><code>$db['access']['hostname'] = "{Microsoft Access Driver (*.mdb)}"; $db['access']['username'] = "ADODB.Connection"; $db['access']['password'] = ""; $db['access']['database'] = "\\path\\to\\db.mdb"; $db['access']['dbdriver'] = "odbc"; $db['access']['dbprefix'] = ""; $db['access']['pconnect'] = TRUE; $db['access']['db_debug'] = TRUE; $db['access']['cache_on'] = FALSE; $db['access']['cachedir'] = ""; $db['access']['char_set'] = "utf8"; $db['access']['dbcollat'] = "utf8_general_ci"; </code></pre>
[ { "answer_id": 260567, "author": "JayTee", "author_id": 20153, "author_profile": "https://Stackoverflow.com/users/20153", "pm_score": 3, "selected": true, "text": "<p>Try setting up a DSN and changing to the following:</p>\n\n<pre><code>$db['access']['hostname'] = \"&lt;dsn name&gt;\";\n$db['access']['username'] = \"\";\n$db['access']['password'] = \"\";\n$db['access']['database'] = \"&lt;dsn name&gt;\";\n</code></pre>\n\n<p>There's also a section in the CodeIgniter documentation that addresses connection strings:</p>\n\n<p><a href=\"http://codeigniter.com/user_guide/database/connecting.html\" rel=\"nofollow noreferrer\">http://codeigniter.com/user_guide/database/connecting.html</a></p>\n" }, { "answer_id": 260667, "author": "Adam", "author_id": 13320, "author_profile": "https://Stackoverflow.com/users/13320", "pm_score": 0, "selected": false, "text": "<p>Would it be possible to use the SQL Express (free!) engine instead and just import/export your MS Access db? You could thank me later on that. :-)</p>\n\n<p>Another option is to use the ADOdb library instead of CI's native DB library, though you'll lose the Active Record support from CI, and have to rewrite certain libraries in CI to utilize it, but it's worth it if you still want to use CI with a DB that isn't supported for your application. I had to do it early on when there was bugs in the Postgres implementation.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178860", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24197/" ]
I'm trying to use a Microsoft Access database for a demo project that I'm thinking of doing in either CodeIgniter or CakePHP. Ignoring the possible folly of using Microsoft Access, I haven't been able to figure out precisely how the connection string corresponds to the frameworks' database settings. In straight PHP, I can use this code to connect to an Access database: ``` $db_connection = odbc_connect( "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=\\path\\to\\db.mdb", "ADODB.Connection", "", "SQL_CUR_USE_ODBC" ); ``` How do those strings correspond to the Code Igniter db settings? This doesn't seem to be quite working: ``` $db['access']['hostname'] = "{Microsoft Access Driver (*.mdb)}"; $db['access']['username'] = "ADODB.Connection"; $db['access']['password'] = ""; $db['access']['database'] = "\\path\\to\\db.mdb"; $db['access']['dbdriver'] = "odbc"; $db['access']['dbprefix'] = ""; $db['access']['pconnect'] = TRUE; $db['access']['db_debug'] = TRUE; $db['access']['cache_on'] = FALSE; $db['access']['cachedir'] = ""; $db['access']['char_set'] = "utf8"; $db['access']['dbcollat'] = "utf8_general_ci"; ```
Try setting up a DSN and changing to the following: ``` $db['access']['hostname'] = "<dsn name>"; $db['access']['username'] = ""; $db['access']['password'] = ""; $db['access']['database'] = "<dsn name>"; ``` There's also a section in the CodeIgniter documentation that addresses connection strings: <http://codeigniter.com/user_guide/database/connecting.html>
178,863
<p>I am building a product that we are eventually going to white-label. Right now I am trying to figure out the best way to facilitate these requirements programmatically so the user can update the basic design of the site (ie header color, etc) via their profile/settings form. </p> <p>Requirements: </p> <ol> <li>User can update the logo (this is complete)</li> <li>User can update basic design elements (based on CSS), ie header color, footer color, sidebar color - all basic CSS overrides</li> </ol> <p>We don't want to use ASP.Net Themes/Skins because that requires storing static themes in the local file system. We would like to use CSS to override the base style and store this in the database.</p> <p>Our initial plan is to store the CSS in a simple varchar field in the database and write that CSS out to the Master Page on Pre-Init event using "!" to override the base styles. Is this the best solution? If not, what have you done to accomplish this functionality/</p>
[ { "answer_id": 178878, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "<p>Your proposed method is how I would go about solving this problem: upload the user-controllable values (maybe just colors and font sizes) into a table linked to the user.</p>\n\n<p>The logo/avatar you want the user to have can be stored in the db or as a file on the fs.</p>\n" }, { "answer_id": 178891, "author": "y0mbo", "author_id": 417, "author_profile": "https://Stackoverflow.com/users/417", "pm_score": -1, "selected": false, "text": "<p>I would avoid using the !important clause and instead just ensure their values appear in a <code>&lt;style&gt;</code> tag following the import of the regular style sheets.</p>\n\n<p>Otherwise, I would do it the same way.</p>\n" }, { "answer_id": 178949, "author": "Travis Illig", "author_id": 8116, "author_profile": "https://Stackoverflow.com/users/8116", "pm_score": 0, "selected": false, "text": "<p>I think it depends on how savvy your users are about CSS. If they're web developers or have that inclination, having them write CSS is probably fine. If not, you'll either have to generate it statically based on their input and store it in the database OR you can just store the values entered and dynamically generate the CSS using a custom handler.</p>\n\n<p>The custom handler approach would mean you could substitute values right in the middle of the CSS without having to worry about !important or the order in which the items are declared to ensure proper overrides happen.</p>\n" }, { "answer_id": 178960, "author": "Paddy Callaghan", "author_id": 17415, "author_profile": "https://Stackoverflow.com/users/17415", "pm_score": 0, "selected": false, "text": "<p>With php for example you can create dynamic css, so this coupled with the user information stored in a db would surely suffice.</p>\n\n<p>Try <a href=\"http://www.digital-web.com/articles/generating_dynamic_css_with_php/\" rel=\"nofollow noreferrer\">here</a> or <a href=\"http://www.barelyfitz.com/projects/csscolor/\" rel=\"nofollow noreferrer\">here</a> as an introduction.</p>\n" }, { "answer_id": 179001, "author": "Mr. Shiny and New 安宇", "author_id": 7867, "author_profile": "https://Stackoverflow.com/users/7867", "pm_score": 2, "selected": false, "text": "<p>First, determine which resources can be replaced, and whether or not resources can be added. You will need to store these somewhere; for small resources such as logos the db is probably fine, otherwise you need to worry about the size in the db.</p>\n\n<p>Then you can determine how much functionality you want the user to customize: just colours, or entire styles? If it's just colours, you can define some variables in a CSS file and serve the file dynamically, with data loaded from the db. The CSS file might be called styles.asp and contain code such as this:</p>\n\n<pre><code>.header_area {\n border: 1px solid &lt;%=headerBorderColor%&gt;;\n background-color: &lt;%=headerBGColor%&gt;;\n foreground-color: &lt;%=headerFGColor%&gt;;\n}\n</code></pre>\n\n<p>(The syntax I used is JSP syntax, I don't know ASP, but the idea is the same.)</p>\n\n<p>Alternatively, allow the user to specify an entire stylesheet, either replacing the default one or supplementing it. Then store the entire sheet in the DB and serve it using its own URL (don't embed it in the page).</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"default_styles.css\"&gt;\n&lt;link rel=\"stylesheet\" href=\"white_label_css.asp\"&gt;\n</code></pre>\n\n<p>Make sure you set the cache headers and content type appropriately on the css file if you serve it using an asp page.</p>\n\n<p>If you are concerned about what kind of content the user can put in the white_label_css file, you can limit it by making a custom tool which generates the css and stores it in the db. For example, instead of allowing the user to upload any file and store it in the db, the user would have to fill out a web-form detailing what customizations they want to make. This way you can ensure that only certain css rules/changes are allowed (but that may not be flexible enough).</p>\n" }, { "answer_id": 179012, "author": "questzen", "author_id": 25210, "author_profile": "https://Stackoverflow.com/users/25210", "pm_score": 0, "selected": false, "text": "<p>If I understood correctly, you want to facilitate color and typography related changes. What about layout? If we safely assume that only color and typography are going to change, we can reuse the same style classes at the end of existing base CSS file and thus override the styles (using !important though a good idea, prevents users from overriding with their custom styles).</p>\n\n<p>These newly created classes can be compressed to a single line string and stored as a varchar, which would then be linked/copied inline while building the page. I can think of the following options</p>\n\n<ol>\n<li>Inline CSS</li>\n<li>Create a file partition where you can dump the generated CSS files and let browsers refer to that location (by creating a softlink?)</li>\n<li>Use Ajax, retrieve the CSS and modify the DOM</li>\n</ol>\n\n<p>If layout is going to change, we are in a thicker soup, I would avoid this as the complexities involved with scripting/event-handling are way too much.</p>\n" }, { "answer_id": 179216, "author": "Andy Brudtkuhl", "author_id": 12442, "author_profile": "https://Stackoverflow.com/users/12442", "pm_score": 1, "selected": false, "text": "<p>I like the idea of using dynamic CSS using an ASP.Net Handler...</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"style.ashx\" /&gt;\n</code></pre>\n\n<p><strong>style.ashx</strong></p>\n\n<pre><code>&lt;!--WebHandler Language=\"C#\" Class=\"StyleSheetHandler\"--&gt;\n</code></pre>\n\n<p><strong>StyleSheetHandler.cs</strong></p>\n\n<pre><code>public class StyleSheetHandler : IHttpHandler {\n public void ProcessRequest (HttpContext context)\n { \n context.Response.ContentType = \"text/css\";\n context.Response.ContentEncoding = System.Text.Encoding.UTF8;\n\n string css = BuildCSSString(); //not showing this function\n\n context.Response.Cache.SetExpires(DateTime.Now.AddSeconds(600));\n context.Response.Cache.SetCacheability(HttpCacheability.Public);\n context.Response.Write( css );\n }\n\n public bool IsReusable\n {\n get { return true; }\n }\n\n}\n</code></pre>\n\n<p>The BuildCSSString() Function will build the css based on the values stored in the database and return it to override the base style on the master page.</p>\n" }, { "answer_id": 180696, "author": "lbz", "author_id": 11530, "author_profile": "https://Stackoverflow.com/users/11530", "pm_score": 3, "selected": false, "text": "<p>I've been there some months ago. While using dynamic CSS generated by a dedicated handler / servlet has been the first solution, to improve performances a customized CSS is now produced on file overrinding the basic elements of the standard CSS:</p>\n\n<pre><code>&lt;link rel=\"stylesheet\" href=\"standard.css\" /&gt;\n&lt;link rel=\"stylesheet\" href=\"&lt;%= customer_code %&gt;/custom_style.css\" /&gt;\n...\n&lt;img scr=\"&lt;%= customer_code %&gt;/logo.png\" /&gt;\n</code></pre>\n\n<p>Each custom CSS will have its own URL, so you can make the browser caching them.</p>\n\n<p>This will make you saving <strong>for each request</strong> the users will make:</p>\n\n<ol>\n<li>traffic from the database to the application layer</li>\n<li>traffic from the application layer to the browser</li>\n<li>some computing at the application layer</li>\n</ol>\n\n<p>I'll second the idea the user should have to fill out a web-form detailing what customizations they want to make.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12442/" ]
I am building a product that we are eventually going to white-label. Right now I am trying to figure out the best way to facilitate these requirements programmatically so the user can update the basic design of the site (ie header color, etc) via their profile/settings form. Requirements: 1. User can update the logo (this is complete) 2. User can update basic design elements (based on CSS), ie header color, footer color, sidebar color - all basic CSS overrides We don't want to use ASP.Net Themes/Skins because that requires storing static themes in the local file system. We would like to use CSS to override the base style and store this in the database. Our initial plan is to store the CSS in a simple varchar field in the database and write that CSS out to the Master Page on Pre-Init event using "!" to override the base styles. Is this the best solution? If not, what have you done to accomplish this functionality/
I've been there some months ago. While using dynamic CSS generated by a dedicated handler / servlet has been the first solution, to improve performances a customized CSS is now produced on file overrinding the basic elements of the standard CSS: ``` <link rel="stylesheet" href="standard.css" /> <link rel="stylesheet" href="<%= customer_code %>/custom_style.css" /> ... <img scr="<%= customer_code %>/logo.png" /> ``` Each custom CSS will have its own URL, so you can make the browser caching them. This will make you saving **for each request** the users will make: 1. traffic from the database to the application layer 2. traffic from the application layer to the browser 3. some computing at the application layer I'll second the idea the user should have to fill out a web-form detailing what customizations they want to make.
178,876
<p>In this asp.net I'm cleaning up it's possible for deadlocks to occur. I want to make sure that the code deals with them properly, so I'm trying to write NUnit tests which trigger a deadlock.....</p> <p>The DAO is split by entity. Each entity has a set of tests which are surrounded by Startup() and Teardown() methods which create a transactionscope and then roll it back after the tests are complete. This works great for everything else, but is completely useless for deadlocks.</p> <p>How can I setup and run a "deadlock" test using TransactionScope and SQL2000 (ie MSDTC is involved) that can be reliably reproduced? More detail: I know there is a situation whereby if two users call two functions with different, specific, data values then a deadlock <em>can</em> result. How can I simulate this within NUNIT - and make the deadlock <em>always</em> happen?</p> <p>And yes, I did start with the "Why don't you stop the deadlocks happening in the first place" plan of action, but I have no control over the code where the deadlocks can occur - I just call the functions and they can deadlock.</p>
[ { "answer_id": 178986, "author": "Nick DeVore", "author_id": 1380, "author_profile": "https://Stackoverflow.com/users/1380", "pm_score": 0, "selected": false, "text": "<p>What if one of your tests in the middle of your transaction just does a \"wait\" for like 5 minutes? Or, you simply write a test that starts a transaction, creates a new record, and then updates that record without committing. Then, start a new transaction in and try to read that record that was created and is currently being updated. You'll get a deadlock there.</p>\n" }, { "answer_id": 179051, "author": "Nick DeVore", "author_id": 1380, "author_profile": "https://Stackoverflow.com/users/1380", "pm_score": 0, "selected": false, "text": "<p>What if you manually locked a table and ALWAYS left it locked? Then, any action you took against that table would produce a deadlock situation?</p>\n" }, { "answer_id": 179278, "author": "Nick DeVore", "author_id": 1380, "author_profile": "https://Stackoverflow.com/users/1380", "pm_score": 0, "selected": false, "text": "<p>Coming at this blind, but is it possible to in your TestSetup method to actually create a SQLConnection to your database? Then, using that, you could just issue either a command to lock the table or take some action to lock a record or page? That way it would be outside of any other transactions you've got going on? It seems like this would be an option you've already considered though. What am I missing about your situation?</p>\n" }, { "answer_id": 185025, "author": "Josh Kodroff", "author_id": 549, "author_profile": "https://Stackoverflow.com/users/549", "pm_score": 3, "selected": true, "text": "<p>If your deadlock results in an exception being thrown, you want to use a Mock Object to emulate the exception being thrown.</p>\n\n<p>The basic idea is that you tell your Mock Object framework (I like <a href=\"http://www.typemock.com/\" rel=\"nofollow noreferrer\">TypeMock</a>) to throw an exception instead, something like this:</p>\n\n<pre><code>MockObject mo = MockManager.MockObject(typeof(MyDeadlockException));\nmock.ExpectAndThrow(\"MyMethod\", (MyDeadlockException)mo.Object); \n</code></pre>\n\n<p>The idea is basically the same for other mocking frameworks.</p>\n" }, { "answer_id": 185549, "author": "Brody", "author_id": 17131, "author_profile": "https://Stackoverflow.com/users/17131", "pm_score": 0, "selected": false, "text": "<p>For unit testing you probably want to avoid actually using a database. How do you know you have a deadlock. You should be testing the condition that tells you there is a deadlock and creating that in your test. </p>\n\n<p>A mock is an ideal whay to mimic that if you call a service and it returns an error. Simply have the mock return the error you are expecting. If you are waiting for a timeout or something then the same thing applies.</p>\n\n<p>In general a unit test should only run on the code being tested and not rely on any other code or components. That said - databases are essentially another component and you are probably doing some sort of functional tests using nunit to drive them. </p>\n\n<p>In that case you really have to create a deadlock situation but locking a record, or table and then calling a component that tries to use the same record and handling the response.</p>\n" }, { "answer_id": 190003, "author": "Pittsburgh DBA", "author_id": 10224, "author_profile": "https://Stackoverflow.com/users/10224", "pm_score": 1, "selected": false, "text": "<p>Most of these solutions involve multiple threads. Here is one that does not.</p>\n\n<p><a href=\"http://www.simple-talk.com/sql/t-sql-programming/close-these-loopholes---reproduce-database-errors/\" rel=\"nofollow noreferrer\">Close these Loopholes - Reproduce Database Errors</a></p>\n\n<p>The author is Alex Kuznetsov.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6969/" ]
In this asp.net I'm cleaning up it's possible for deadlocks to occur. I want to make sure that the code deals with them properly, so I'm trying to write NUnit tests which trigger a deadlock..... The DAO is split by entity. Each entity has a set of tests which are surrounded by Startup() and Teardown() methods which create a transactionscope and then roll it back after the tests are complete. This works great for everything else, but is completely useless for deadlocks. How can I setup and run a "deadlock" test using TransactionScope and SQL2000 (ie MSDTC is involved) that can be reliably reproduced? More detail: I know there is a situation whereby if two users call two functions with different, specific, data values then a deadlock *can* result. How can I simulate this within NUNIT - and make the deadlock *always* happen? And yes, I did start with the "Why don't you stop the deadlocks happening in the first place" plan of action, but I have no control over the code where the deadlocks can occur - I just call the functions and they can deadlock.
If your deadlock results in an exception being thrown, you want to use a Mock Object to emulate the exception being thrown. The basic idea is that you tell your Mock Object framework (I like [TypeMock](http://www.typemock.com/)) to throw an exception instead, something like this: ``` MockObject mo = MockManager.MockObject(typeof(MyDeadlockException)); mock.ExpectAndThrow("MyMethod", (MyDeadlockException)mo.Object); ``` The idea is basically the same for other mocking frameworks.
178,888
<p>This is a minor bug (one I'm willing to live with in the interest of go-live, frankly), but I'm wondering if anyone else has ideas to fix it.</p> <p>I have a C# WinForms application. When the app is launched via the executable (not via the debugger), the first thing the user sees is a console window, followed by the main window (after pre-loading is complete.)</p> <p>I'd like to not display the console window. (Like I said, it's a minor bug.)</p> <p>The project output is already set to Windows Application.</p> <p>Here's (most of) the code for the Main() method. I've snipped out various proprietary/security related stuff, replacing it with comments where appropriate.</p> <pre><code>[STAThread] static void Main() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // SNIP: Get username from Windows, associate with DB user if (user == null || user.UID == 0 || (user.Active.HasValue &amp;&amp; !(user.Active.Value))) { MessageBox.Show(ErrorStrings.UnknownUser, ErrorStrings.TitleBar, MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); return; } // SNIP: Associate user with employee object Application.Run(new MainForm()); } catch (Exception ex) { if (ExceptionPolicy.HandleException(ex, UiStrings.ExceptionPolicy)) { string message = ErrorStrings.UnhandledPreface + ex.ToString(); MessageBox.Show(message, ErrorStrings.TitleBar, MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } } } </code></pre> <p>Anyone have any ideas?</p>
[ { "answer_id": 178923, "author": "Nick", "author_id": 22407, "author_profile": "https://Stackoverflow.com/users/22407", "pm_score": 3, "selected": true, "text": "<p>My first guess would be to double check your Project Property settings and make sure that the output type is Windows Application and not Console Application.</p>\n" }, { "answer_id": 178929, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 1, "selected": false, "text": "<p>If you navigate to the Properties tabs for your project in Visual Studio, you should be able to set the output type to Windows Application. It sounds like it may be set to Console Application currently.</p>\n" }, { "answer_id": 178955, "author": "Stephen Deken", "author_id": 7154, "author_profile": "https://Stackoverflow.com/users/7154", "pm_score": 1, "selected": false, "text": "<p>As above, check to make sure that your project's properties are set to Windows Application instead of Console Application. If that's not the issue, then a component of your application might be manually creating a console window using the Win32 API call <code>AllocConsole()</code>, or you might be launching a command-line application in the background without using <code>UseShellExecute=false; CreateNoWindow=true;</code> in your StartInfo.</p>\n" }, { "answer_id": 179037, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "<p>Take a backup of your code and then hack at it, removing everything unrelated to this issue. In other words, have a cycle of \"remove code, get it to build, run it and see if the console still pops up.\" Eventually you should end up either spotting the issue or being able to post a short but complete program so that we can reproduce it and help fix it.</p>\n" }, { "answer_id": 179084, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 2, "selected": false, "text": "<p>I found it. </p>\n\n<p>When the project is built in Visual Studio, there are no problems -- no console window.</p>\n\n<p>When the project is built from CruiseControl, that's when we get a console window.</p>\n\n<p>The difference? Visual Studio (based on my election of a WinForms app) is appending /target:winexe to the csc line.</p>\n\n<p>CruiseControl calls a series of NAnt scripts. In the source.build script, the compile step is misconfigured, and is targeting exe instead of winexe -- the equivalent of selecting \"Console App\" in VS. Thus, a console window on release builds vs. debug builds.</p>\n\n<p>Relevant NAnt:</p>\n\n<pre><code>&lt;csc output=\"${build.outputPath}\\[myapp].exe\" target=\"winexe\" debug=\"Full\" rebuild=\"true\"&gt;\n &lt;!-- lots of references, sources and resources --&gt;\n&lt;/csc&gt;\n</code></pre>\n\n<p>Yeah, now I feel dumb. :)</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14048/" ]
This is a minor bug (one I'm willing to live with in the interest of go-live, frankly), but I'm wondering if anyone else has ideas to fix it. I have a C# WinForms application. When the app is launched via the executable (not via the debugger), the first thing the user sees is a console window, followed by the main window (after pre-loading is complete.) I'd like to not display the console window. (Like I said, it's a minor bug.) The project output is already set to Windows Application. Here's (most of) the code for the Main() method. I've snipped out various proprietary/security related stuff, replacing it with comments where appropriate. ``` [STAThread] static void Main() { try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // SNIP: Get username from Windows, associate with DB user if (user == null || user.UID == 0 || (user.Active.HasValue && !(user.Active.Value))) { MessageBox.Show(ErrorStrings.UnknownUser, ErrorStrings.TitleBar, MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); return; } // SNIP: Associate user with employee object Application.Run(new MainForm()); } catch (Exception ex) { if (ExceptionPolicy.HandleException(ex, UiStrings.ExceptionPolicy)) { string message = ErrorStrings.UnhandledPreface + ex.ToString(); MessageBox.Show(message, ErrorStrings.TitleBar, MessageBoxButtons.OK, MessageBoxIcon.Error); Application.Exit(); } } } ``` Anyone have any ideas?
My first guess would be to double check your Project Property settings and make sure that the output type is Windows Application and not Console Application.
178,898
<p>I have a program that uses the built in webbrowser control. At some point during the usage of this, I'm not sure at what point, but it appears to be random, I get the following error:</p> <pre><code>System.AccessViolationException FullText = System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG&amp; msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) </code></pre> <p>Does anyone have any clues as to why I would get this and how to prevent it?</p>
[ { "answer_id": 178972, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 2, "selected": false, "text": "<p>My gut feeling is that you are trying to manipulate the document before you've navigated to one. Try navigating to \"about:blank\" before changing the document text or html.</p>\n\n<p>If you already are performing navigation, note that navigation is asynchronous, so you need to monitor the events of the browser in order to detect when the navigation is complete. Otherwise, you may try to write to the document before it exists.</p>\n" }, { "answer_id": 185182, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 1, "selected": false, "text": "<p>We're hitting this too. Inconsistently, we'll get this exception.</p>\n\n<p>Some questions to help narrow this down: are you using any mshtml interfaces directly (e.g. mshtml.dll)? Doing any COM interop directly?</p>\n\n<p>We've found that calling some of the COM MSHTML interfaces incorrectly can cause this.</p>\n\n<p>We've also found that doing COM marshalling incorrectly can cause this.</p>\n\n<p>If there's a bug in the MSHTML interface import that the built-in WebBrowser uses, it can cause this.</p>\n\n<p>Accessing document IFRAME Elements from another domain can cause this.</p>\n\n<p>It's possible that making WebBrowser calls when the document isn't quite ready may also cause this.</p>\n" }, { "answer_id": 189210, "author": "Kevin Dark", "author_id": 26151, "author_profile": "https://Stackoverflow.com/users/26151", "pm_score": 0, "selected": false, "text": "<p>Just a suggestion, I'm no expert on this but have used the WebBrowser a lot in previous applications, but why dont you write a function to wait 1 second before attempting to pass the browser anything and always check the readystate beforehand aswell.\nMight slow it down a bit but it should make it bullet proof. :)</p>\n" }, { "answer_id": 193542, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 0, "selected": false, "text": "<p>Are the pages you are navigating to hosting any ActiveX controls? If yes, one of those may be flawed. Also check your pages in IE. See if they crash the same way. That will help isolate if it's specific to the content or the browser control.</p>\n" }, { "answer_id": 643539, "author": "Aaron Smith", "author_id": 12969, "author_profile": "https://Stackoverflow.com/users/12969", "pm_score": 0, "selected": false, "text": "<p>I ended up just opening up the webpage in the browser. That way I don't even have to worry about this. It's still strange that it throws this error though.</p>\n" }, { "answer_id": 1920554, "author": "Darkmage", "author_id": 173728, "author_profile": "https://Stackoverflow.com/users/173728", "pm_score": 0, "selected": false, "text": "<p>This seems to be a Vista Issue, what happend to me was that my C# webBrowser1 opend a web page that runned a java applet that opend a external IE webpage that runs a ActiveX app/script. </p>\n\n<p>When the ActiveX script tryes to update back in to the memory of the C# app the DEP \"Data Execution Prevention\" in Vista flags this operation as hostile/virus and ends the program with the System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.\"</p>\n\n<p>My fix for this was to turn of DEP in Vista with this line in cmd</p>\n\n<pre><code>\"bcdedit.exe /set {current} nx AlwaysOff\"\n</code></pre>\n\n<p>and reboot the machine.</p>\n\n<p>XP also run DEP so in certain cases i guess this cold happen here too.\nTo test if its a DEP issue do this.</p>\n\n<p>Right click on \"My Computer\"\nSelect \"Properties\" and \"Advanced\"\nUnder \"Startup and Recovery, click Settings\nNow click on \"Edit\"\nThe notepad has just begun. Simply replace the line:\nCode:\n noexecute optionn by AlwaysOff\nRestart your PC to complete the transaction.</p>\n\n<p>If you want to reactivate the DEP be sufficient to conduct the reverse, like this:</p>\n\n<p>Replace by\nQuote:\n AlwaysOff noexecute = noexecute = optin </p>\n" }, { "answer_id": 5223166, "author": "Filip Navara", "author_id": 156063, "author_profile": "https://Stackoverflow.com/users/156063", "pm_score": 3, "selected": false, "text": "<p>We have recently had a similar problem on the machines of several customers. The problem turned out to be a bug in the MSHTML control in certain environments. A common symptom for the problem seems to be the broken registration of the jscript.dll library.</p>\n<p>Symptoms that may help to diagnose if it's the same problem - the jscript.dll is not listed in Modules in the debugger and is not loaded by the process; Native stack trace for the crash is the following:</p>\n<pre><code>mshtml!CRootTracker::CollectGarbageInternal+0xd\nmshtml!CDoc::ReduceMemoryPressureTask+0x29\nmshtml!CStackPtrAry&lt;unsigned long,12&gt;::GetStackSize+0xb6\nmshtml!GlobalWndProc+0x183\nUSER32!InternalCallWinProc+0x23\nUSER32!UserCallWinProcCheckWow+0x109\nUSER32!DispatchMessageWorker+0x3bc\nUSER32!DispatchMessageW+0xf\n</code></pre>\n<p>The solution is to re-register the jscript.dll library and the crash should go away.</p>\n<p>Re-registering the library is done as follows (example given for 64-bit Windows, otherwise only the first line is necessary):</p>\n<pre><code>C:\\Windows\\System32\\regsvr32.exe C:\\Windows\\System32\\jscript.dll\nC:\\Windows\\SysWOW64\\regsvr32.exe C:\\Windows\\SysWOW64\\jscript.dll\n</code></pre>\n<p>Both commands have to be &quot;Run as Administrator&quot;.</p>\n" }, { "answer_id": 6566190, "author": "Jacotb", "author_id": 738311, "author_profile": "https://Stackoverflow.com/users/738311", "pm_score": 2, "selected": false, "text": "<p>I encountered this exception at various occasions while trying to access WebBrowser.ReadyState and WebBrowser.Document.</p>\n\n<p>I was having the exceptions exclusively on Windows XP 32bit. After the other solutions didn't help, it appeared to be a threading issue. I surrounded any code blocks that accessed the web browser control with mutex locks, and that seemed to solve the problem.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12969/" ]
I have a program that uses the built in webbrowser control. At some point during the usage of this, I'm not sure at what point, but it appears to be random, I get the following error: ``` System.AccessViolationException FullText = System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) ``` Does anyone have any clues as to why I would get this and how to prevent it?
We have recently had a similar problem on the machines of several customers. The problem turned out to be a bug in the MSHTML control in certain environments. A common symptom for the problem seems to be the broken registration of the jscript.dll library. Symptoms that may help to diagnose if it's the same problem - the jscript.dll is not listed in Modules in the debugger and is not loaded by the process; Native stack trace for the crash is the following: ``` mshtml!CRootTracker::CollectGarbageInternal+0xd mshtml!CDoc::ReduceMemoryPressureTask+0x29 mshtml!CStackPtrAry<unsigned long,12>::GetStackSize+0xb6 mshtml!GlobalWndProc+0x183 USER32!InternalCallWinProc+0x23 USER32!UserCallWinProcCheckWow+0x109 USER32!DispatchMessageWorker+0x3bc USER32!DispatchMessageW+0xf ``` The solution is to re-register the jscript.dll library and the crash should go away. Re-registering the library is done as follows (example given for 64-bit Windows, otherwise only the first line is necessary): ``` C:\Windows\System32\regsvr32.exe C:\Windows\System32\jscript.dll C:\Windows\SysWOW64\regsvr32.exe C:\Windows\SysWOW64\jscript.dll ``` Both commands have to be "Run as Administrator".
178,899
<p>I have a collection of classes that I want to serialize out to an XML file. It looks something like this:</p> <pre><code>public class Foo { public List&lt;Bar&gt; BarList { get; set; } } </code></pre> <p>Where a bar is just a wrapper for a collection of properties, like this:</p> <pre><code>public class Bar { public string Property1 { get; set; } public string Property2 { get; set; } } </code></pre> <p>I want to mark this up so that it outputs to an XML file - this will be used for both persistence, and also to render the settings via an XSLT to a nice human-readable form. </p> <p>I want to get a nice XML representation like this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Foo&gt; &lt;BarList&gt; &lt;Bar&gt; &lt;Property1&gt;Value&lt;/Property1&gt; &lt;Property2&gt;Value&lt;/Property2&gt; &lt;/Bar&gt; &lt;Bar&gt; &lt;Property1&gt;Value&lt;/Property1&gt; &lt;Property2&gt;Value&lt;/Property2&gt; &lt;/Bar&gt; &lt;/Barlist&gt; &lt;/Foo&gt; </code></pre> <p>where are all of the Bars in the Barlist are written out with all of their properties. I'm fairly sure that I'll need some markup on the class definition to make it work, but I can't seem to find the right combination.</p> <p>I've marked Foo with the attribute </p> <pre><code>[XmlRoot("Foo")] </code></pre> <p>and the <code>list&lt;Bar&gt;</code> with the attribute</p> <pre><code>[XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName="Bar")] </code></pre> <p>in an attempt to tell the Serializer what I want to happen. This doesn't seem to work however and I just get an empty tag, looking like this:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Foo&gt; &lt;Barlist /&gt; &lt;/Foo&gt; </code></pre> <p>I'm not sure if the fact I'm using Automatic Properties should have any effect, or if the use of generics requires any special treatment. I've gotten this to work with simpler types like a list of strings, but a list of classes so far eludes me.</p>
[ { "answer_id": 178931, "author": "Carl", "author_id": 951280, "author_profile": "https://Stackoverflow.com/users/951280", "pm_score": 6, "selected": true, "text": "<p>Just to check, have you marked Bar as [Serializable]?</p>\n\n<p>Also, you need a parameter-less ctor on Bar, to deserialize</p>\n\n<p>Hmm, I used:</p>\n\n<pre><code>public partial class Form1 : Form\n{\n public Form1()\n {\n InitializeComponent();\n }\n\n private void button1_Click(object sender, EventArgs e)\n {\n\n Foo f = new Foo();\n\n f.BarList = new List&lt;Bar&gt;();\n\n f.BarList.Add(new Bar { Property1 = \"abc\", Property2 = \"def\" });\n\n XmlSerializer ser = new XmlSerializer(typeof(Foo));\n\n using (FileStream fs = new FileStream(@\"c:\\sertest.xml\", FileMode.Create))\n {\n ser.Serialize(fs, f);\n }\n }\n}\n\npublic class Foo\n{\n [XmlArray(\"BarList\"), XmlArrayItem(typeof(Bar), ElementName = \"Bar\")]\n public List&lt;Bar&gt; BarList { get; set; }\n}\n\n[XmlRoot(\"Foo\")]\npublic class Bar\n{\n public string Property1 { get; set; }\n public string Property2 { get; set; }\n}\n</code></pre>\n\n<p>And that produced:</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;Foo xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"&gt;\n &lt;BarList&gt;\n &lt;Bar&gt;\n &lt;Property1&gt;abc&lt;/Property1&gt;\n &lt;Property2&gt;def&lt;/Property2&gt;\n &lt;/Bar&gt;\n &lt;/BarList&gt;\n&lt;/Foo&gt;\n</code></pre>\n" }, { "answer_id": 178994, "author": "FryHard", "author_id": 231, "author_profile": "https://Stackoverflow.com/users/231", "pm_score": 2, "selected": false, "text": "<p>Everything looks great. As @Carl said you need to add the <strong>[Serializable]</strong> attibute to your classes, but other than that your XML creation should work find.</p>\n\n<p><strong>Foo</strong></p>\n\n<pre><code>[Serializable]\n[XmlRoot(\"Foo\")]\npublic class Foo\n{\n [XmlArray(\"BarList\"), XmlArrayItem(typeof(Bar), ElementName = \"Bar\")]\n public List&lt;Bar&gt; BarList { get; set; }\n}\n</code></pre>\n\n<p><strong>Bar</strong></p>\n\n<pre><code>[Serializable]\npublic class Bar\n{\n public string Property1 { get; set; }\n public string Property2 { get; set; }\n}\n</code></pre>\n\n<p><strong>Code to test</strong></p>\n\n<pre><code>Foo f = new Foo();\nf.BarList = new List&lt;Bar&gt;();\nf.BarList.Add(new Bar() { Property1 = \"s\", Property2 = \"2\" });\nf.BarList.Add(new Bar() { Property1 = \"s\", Property2 = \"2\" });\n\nFileStream fs = new FileStream(\"c:\\\\test.xml\", FileMode.OpenOrCreate);\nSystem.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(typeof(Foo));\ns.Serialize(fs, f);\n</code></pre>\n\n<p><strong>Output</strong></p>\n\n<pre><code>&lt;?xml version=\"1.0\" ?&gt; \n&lt;Foo xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"&gt;\n &lt;BarList&gt;\n &lt;Bar&gt;\n &lt;Property1&gt;s&lt;/Property1&gt; \n &lt;Property2&gt;2&lt;/Property2&gt; \n &lt;/Bar&gt;\n &lt;Bar&gt;\n &lt;Property1&gt;s&lt;/Property1&gt; \n &lt;Property2&gt;2&lt;/Property2&gt; \n &lt;/Bar&gt;\n &lt;/BarList&gt;\n&lt;/Foo&gt;\n</code></pre>\n" }, { "answer_id": 17980727, "author": "Peter Klein", "author_id": 1679936, "author_profile": "https://Stackoverflow.com/users/1679936", "pm_score": 1, "selected": false, "text": "<p>It has been over 5 years since this item was posted. I give my experience from July 2013 (.NET Framework 4.5). For what it's worth and to whom it may concern:</p>\n\n<p>When I define a class like so: (VB.Net code)</p>\n\n<pre><code>&lt;Serializable&gt; Public Class MyClass\n Public Property Children as List(of ChildCLass)\n &lt;XmlAttribute&gt; Public Property MyFirstProperty as string\n &lt;XmlAttribute&gt; Public Property MySecondProperty as string\nEnd Class\n\n&lt;Serializable&gt; Public Class ChildClass\n &lt;XmlAttribute&gt; Public Property MyFirstProperty as string\n &lt;XmlAttribute&gt; Public Property MySecondProperty as string\nEnd Class\n</code></pre>\n\n<p>With this definition the class is (de)serialized without any problems. This is the XML that comes out of here:</p>\n\n<pre><code>&lt;MyClass&gt; MyFirstProperty=\"\" MySecondProperty=\"\"\n &lt;Children&gt;\n &lt;ChildClass&gt; MyFirstProperty=\"\" MySecondProperty=\"\"\n &lt;/ChildClass&gt;\n &lt;/Children&gt;\n&lt;/MyClass&gt;\n</code></pre>\n\n<p>It only took me two days to figure it out that the solution was to leave out the <code>&lt;XmlElement&gt;</code> prefix of the List(of T) elements.</p>\n" }, { "answer_id": 47215920, "author": "Lê Quý Đôn", "author_id": 8891788, "author_profile": "https://Stackoverflow.com/users/8891788", "pm_score": 2, "selected": false, "text": "<pre><code>var xmlfromLINQ = new XElement(\"BarList\",\n from c in BarList \n select new XElement(\"Bar\",\n new XElement(\"Property1\", c.Property1),\n new XElement(\"Property2\", c.Property2)\n ));\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4019/" ]
I have a collection of classes that I want to serialize out to an XML file. It looks something like this: ``` public class Foo { public List<Bar> BarList { get; set; } } ``` Where a bar is just a wrapper for a collection of properties, like this: ``` public class Bar { public string Property1 { get; set; } public string Property2 { get; set; } } ``` I want to mark this up so that it outputs to an XML file - this will be used for both persistence, and also to render the settings via an XSLT to a nice human-readable form. I want to get a nice XML representation like this: ``` <?xml version="1.0" encoding="utf-8"?> <Foo> <BarList> <Bar> <Property1>Value</Property1> <Property2>Value</Property2> </Bar> <Bar> <Property1>Value</Property1> <Property2>Value</Property2> </Bar> </Barlist> </Foo> ``` where are all of the Bars in the Barlist are written out with all of their properties. I'm fairly sure that I'll need some markup on the class definition to make it work, but I can't seem to find the right combination. I've marked Foo with the attribute ``` [XmlRoot("Foo")] ``` and the `list<Bar>` with the attribute ``` [XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName="Bar")] ``` in an attempt to tell the Serializer what I want to happen. This doesn't seem to work however and I just get an empty tag, looking like this: ``` <?xml version="1.0" encoding="utf-8"?> <Foo> <Barlist /> </Foo> ``` I'm not sure if the fact I'm using Automatic Properties should have any effect, or if the use of generics requires any special treatment. I've gotten this to work with simpler types like a list of strings, but a list of classes so far eludes me.
Just to check, have you marked Bar as [Serializable]? Also, you need a parameter-less ctor on Bar, to deserialize Hmm, I used: ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Foo f = new Foo(); f.BarList = new List<Bar>(); f.BarList.Add(new Bar { Property1 = "abc", Property2 = "def" }); XmlSerializer ser = new XmlSerializer(typeof(Foo)); using (FileStream fs = new FileStream(@"c:\sertest.xml", FileMode.Create)) { ser.Serialize(fs, f); } } } public class Foo { [XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName = "Bar")] public List<Bar> BarList { get; set; } } [XmlRoot("Foo")] public class Bar { public string Property1 { get; set; } public string Property2 { get; set; } } ``` And that produced: ``` <?xml version="1.0"?> <Foo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <BarList> <Bar> <Property1>abc</Property1> <Property2>def</Property2> </Bar> </BarList> </Foo> ```
178,904
<pre><code>var something = { wtf: null, omg: null }; </code></pre> <p>My JavaScript knowledge is still horribly patchy since I last programmed with it, but I think I've relearned most of it now. Except for this. I don't recall ever seeing this before. What is it? And where can I learn more about it?</p>
[ { "answer_id": 178916, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 4, "selected": false, "text": "<p>It's object literal syntax. The 'wft' and 'omg' are property names while, null and null are the property values.</p>\n\n<p>It is equivalent to:</p>\n\n<pre><code>var something = new Object();\nsomething.wtf = null;\nsomething.omg = null;\n</code></pre>\n\n<p>Check out mozilla's documentation on object literals: <a href=\"http://developer.mozilla.org/En/Core_JavaScript_1.5_Guide:Literals#Object_Literals\" rel=\"noreferrer\">http://developer.mozilla.org/En/Core_JavaScript_1.5_Guide:Literals#Object_Literals</a></p>\n" }, { "answer_id": 178918, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 2, "selected": false, "text": "<p>I believe its an object with 2 properties, WTF and OMG. </p>\n\n<p>you could say </p>\n\n<pre><code>something.wtf = \"myMessage\";\nalert(something.wtf);\n</code></pre>\n\n<p>check out JSON.ORG</p>\n" }, { "answer_id": 178922, "author": "Sergey Ilinsky", "author_id": 23815, "author_profile": "https://Stackoverflow.com/users/23815", "pm_score": 0, "selected": false, "text": "<p>This is an example of inline JavaScript object instantiation.</p>\n" }, { "answer_id": 178924, "author": "Stephen Deken", "author_id": 7154, "author_profile": "https://Stackoverflow.com/users/7154", "pm_score": 2, "selected": false, "text": "<p>This is an object literal. It's effectively equivalent to the following:</p>\n\n<pre><code>var something = new Object();\nsomething[\"wtf\"] = null;\nsomething[\"omg\"] = null;\n</code></pre>\n" }, { "answer_id": 178925, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 3, "selected": false, "text": "<p>It's an <strong>Object literal</strong> (or, sometimes, a <strong>vanilla object</strong> in libraries with Hash classes).</p>\n\n<p>Same thing as:</p>\n\n<pre><code>var o = new Object();\no.wtf = null;\no.omg = null;\n</code></pre>\n" }, { "answer_id": 178956, "author": "chroder", "author_id": 18802, "author_profile": "https://Stackoverflow.com/users/18802", "pm_score": 5, "selected": true, "text": "<p>It is an object literal with two properties. Usually this is how people create associative arrays or hashes because JS doesn't natively support that data structure. Though note that it is still a fully-fledged object, you can even add functions as properties:</p>\n\n<pre><code>var myobj = {\n name: 'SO',\n hello: function() {\n alert(this.name);\n }\n};\n</code></pre>\n\n<p>And you can iterate through the properties using a for loop:</p>\n\n<pre><code>for (i in myobj) {\n // myobj[i]\n // Using the brackets (myobj['name']) is the same as using a dot (myobj.name)\n}\n</code></pre>\n" }, { "answer_id": 178966, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": false, "text": "<p>Explanation from the \"I want an associative Array in Javascript\" standpoint (which is what in many cases object literals end up being used for)</p>\n\n<p>From <a href=\"http://www.hunlock.com/blogs/Mastering_Javascript_Arrays\" rel=\"nofollow noreferrer\">\"Mastering Javascript Arrays\"</a></p>\n\n<p>An associative array is an array which uses a string instead of a number as an index.</p>\n\n<pre><code>var normalArray = [];\n normalArray[1] = 'This is an enumerated array';\n\n alert(normalArray[1]); // outputs: This is an enumerated array\n\nvar associativeArray = [];\n associativeArray['person'] = 'John Smith';\n\n alert(associativeArray['person']); // outputs: John Smith \n</code></pre>\n\n<p>Javascript does not have, and does not support Associative Arrays. However… All arrays in Javascript are objects and Javascript's object syntax gives a basic emulation of an associative Array. For this reason the example code above will actually work. Be warned that this is not a real array and it has real pitfalls if you try to use it. The 'person' element in the example becomes part of the Array object's properties and methods, just like .length, .sort(), .splice(), and all the other built-in properties and methods.</p>\n\n<p>You can loop through an object's properties with the following loop…</p>\n\n<pre><code>var associativeArray = [];\nassociativeArray[\"one\"] = \"First\";\nassociativeArray[\"two\"] = \"Second\";\nassociativeArray[\"three\"] = \"Third\";\nfor (i in associativeArray) { \n document.writeln(i+':'+associativeArray[i]+', '); \n // outputs: one:First, two:Second, three:Third\n};\n</code></pre>\n\n<p>In the above example, associativeArray.length will be zero because we didn't actually put anything into the Array, we put it into associativeArray's object. associativeArray[0] will be undefined.</p>\n\n<p>The loop in the above example will also pick up any methods, properties, and prototypes which have been added to the array and not just your data. A lot of problems people have with the Prototype library is that their associative arrays break because Prototype adds a few useful Prototype functions to the Array object and for i in x loops pick up those additional methods. That's the pitfal of using Array/objects as a poor man's associative array.</p>\n\n<p>As a final example, the previous code will work regardless of whether you define associativeArray as an Array ([]), an Object({}), a Regular Expression (//), String(\"\"), or any other Javascript object.</p>\n\n<p>The bottom line is -- don't try to use associative arrays, code for what they are -- object properties, not Arrays. </p>\n" }, { "answer_id": 179286, "author": "Odilon Redo", "author_id": 21166, "author_profile": "https://Stackoverflow.com/users/21166", "pm_score": 1, "selected": false, "text": "<p>This code:</p>\n\n<pre><code>var something = {wtf:null}\n</code></pre>\n\n<p>Has the same effect as:</p>\n\n<pre><code>var something={};\nsomething.wtf=null;\n</code></pre>\n\n<p>Or for unnecessary verbosity:</p>\n\n<pre><code>var something=new Object();\nsomething.wtf=null;\n</code></pre>\n\n<p>And it's useful to remember that the last line is the same as</p>\n\n<pre><code>something[\"wtf\"]=null;\n</code></pre>\n\n<p>So you can use:</p>\n\n<pre><code>var myName=\"wtf\";\nsomething[myName]=null;\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19825/" ]
``` var something = { wtf: null, omg: null }; ``` My JavaScript knowledge is still horribly patchy since I last programmed with it, but I think I've relearned most of it now. Except for this. I don't recall ever seeing this before. What is it? And where can I learn more about it?
It is an object literal with two properties. Usually this is how people create associative arrays or hashes because JS doesn't natively support that data structure. Though note that it is still a fully-fledged object, you can even add functions as properties: ``` var myobj = { name: 'SO', hello: function() { alert(this.name); } }; ``` And you can iterate through the properties using a for loop: ``` for (i in myobj) { // myobj[i] // Using the brackets (myobj['name']) is the same as using a dot (myobj.name) } ```
178,913
<p>Here's the jist of the problem: Given a list of sets, such as:</p> <pre><code>[ (1,2,3), (5,2,6), (7,8,9), (6,12,13), (21,8,34), (19,20) ] </code></pre> <p>Return a list of groups of the sets, such that sets that have a shared element are in the same group.</p> <pre><code>[ [ (1,2,3), (5,2,6), (6,12,13) ], [ (7,8,9), (21,8,34) ], [ (19,20) ] ] </code></pre> <p>Note the stickeyness - the set (6,12,13) doesn't have a shared element with (1,2,3), but they get put in the same group because of (5,2,6).</p> <p>To complicate matters, I should mention that I don't really have these neat sets, but rather a DB table with several million rows that looks like:</p> <pre><code>element | set_id ---------------- 1 | 1 2 | 1 3 | 1 5 | 2 2 | 2 6 | 2 </code></pre> <p>and so on. So I would love a way to do it in SQL, but I would be happy with a general direction for the solution.</p> <p><strong>EDIT</strong>: Changed the table column names to (element, set_id) instead of (key, group_id), to make the terms more consistent. Note that Kev's answer uses the old column names.</p>
[ { "answer_id": 178940, "author": "Matt Price", "author_id": 852, "author_profile": "https://Stackoverflow.com/users/852", "pm_score": 1, "selected": false, "text": "<p>You could think of it as a graph problem where the set (1,2,3) is connected to the set (5,2,6) via the 2. And then use a standard algorithm to fine the connected sub-graphs.</p>\n\n<p>Here's a quick python implementation:</p>\n\n<pre><code>nodes = [ [1,2,3], [2,4,5], [6,7,8], [10,11,12], [7,10,13], [12], [] ]\nlinks = [ set() for x in nodes ]\n\n#first find the links\nfor n in range(len(nodes)):\n for item in nodes[n]:\n for m in range(n+1, len(nodes)):\n if (item in nodes[m]):\n links[n].add(m)\n links[m].add(n)\n\nsets = []\nnodes_not_in_a_set = range(len(nodes))\n\nwhile len(nodes_not_in_a_set) &gt; 0:\n nodes_to_explore = [nodes_not_in_a_set.pop()]\n current_set = set()\n while len(nodes_to_explore) &gt; 0:\n current_node = nodes_to_explore.pop()\n current_set.add(current_node)\n if current_node in nodes_not_in_a_set:\n nodes_not_in_a_set.remove(current_node)\n for l in links[current_node]:\n if l not in current_set and l not in nodes_to_explore:\n nodes_to_explore.append(l)\n if len(current_set) &gt; 0:\n sets.append(current_set)\n\nfor s in sets:\n print [nodes[n] for n in s]\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>[[]]\n[[6, 7, 8], [10, 11, 12], [7, 10, 13], [12]]\n[[1, 2, 3], [2, 4, 5]]\n</code></pre>\n" }, { "answer_id": 178965, "author": "Kev", "author_id": 16777, "author_profile": "https://Stackoverflow.com/users/16777", "pm_score": 0, "selected": false, "text": "<p>This is likely pretty inefficient, but it should work, at least: Start with a key, select all the groups containing that key, select all the keys of those groups, select all the groups containing those keys, etc., and as soon as a step adds no new keys or groups, you have a list of all the groups of one sub-graph. Exclude those and repeat from the beginning until you have no data left.</p>\n\n<p>In terms of SQL this would need a stored procedure, I think. WITH RECURSIVE might help you somehow, but I don't have any experience with it yet, and I'm not sure it's available on your DB backend.</p>\n" }, { "answer_id": 179183, "author": "itsadok", "author_id": 7581, "author_profile": "https://Stackoverflow.com/users/7581", "pm_score": 0, "selected": false, "text": "<p>After thinking about this some more, I came up with this:</p>\n\n<ol>\n<li>Create a table called <code>groups</code> with columns <code>(group_id, set_id)</code></li>\n<li>Sort the <code>sets</code> table by <code>element</code>. Now it should be easy to find duplicate elements.</li>\n<li>Iterate through the sets table, and when you find a duplicate element do:\n\n<ol>\n<li>if one of the <code>set_id</code> fields exists in the <code>groups</code> table, add the other one with the same <code>group_id</code>.</li>\n<li>If neither <code>set_id</code> exists in the <code>groups</code> table, generate a new group ID, and add both <code>set_id</code>s to the <code>groups</code> table.</li>\n</ol></li>\n</ol>\n\n<p>In the end I should have a <code>groups</code> table containing all the sets.</p>\n\n<p>This is not pure SQL, but seems like O(nlogn), so I guess I can live with that.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/178913/partition-a-list-of-sets-by-shared-elements#178940\">Matt's answer</a> seems more correct, but I'm not sure how to implement it in my case.</p>\n" }, { "answer_id": 180584, "author": "Camille", "author_id": 16990, "author_profile": "https://Stackoverflow.com/users/16990", "pm_score": 4, "selected": true, "text": "<p>The problem is exactly the computation of the connected components of an hypergraph: the integers are the vertices, and the sets are the hyperedges. A usual way of computing the connected components is by flooding them one after the other:</p>\n\n<ul>\n<li>for all i = 1 to N, do:</li>\n<li>if i has been tagged by some j &lt; i, then continue (I mean skip to the next i)</li>\n<li>else flood_from(i,i)</li>\n</ul>\n\n<p>where flood_from(i,j) would be defined as</p>\n\n<ul>\n<li>for each set S containing i, if it is not already tagged by j then:</li>\n<li>tag S by j and for each element k of S, if k is not already tagged by j, then tag it by j, and call flood_from(k,j)</li>\n</ul>\n\n<p>The tags of the sets then give you the connected components you are looking for. </p>\n\n<hr>\n\n<p>In terms of databases, the algorithm can be expressed as follows: you add a TAG column to your database, and you compute the connected component of set i by doing</p>\n\n<ul>\n<li>S = select all rows where set_id == i</li>\n<li>set TAG to i for the rows in S </li>\n<li>S' = select all rows where TAG is not set and where element is in element(S)</li>\n<li>while S' is not empty, do</li>\n<li>---- set TAG to i for the rows in S'</li>\n<li>---- S'' = select all rows where TAG is not set and where element is in element(S')</li>\n<li>---- S = S union S'</li>\n<li>---- S' = S''</li>\n<li>return set_id(S)</li>\n</ul>\n\n<hr>\n\n<p>Another (theoretical) way of presenting this algorithm would be to say that you are looking for the fixed points of a mapping:</p>\n\n<ul>\n<li>if A = {A<sub>1</sub>, ..., A<sub>n</sub>} is a set of sets, define union(A) = A<sub>1</sub> union ... union A<sub>n</sub></li>\n<li>if K = {k<sub>1</sub>, ..., k<sub>p</sub>} is a set of integers, define incidences(K) = the set of sets which intersect K</li>\n</ul>\n\n<p>Then if S is a set, the connected component of S is obtained by iterating (incidences)o(union) on S until a fixed point is reached:</p>\n\n<ol>\n<li>K = S</li>\n<li>K' = incidences(union(K)). </li>\n<li>if K == K', then return K, else K = K' and go to 2.</li>\n</ol>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7581/" ]
Here's the jist of the problem: Given a list of sets, such as: ``` [ (1,2,3), (5,2,6), (7,8,9), (6,12,13), (21,8,34), (19,20) ] ``` Return a list of groups of the sets, such that sets that have a shared element are in the same group. ``` [ [ (1,2,3), (5,2,6), (6,12,13) ], [ (7,8,9), (21,8,34) ], [ (19,20) ] ] ``` Note the stickeyness - the set (6,12,13) doesn't have a shared element with (1,2,3), but they get put in the same group because of (5,2,6). To complicate matters, I should mention that I don't really have these neat sets, but rather a DB table with several million rows that looks like: ``` element | set_id ---------------- 1 | 1 2 | 1 3 | 1 5 | 2 2 | 2 6 | 2 ``` and so on. So I would love a way to do it in SQL, but I would be happy with a general direction for the solution. **EDIT**: Changed the table column names to (element, set\_id) instead of (key, group\_id), to make the terms more consistent. Note that Kev's answer uses the old column names.
The problem is exactly the computation of the connected components of an hypergraph: the integers are the vertices, and the sets are the hyperedges. A usual way of computing the connected components is by flooding them one after the other: * for all i = 1 to N, do: * if i has been tagged by some j < i, then continue (I mean skip to the next i) * else flood\_from(i,i) where flood\_from(i,j) would be defined as * for each set S containing i, if it is not already tagged by j then: * tag S by j and for each element k of S, if k is not already tagged by j, then tag it by j, and call flood\_from(k,j) The tags of the sets then give you the connected components you are looking for. --- In terms of databases, the algorithm can be expressed as follows: you add a TAG column to your database, and you compute the connected component of set i by doing * S = select all rows where set\_id == i * set TAG to i for the rows in S * S' = select all rows where TAG is not set and where element is in element(S) * while S' is not empty, do * ---- set TAG to i for the rows in S' * ---- S'' = select all rows where TAG is not set and where element is in element(S') * ---- S = S union S' * ---- S' = S'' * return set\_id(S) --- Another (theoretical) way of presenting this algorithm would be to say that you are looking for the fixed points of a mapping: * if A = {A1, ..., An} is a set of sets, define union(A) = A1 union ... union An * if K = {k1, ..., kp} is a set of integers, define incidences(K) = the set of sets which intersect K Then if S is a set, the connected component of S is obtained by iterating (incidences)o(union) on S until a fixed point is reached: 1. K = S 2. K' = incidences(union(K)). 3. if K == K', then return K, else K = K' and go to 2.
178,915
<p>What do I need to do to save an image my program has generated (possibly from the camera, possibly not) to the system photo library on the iPhone?</p>
[ { "answer_id": 179066, "author": "Martin Gordon", "author_id": 2481, "author_profile": "https://Stackoverflow.com/users/2481", "pm_score": 10, "selected": true, "text": "<p>You can use this function:</p>\n\n<pre><code>UIImageWriteToSavedPhotosAlbum(UIImage *image, \n id completionTarget, \n SEL completionSelector, \n void *contextInfo);\n</code></pre>\n\n<p>You only need <strong>completionTarget</strong>, <strong>completionSelector</strong> and <strong>contextInfo</strong> if you want to be notified when the <code>UIImage</code> is done saving, otherwise you can pass in <code>nil</code>.</p>\n\n<p>See the <a href=\"https://developer.apple.com/documentation/uikit/1619125-uiimagewritetosavedphotosalbum?language=objc\" rel=\"noreferrer\">official documentation for <code>UIImageWriteToSavedPhotosAlbum()</code></a>.</p>\n" }, { "answer_id": 2542467, "author": "mrburns05", "author_id": 199367, "author_profile": "https://Stackoverflow.com/users/199367", "pm_score": 3, "selected": false, "text": "<p>Just pass the images from an array to it like so</p>\n\n<pre><code>-(void) saveMePlease {\n\n//Loop through the array here\nfor (int i=0:i&lt;[arrayOfPhotos count]:i++){\n NSString *file = [arrayOfPhotos objectAtIndex:i];\n NSString *path = [get the path of the image like you would in DOCS FOLDER or whatever];\n NSString *imagePath = [path stringByAppendingString:file];\n UIImage *image = [[[UIImage alloc] initWithContentsOfFile:imagePath]autorelease];\n\n //Now it will do this for each photo in the array\n UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);\n }\n}\n</code></pre>\n\n<p>Sorry for typo's kinda just did this on the fly but you get the point</p>\n" }, { "answer_id": 2870518, "author": "mrburns05", "author_id": 199367, "author_profile": "https://Stackoverflow.com/users/199367", "pm_score": 1, "selected": false, "text": "<p>my last answer will do it..</p>\n\n<p>for each image you want to save, add it to a NSMutableArray</p>\n\n<pre><code> //in the .h file put:\n\nNSMutableArray *myPhotoArray;\n\n\n///then in the .m\n\n- (void) viewDidLoad {\n\n myPhotoArray = [[NSMutableArray alloc]init];\n\n\n\n}\n\n//However Your getting images\n\n- (void) someOtherMethod { \n\n UIImage *someImage = [your prefered method of using this];\n[myPhotoArray addObject:someImage];\n\n}\n\n-(void) saveMePlease {\n\n//Loop through the array here\nfor (int i=0:i&lt;[myPhotoArray count]:i++){\n NSString *file = [myPhotoArray objectAtIndex:i];\n NSString *path = [get the path of the image like you would in DOCS FOLDER or whatever];\n NSString *imagePath = [path stringByAppendingString:file];\n UIImage *image = [[[UIImage alloc] initWithContentsOfFile:imagePath]autorelease];\n\n //Now it will do this for each photo in the array\n UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);\n }\n}\n</code></pre>\n" }, { "answer_id": 3760992, "author": "Dzianis Fileyeu", "author_id": 453987, "author_profile": "https://Stackoverflow.com/users/453987", "pm_score": 6, "selected": false, "text": "<p><strong>Deprecated in iOS 9.0.</strong></p>\n\n<p>There`s much more fast then UIImageWriteToSavedPhotosAlbum way to do it using iOS 4.0+ AssetsLibrary framework</p>\n\n<pre><code> ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];\n\n [library writeImageToSavedPhotosAlbum:[image CGImage] orientation:(ALAssetOrientation)[image imageOrientation] completionBlock:^(NSURL *assetURL, NSError *error){\n if (error) {\n // TODO: error handling\n } else {\n // TODO: success handling\n }\n}];\n[library release];\n</code></pre>\n" }, { "answer_id": 5272479, "author": "Hello", "author_id": 655276, "author_profile": "https://Stackoverflow.com/users/655276", "pm_score": 1, "selected": false, "text": "<pre><code>homeDirectoryPath = NSHomeDirectory();\nunexpandedPath = [homeDirectoryPath stringByAppendingString:@\"/Pictures/\"];\n\nfolderPath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedPath stringByExpandingTildeInPath]], nil]];\n\nunexpandedImagePath = [folderPath stringByAppendingString:@\"/image.png\"];\n\nimagePath = [NSString pathWithComponents:[NSArray arrayWithObjects:[NSString stringWithString:[unexpandedImagePath stringByExpandingTildeInPath]], nil]];\n\nif (![[NSFileManager defaultManager] fileExistsAtPath:folderPath isDirectory:NULL]) {\n [[NSFileManager defaultManager] createDirectoryAtPath:folderPath attributes:nil];\n}\n</code></pre>\n" }, { "answer_id": 15755630, "author": "Jeff C.", "author_id": 881448, "author_profile": "https://Stackoverflow.com/users/881448", "pm_score": 4, "selected": false, "text": "<p>One thing to remember: If you use a callback, make sure that your selector conforms to the following form:</p>\n\n<pre><code>- (void) image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo;\n</code></pre>\n\n<p>Otherwise, you'll crash with an error such as the following:</p>\n\n<p><code>[NSInvocation setArgument:atIndex:]: index (2) out of bounds [-1, 1]</code></p>\n" }, { "answer_id": 18220664, "author": "SamChen", "author_id": 927208, "author_profile": "https://Stackoverflow.com/users/927208", "pm_score": 2, "selected": false, "text": "<p>When saving an array of photos, don't use a for loop, do the following</p>\n\n<pre><code>-(void)saveToAlbum{\n [self performSelectorInBackground:@selector(startSavingToAlbum) withObject:nil];\n}\n-(void)startSavingToAlbum{\n currentSavingIndex = 0;\n UIImage* img = arrayOfPhoto[currentSavingIndex];//get your image\n UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);\n}\n- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo{ //can also handle error message as well\n currentSavingIndex ++;\n if (currentSavingIndex &gt;= arrayOfPhoto.count) {\n return; //notify the user it's done.\n }\n else\n {\n UIImage* img = arrayOfPhoto[currentSavingIndex];\n UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);\n }\n}\n</code></pre>\n" }, { "answer_id": 20756849, "author": "Mutawe", "author_id": 1091539, "author_profile": "https://Stackoverflow.com/users/1091539", "pm_score": 5, "selected": false, "text": "<p>The simplest way is:</p>\n\n<pre><code>UIImageWriteToSavedPhotosAlbum(myUIImage, nil, nil, nil);\n</code></pre>\n\n<p>For <code>Swift</code>, you can refer to <a href=\"https://www.hackingwithswift.com/read/13/5/saving-to-the-ios-photo-library\" rel=\"noreferrer\">Saving to the iOS photo library using swift</a></p>\n" }, { "answer_id": 21281534, "author": "Pratik Somaiya", "author_id": 1235566, "author_profile": "https://Stackoverflow.com/users/1235566", "pm_score": 0, "selected": false, "text": "<p>You can use this</p>\n\n<pre><code>dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{\n UIImageWriteToSavedPhotosAlbum(img.image, nil, nil, nil);\n});\n</code></pre>\n" }, { "answer_id": 29133115, "author": "King-Wizard", "author_id": 1110914, "author_profile": "https://Stackoverflow.com/users/1110914", "pm_score": 2, "selected": false, "text": "<p>In <strong>Swift</strong>:</p>\n\n<pre><code> // Save it to the camera roll / saved photo album\n // UIImageWriteToSavedPhotosAlbum(self.myUIImageView.image, nil, nil, nil) or \n UIImageWriteToSavedPhotosAlbum(self.myUIImageView.image, self, \"image:didFinishSavingWithError:contextInfo:\", nil)\n\n func image(image: UIImage!, didFinishSavingWithError error: NSError!, contextInfo: AnyObject!) {\n if (error != nil) {\n // Something wrong happened.\n } else {\n // Everything is alright.\n }\n }\n</code></pre>\n" }, { "answer_id": 31512044, "author": "HugglesNL", "author_id": 3075874, "author_profile": "https://Stackoverflow.com/users/3075874", "pm_score": 1, "selected": false, "text": "<p>I created a UIImageView category for this, based on some of the answers above.</p>\n\n<p>Header File:</p>\n\n<pre><code>@interface UIImageView (SaveImage) &lt;UIActionSheetDelegate&gt;\n- (void)addHoldToSave;\n@end\n</code></pre>\n\n<p>Implementation</p>\n\n<pre><code>@implementation UIImageView (SaveImage)\n- (void)addHoldToSave{\n UILongPressGestureRecognizer* longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];\n longPress.minimumPressDuration = 1.0f;\n [self addGestureRecognizer:longPress];\n}\n\n- (void)handleLongPress:(UILongPressGestureRecognizer*)sender {\n if (sender.state == UIGestureRecognizerStateEnded) {\n\n UIActionSheet* _attachmentMenuSheet = [[UIActionSheet alloc] initWithTitle:nil\n delegate:self\n cancelButtonTitle:@\"Cancel\"\n destructiveButtonTitle:nil\n otherButtonTitles:@\"Save Image\", nil];\n [_attachmentMenuSheet showInView:[[UIView alloc] initWithFrame:self.frame]];\n }\n else if (sender.state == UIGestureRecognizerStateBegan){\n //Do nothing\n }\n}\n-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{\n if (buttonIndex == 0) {\n UIImageWriteToSavedPhotosAlbum(self.image, nil,nil, nil);\n }\n}\n\n\n@end\n</code></pre>\n\n<p>Now simply call this function on your imageview:</p>\n\n<pre><code>[self.imageView addHoldToSave];\n</code></pre>\n\n<p>Optionally you can alter the minimumPressDuration parameter.</p>\n" }, { "answer_id": 32962031, "author": "iDevAmit", "author_id": 1872233, "author_profile": "https://Stackoverflow.com/users/1872233", "pm_score": 2, "selected": false, "text": "<p><strong>Below function would work. You can copy from here and paste there...</strong></p>\n\n<pre><code>-(void)savePhotoToAlbum:(UIImage*)imageToSave {\n\n CGImageRef imageRef = imageToSave.CGImage;\n NSDictionary *metadata = [NSDictionary new]; // you can add\n ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];\n\n [library writeImageToSavedPhotosAlbum:imageRef metadata:metadata completionBlock:^(NSURL *assetURL,NSError *error){\n if(error) {\n NSLog(@\"Image save eror\");\n }\n }];\n}\n</code></pre>\n" }, { "answer_id": 36819428, "author": "jarora", "author_id": 1869954, "author_profile": "https://Stackoverflow.com/users/1869954", "pm_score": 1, "selected": false, "text": "<p>In <strong>Swift 2.2</strong></p>\n\n<pre><code>UIImageWriteToSavedPhotosAlbum(image: UIImage, _ completionTarget: AnyObject?, _ completionSelector: Selector, _ contextInfo: UnsafeMutablePointer&lt;Void&gt;)\n</code></pre>\n\n<p>If you do not want to be notified when the image is done saving then you may pass nil in the <strong>completionTarget</strong>, <strong>completionSelector</strong> and <strong>contextInfo</strong> parameters.</p>\n\n<p>Example:</p>\n\n<pre><code>UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.imageSaved(_:didFinishSavingWithError:contextInfo:)), nil)\n\nfunc imageSaved(image: UIImage!, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?) {\n if (error != nil) {\n // Something wrong happened.\n } else {\n // Everything is alright.\n }\n }\n</code></pre>\n\n<p>The important thing to note here is that your method that observes the image saving should have these 3 parameters else you will run into NSInvocation errors. </p>\n\n<p>Hope it helps. </p>\n" }, { "answer_id": 54250312, "author": "luhuiya", "author_id": 932672, "author_profile": "https://Stackoverflow.com/users/932672", "pm_score": 2, "selected": false, "text": "<p>Swift 4</p>\n\n<pre><code>func writeImage(image: UIImage) {\n UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.finishWriteImage), nil)\n}\n\n@objc private func finishWriteImage(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {\n if (error != nil) {\n // Something wrong happened.\n print(\"error occurred: \\(String(describing: error))\")\n } else {\n // Everything is alright.\n print(\"saved success!\")\n }\n}\n</code></pre>\n" }, { "answer_id": 64046706, "author": "Hope", "author_id": 2692027, "author_profile": "https://Stackoverflow.com/users/2692027", "pm_score": 0, "selected": false, "text": "<p>For Swift 5.0</p>\n<p>I used this code to copy images to photo albums my application had created;\nWhen I want to copy images files I call &quot;startSavingPhotoAlbume()&quot; function.\nFirst I get UIImage from App folder then save it to photo albums.\nBecause it is irrelevant I dont show how to read image from App folder.</p>\n<pre><code>var saveToPhotoAlbumCounter = 0\n\n\n\nfunc startSavingPhotoAlbume(){\n saveToPhotoAlbumCounter = 0\n saveToPhotoAlbume()\n}\n\nfunc saveToPhotoAlbume(){ \n let image = loadImageFile(fileName: imagefileList[saveToPhotoAlbumCounter], folderName: folderName)\n UIImageWriteToSavedPhotosAlbum(image!, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)\n}\n\n@objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {\n if (error != nil) {\n print(&quot;ptoto albume savin error for \\(imageFileList[saveToPhotoAlbumCounter])&quot;)\n } else {\n \n if saveToPhotoAlbumCounter &lt; imageFileList.count - 1 {\n saveToPhotoAlbumCounter += 1\n saveToPhotoAlbume()\n } else {\n print(&quot;saveToPhotoAlbume is finished with \\(saveToPhotoAlbumCounter) files&quot;)\n }\n }\n}\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178915", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20626/" ]
What do I need to do to save an image my program has generated (possibly from the camera, possibly not) to the system photo library on the iPhone?
You can use this function: ``` UIImageWriteToSavedPhotosAlbum(UIImage *image, id completionTarget, SEL completionSelector, void *contextInfo); ``` You only need **completionTarget**, **completionSelector** and **contextInfo** if you want to be notified when the `UIImage` is done saving, otherwise you can pass in `nil`. See the [official documentation for `UIImageWriteToSavedPhotosAlbum()`](https://developer.apple.com/documentation/uikit/1619125-uiimagewritetosavedphotosalbum?language=objc).
178,921
<p>I have the following code in my file to load a div with HTML from an AJAX call:</p> <pre><code>$('#searchButton').click( function() { $('#inquiry').load('/search.php?pid=' + $('#searchValue').val()); }); </code></pre> <p>This works fine in Firefox and Google Chrome, but whenever I do the search in IE I get redirected back to index.php. I grabbed the URL from Firebug and pasted that into IE and no redirection happens, I just get the output that should be returned.</p> <p>I also tried changing it to a $.get() request and a full $.ajax() request but still the same redirection.</p>
[ { "answer_id": 178942, "author": "Steve g", "author_id": 12092, "author_profile": "https://Stackoverflow.com/users/12092", "pm_score": 2, "selected": false, "text": "<p>IE Handles default events differently (also beware of hitting enter in a text field). IE is causing some default event handler to fire. If searchButton is a link with HREF of \"\" it will reload the current page. You can try to set the href to \"javascript:void(0)\" or do something like:</p>\n\n<pre><code>$('#searchButton').click( function(e) {\n $('#inquiry').load('/search.php?pid=' + $('#searchValue').val());\n e.preventDefault();\n});\n</code></pre>\n" }, { "answer_id": 179043, "author": "dragonmantank", "author_id": 204, "author_profile": "https://Stackoverflow.com/users/204", "pm_score": 2, "selected": true, "text": "<p>More fun. I have the input text and button wrapped in this form:</p>\n\n<pre><code>&lt;form onSubmit=\"return false;\"&gt;\n[HTML]\n&lt;/form&gt;\n</code></pre>\n\n<p>and IE seems to be ignoring the return false. I tried modding the jQuery function to be like Steve's but it was still refreshing inproperly.</p>\n\n<p>I removed the form tags and that took care of it.</p>\n" }, { "answer_id": 180675, "author": "Sugendran", "author_id": 22466, "author_profile": "https://Stackoverflow.com/users/22466", "pm_score": 0, "selected": false, "text": "<p>set the action attribute of the form to a javascript function (e.g. your search handling function) or \"return false\"</p>\n\n<p>MSIE is firing the form action when you hit enter</p>\n" }, { "answer_id": 180708, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 0, "selected": false, "text": "<p>Your function should return false to prevent the submit action of the button. I don't know how jQuery handles that, though.</p>\n" }, { "answer_id": 23929433, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>You should prevent default like follow way ..</p>\n\n<pre><code>var searchbutton = $('#searchButton');\nvar inquirysearchvalue = $('#inquiry').load('/search.php?pid=' + $('#searchValue');\n\nsearchbutton.click( function(e) {\n inquirysearchvalue.val());\n e.preventDefault();\n});\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178921", "https://Stackoverflow.com", "https://Stackoverflow.com/users/204/" ]
I have the following code in my file to load a div with HTML from an AJAX call: ``` $('#searchButton').click( function() { $('#inquiry').load('/search.php?pid=' + $('#searchValue').val()); }); ``` This works fine in Firefox and Google Chrome, but whenever I do the search in IE I get redirected back to index.php. I grabbed the URL from Firebug and pasted that into IE and no redirection happens, I just get the output that should be returned. I also tried changing it to a $.get() request and a full $.ajax() request but still the same redirection.
More fun. I have the input text and button wrapped in this form: ``` <form onSubmit="return false;"> [HTML] </form> ``` and IE seems to be ignoring the return false. I tried modding the jQuery function to be like Steve's but it was still refreshing inproperly. I removed the form tags and that took care of it.
178,934
<p>In the STL library some containers have iterators and it is commonly held that they are a superior way of iterating through these containers rather than simple for loops e.g.</p> <pre><code>for ( int i=0; i &lt; vecVector.size(); i++ ) { .. } </code></pre> <p>Can anyone tell me why and in what cases I should use iterators and in what cases the code snippet above please?</p>
[ { "answer_id": 178950, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 4, "selected": false, "text": "<p>Using iterators allows your code to be agnostic about the implementation of your container. If random access for your container is cheap, there isn't much difference performance-wise.</p>\n\n<p>But in lots of cases you won't know whether that is the case. If you try do use your method on a linked list, for example, with subscripting, the container is going to have to walk the list on every iteration to find your element.</p>\n\n<p>So unless you know for sure that random access to your container is cheap, use an iterator.</p>\n" }, { "answer_id": 178974, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 2, "selected": false, "text": "<p>In your example, the call to vecVector.size() is less efficient than using an iterator. The iterator essentially encapsulates you from having to worry about the size of the container being iterated upon. Furthermore, the iterator does not necessary have to go in sequential order. It simply has to respond to a .next call in whatever way it sees fit.</p>\n" }, { "answer_id": 178989, "author": "Dave Van den Eynde", "author_id": 455874, "author_profile": "https://Stackoverflow.com/users/455874", "pm_score": 1, "selected": false, "text": "<p>Well, for one thing the above will no longer work if you turn that vector into a list.</p>\n\n<p>Iterators allow you to create function templates that don't need to know the type of container they work on. You can even do the following:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n\nvoid printvalue(double s)\n{\n // Do something with s\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n double s[20] = {0};\n\n std::for_each(s, s+20, printvalue);\n\n return 0;\n}\n</code></pre>\n\n<p>That's because a standard pointer is also a valid iterator for for_each.</p>\n\n<p>Dave</p>\n" }, { "answer_id": 178992, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 6, "selected": true, "text": "<p>Note that the usually implementation of vector won't use an &quot;int&quot; as the type of the index/size. So your code will at the very least provoke compiler warnings.</p>\n<h3>Genericity</h3>\n<p>Iterators increase the genericity of your code.</p>\n<p>For example:</p>\n<pre><code>typedef std::vector&lt;int&gt; Container ;\n\nvoid doSomething(Container &amp; p_aC)\n{\n for(Container::iterator it = p_aC.begin(), itEnd = p_aC.end(); it != itEnd; ++it)\n {\n int &amp; i = *it ; // i is now a reference to the value iterated\n // do something with &quot;i&quot;\n }\n}\n</code></pre>\n<p>Now, let's imagine you change the vector into a list (because in your case, the list is now better). You only need to change the typedef declaration, and recompile the code.</p>\n<p>Should you have used index-based code instead, it would have needed to be re-written.</p>\n<h3>Access</h3>\n<p>The iterator should be viewed like a kind of super pointer.\nIt &quot;points&quot; to the value (or, in case of maps, to the pair of key/value).</p>\n<p>But it has methods to move to the next item in the container. Or the previous. Some containers offer even random access (the vector and the deque).</p>\n<h3>Algorithms</h3>\n<p>Most STL algorithms work on iterators or on ranges of iterators (again, because of genericity). You won't be able to use an index, here.</p>\n" }, { "answer_id": 179348, "author": "Jamie Eisenhart", "author_id": 19533, "author_profile": "https://Stackoverflow.com/users/19533", "pm_score": 2, "selected": false, "text": "<p>If you use iterators as the arguments to your function you can decouple it from the type of \"container\" used. For example, you might direct the results of a function to console output rather than a vector (example below). This trick can be enormously powerful for reducing coupling between your classes. Loosely coupled classes are much easier to test.</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n#include &lt;algorithm&gt;\n\nusing namespace std;\n\ntemplate &lt;typename InputIterator, typename OutputIterator&gt;\nvoid AddOne(InputIterator begin, InputIterator end, OutputIterator dest)\n{\n while (begin != end)\n {\n *dest = *begin + 1;\n ++dest;\n ++begin;\n }\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n vector&lt;int&gt; data;\n data.push_back(1);\n data.push_back(2);\n data.push_back(3);\n\n // Compute intermediate results vector and dump to console\n vector&lt;int&gt; results;\n AddOne(data.begin(), data.end(), back_inserter(results));\n copy(results.begin(), results.end(), ostream_iterator&lt;int&gt;(cout, \" \"));\n cout &lt;&lt; endl;\n\n // Compute results and send directly to console, no intermediate vector required\n AddOne(data.begin(), data.end(), ostream_iterator&lt;int&gt;(cout, \" \"));\n cout &lt;&lt; endl;\n\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 181824, "author": "Johann Gerell", "author_id": 6345, "author_profile": "https://Stackoverflow.com/users/6345", "pm_score": 1, "selected": false, "text": "<p>The iterator is mostly a higher level of abstraction.</p>\n\n<p>Your snippet assumes that the container can be indexed. This is true for <code>std::vector&lt;&gt;</code> and some other containers, for instance raw arrays.</p>\n\n<p>But <code>std::set&lt;&gt;</code> lacks indexing completely and the index operator of <code>std::map&lt;&gt;</code> will insert whatever argument is supplied to it into the map - not the expected behavior in your <code>for</code>-loop.</p>\n\n<p>Also, performance issues are only issues when measured and proved so.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18664/" ]
In the STL library some containers have iterators and it is commonly held that they are a superior way of iterating through these containers rather than simple for loops e.g. ``` for ( int i=0; i < vecVector.size(); i++ ) { .. } ``` Can anyone tell me why and in what cases I should use iterators and in what cases the code snippet above please?
Note that the usually implementation of vector won't use an "int" as the type of the index/size. So your code will at the very least provoke compiler warnings. ### Genericity Iterators increase the genericity of your code. For example: ``` typedef std::vector<int> Container ; void doSomething(Container & p_aC) { for(Container::iterator it = p_aC.begin(), itEnd = p_aC.end(); it != itEnd; ++it) { int & i = *it ; // i is now a reference to the value iterated // do something with "i" } } ``` Now, let's imagine you change the vector into a list (because in your case, the list is now better). You only need to change the typedef declaration, and recompile the code. Should you have used index-based code instead, it would have needed to be re-written. ### Access The iterator should be viewed like a kind of super pointer. It "points" to the value (or, in case of maps, to the pair of key/value). But it has methods to move to the next item in the container. Or the previous. Some containers offer even random access (the vector and the deque). ### Algorithms Most STL algorithms work on iterators or on ranges of iterators (again, because of genericity). You won't be able to use an index, here.
178,936
<p>I am working on a build system. The build system posts the results as a zip file in a directory. Unfortunately I have no easy way to know the name of the zip file, because it is timestamped. For the next operation, I must decompress this zip file to some specific location and then do some more file operations.</p> <p>I guess I could change the build system so I specify the name of the result zip file from the command line, however, I though it might be easiest just to find out which one is the newest file and unzip it (if the previous process is successful). </p> <p>How can I issue an unzip command that will only take effect on the newest zip file in the directory, ignoring all others?</p> <p>EDIT: I decided to use the capabilities in ANT for this task instead. However, it is still a neat trick to have up the sleve... Thanks for the answer!</p>
[ { "answer_id": 178941, "author": "Rasmus", "author_id": 25792, "author_profile": "https://Stackoverflow.com/users/25792", "pm_score": -1, "selected": false, "text": "<p>Why use bat files when you have powershell or console applications?</p>\n" }, { "answer_id": 178946, "author": "RedWolves", "author_id": 648, "author_profile": "https://Stackoverflow.com/users/648", "pm_score": -1, "selected": false, "text": "<p>I think you would need 7-zip to be able to script compression/uncompression.</p>\n" }, { "answer_id": 179016, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 5, "selected": true, "text": "<p>This should do it:</p>\n\n<pre><code>FOR /F usebackq %%i IN (`DIR /B /O-D *.ZIP`) DO UNZIP %%i &amp;&amp; GOTO DONE || GOTO DONE\n:DONE\n</code></pre>\n\n<p>This works as follows:</p>\n\n<ul>\n<li><code>DIR /B /O-D *.ZIP</code> lists all ZIP files in reverse date order in a \"bare\" - i.e. name only - format.</li>\n<li><code>FOR /F usebackq</code> is used to loop over the output of the command.</li>\n<li><code>&amp;&amp; GOTO DONE || GOTO DONE</code> makes sure the <code>UNZIP</code> is only run for the first file. You need both <code>&amp;&amp;</code> (and) and <code>||</code> (or) in case the unzip fails for some reason.</li>\n</ul>\n\n<p>You'll need to change <code>UNZIP %%i</code> for whatever unzip command you want to use.</p>\n\n<p><strong>EDIT</strong>\nThe above will work as long as the Zip filename doesn't contain any spaces. If you want to handle filenames with spaces, use the following variant:</p>\n\n<pre><code>FOR /F \"tokens=*\" %%i IN ('DIR /B /O-D *.ZIP') DO UNZIP \"%%i\" &amp;&amp; GOTO DONE || GOTO DONE\n:DONE\n</code></pre>\n\n<p>The differences are:</p>\n\n<ul>\n<li><p>The \"tokens=*\" option returns the whole of the filename even if it contains spaces.</p></li>\n<li><p>The filename passed to UNZIP is quoted</p></li>\n<li><p>This variant uses single quotes for the DIR command so doesn't need the \"usebackq\" option.</p></li>\n</ul>\n" }, { "answer_id": 179035, "author": "John Nilsson", "author_id": 24243, "author_profile": "https://Stackoverflow.com/users/24243", "pm_score": 2, "selected": false, "text": "<p>If Cygwin or other Unix-like environment is an alternative</p>\n\n<pre><code>unzip \"$(ls -tr *zip | tail -n1)\"\n</code></pre>\n\n<p>would do it</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2309/" ]
I am working on a build system. The build system posts the results as a zip file in a directory. Unfortunately I have no easy way to know the name of the zip file, because it is timestamped. For the next operation, I must decompress this zip file to some specific location and then do some more file operations. I guess I could change the build system so I specify the name of the result zip file from the command line, however, I though it might be easiest just to find out which one is the newest file and unzip it (if the previous process is successful). How can I issue an unzip command that will only take effect on the newest zip file in the directory, ignoring all others? EDIT: I decided to use the capabilities in ANT for this task instead. However, it is still a neat trick to have up the sleve... Thanks for the answer!
This should do it: ``` FOR /F usebackq %%i IN (`DIR /B /O-D *.ZIP`) DO UNZIP %%i && GOTO DONE || GOTO DONE :DONE ``` This works as follows: * `DIR /B /O-D *.ZIP` lists all ZIP files in reverse date order in a "bare" - i.e. name only - format. * `FOR /F usebackq` is used to loop over the output of the command. * `&& GOTO DONE || GOTO DONE` makes sure the `UNZIP` is only run for the first file. You need both `&&` (and) and `||` (or) in case the unzip fails for some reason. You'll need to change `UNZIP %%i` for whatever unzip command you want to use. **EDIT** The above will work as long as the Zip filename doesn't contain any spaces. If you want to handle filenames with spaces, use the following variant: ``` FOR /F "tokens=*" %%i IN ('DIR /B /O-D *.ZIP') DO UNZIP "%%i" && GOTO DONE || GOTO DONE :DONE ``` The differences are: * The "tokens=\*" option returns the whole of the filename even if it contains spaces. * The filename passed to UNZIP is quoted * This variant uses single quotes for the DIR command so doesn't need the "usebackq" option.
178,948
<p>I have a repeater that outputs divs like the following for every item returned from some method.</p> <pre><code>&lt;div class="editor-area"&gt; &lt;div class="title"&gt;the title&lt;/div&gt; &lt;div&gt;the description&lt;/div&gt; &lt;div class="bottom-bar"&gt; &lt;a href="link"&gt;Modify&lt;/a&gt; &lt;a href="link2"&gt;Delete&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>I need to have a textbox on the page that allows the user to filter the list based on what's in the title field. I would like it to happen as the user types.</p> <p>I could get this done without asking for help, but I want to do it right. I'm using ASP.Net 2.0 WebForms (unfortunately), and I can use jQuery if it would be useful for this (i have very little experience with it). </p> <p>Any tips or samples would be appreciated. </p> <p>If the filter operation takes a couple of seconds, how do you keep it from locking up the screen? What event should I do the filter on? Is there anything in jQuery that would make the javascript a little cleaner?</p>
[ { "answer_id": 179021, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 4, "selected": true, "text": "<p>Yes, this is dead simple with jQuery. First hide everything:</p>\n\n<pre><code>$(\"div.title\").hide();\n</code></pre>\n\n<p>(Matches elements of type \"div\" with class \"title\".) Now show the matches:</p>\n\n<pre><code>$(\"div.title:contains(searchText)\").show();\n</code></pre>\n\n<p><a href=\"http://docs.jquery.com/Selectors/contains#text\" rel=\"noreferrer\">Help for \"contains\".</a></p>\n\n<p>It should not take \"seconds\" to do this unless your page is enormous. You can do this in onKeyDown and onChange.</p>\n" }, { "answer_id": 179401, "author": "Dan Goldstein", "author_id": 23427, "author_profile": "https://Stackoverflow.com/users/23427", "pm_score": 2, "selected": false, "text": "<p>Craig is very close. Put \".parent()\" before \".hide()\" or \".show()\" to show or hide the parent div.</p>\n\n<p>As for your second comment, that's a separate problem but yes, you'll need to account for non-text input. Another idea is to show everything if the filter textbox is blank.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178948", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3226/" ]
I have a repeater that outputs divs like the following for every item returned from some method. ``` <div class="editor-area"> <div class="title">the title</div> <div>the description</div> <div class="bottom-bar"> <a href="link">Modify</a> <a href="link2">Delete</a> </div> </div> ``` I need to have a textbox on the page that allows the user to filter the list based on what's in the title field. I would like it to happen as the user types. I could get this done without asking for help, but I want to do it right. I'm using ASP.Net 2.0 WebForms (unfortunately), and I can use jQuery if it would be useful for this (i have very little experience with it). Any tips or samples would be appreciated. If the filter operation takes a couple of seconds, how do you keep it from locking up the screen? What event should I do the filter on? Is there anything in jQuery that would make the javascript a little cleaner?
Yes, this is dead simple with jQuery. First hide everything: ``` $("div.title").hide(); ``` (Matches elements of type "div" with class "title".) Now show the matches: ``` $("div.title:contains(searchText)").show(); ``` [Help for "contains".](http://docs.jquery.com/Selectors/contains#text) It should not take "seconds" to do this unless your page is enormous. You can do this in onKeyDown and onChange.
178,952
<p>In the code below I use <code>mpf_add</code> to add the string representation of two floating values. What I don't understand at this point is why <code>2.2 + 3.2 = 5.39999999999999999999999999999999999999</code>. I would have thought that <code>gmp</code> was smart enough to give <code>5.4</code>. </p> <p>What am I not comprehending about how gmp does floats?</p> <p>(BTW, when I first wrote this I wasn't sure how to insert a decimal point, thus the plus/minus digit stuff at the end)</p> <pre><code>BSTR __stdcall FBIGSUM(BSTR p1, BSTR p2 ) { USES_CONVERSION; F(n1); F(n2); F(res); LPSTR sNum1 = W2A( p1 ); LPSTR sNum2 = W2A( p2 ); mpf_set_str( n1, sNum1, 10 ); mpf_set_str( n2, sNum2, 10 ); mpf_add( res, n1, n2 ); char * buff = (char *) _alloca( 1024 ); char expBuffer[ 20 ]; mp_exp_t exp; mpf_get_str(buff, &amp;exp, 10, 0, res); char * temp = ltoa( (long) exp, expBuffer, 10 ); if (exp &gt;= 0) { strcat(buff, "+" ); } strcat(buff, expBuffer ); BSTR bResult = _com_util::ConvertStringToBSTR( buff ); return bResult; } </code></pre>
[ { "answer_id": 178978, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 3, "selected": true, "text": "<p>This is because of the inherent error of using floating-point arithmetic in a binary environment.</p>\n\n<p>See the <a href=\"http://en.wikipedia.org/wiki/IEEE_754\" rel=\"nofollow noreferrer\">IEEE 754</a> standard for more information.</p>\n" }, { "answer_id": 179013, "author": "Chris Charabaruk", "author_id": 5697, "author_profile": "https://Stackoverflow.com/users/5697", "pm_score": 1, "selected": false, "text": "<p>What <a href=\"https://stackoverflow.com/users/4418/warren\">warren</a> <a href=\"https://stackoverflow.com/questions/178952/adding-floats-with-gmp-gives-correct-results-sort-of#178978\">said</a>.</p>\n\n<p>You might have better results if you use binary coded decimal instead of floating point numbers, although I can't really direct you to any libraries for that.</p>\n" }, { "answer_id": 184167, "author": "bugmagnet", "author_id": 426, "author_profile": "https://Stackoverflow.com/users/426", "pm_score": 1, "selected": false, "text": "<p>I eventually ended up answering this myself. The solution for me was to do in code what I used to do in school. The method works like this:</p>\n\n<ol>\n<li>Take each number and make sure that the number of digits to the right of the decimal point are the same. So if adding <code>2.1</code> and <code>3.457</code>, 'normalise' the first one to <code>2.100</code>. Keep a record of the number of digits that are to the right of the decimal, in this case, three.</li>\n<li>Now remove the decimal point and use <code>mpz_add</code> to add the two numbers, which have now become <code>2100</code> and <code>3457</code>. The result is <code>5557</code>.</li>\n<li>Finally, reinsert the decimal point three characters (in this case) from the right, giving the correct answer of <code>5.557</code>. </li>\n</ol>\n\n<p>I prototyped the solution in VBScript (below) </p>\n\n<pre><code>function fadd( n1, n2 )\n dim s1, s2, max, mul, res\n normalise3 n1, n2, s1, s2, max\n s1 = replace( s1, \".\", \"\" )\n s2 = replace( s2, \".\", \"\" )\n mul = clng(s1) + clng(s2)\n res = left( mul, len(mul) - max ) &amp; \".\" &amp; mid( mul, len( mul ) - max + 1 )\n fadd = res\nend function\n\nsub normalise3( byval n1, byval n2, byref s1, byref s2, byref numOfDigits )\n dim a1, a2\n dim max\n if instr( n1, \".\" ) = 0 then n1 = n1 &amp; \".\"\n if instr( n2, \".\" ) = 0 then n2 = n2 &amp; \".\"\n a1 = split( n1, \".\" )\n a2 = split( n2, \".\" )\n max = len( a1(1) )\n if len( a2(1) ) &gt; max then max = len( a2( 1 ) )\n s1 = a1(0) &amp; \".\" &amp; a1(1) &amp; string( max - len( a1( 1 )), \"0\" )\n s2 = a2(0) &amp; \".\" &amp; a2(1) &amp; string( max - len( a2( 1 )), \"0\" )\n numOfDigits = max\nend sub\n</code></pre>\n\n<p>and finally in Visual C++ (below).</p>\n\n<pre><code>#define Z(x) mpz_t x; mpz_init( x );\n\nBSTR __stdcall FADD( BSTR p1, BSTR p2 ) {\n USES_CONVERSION;\n\n LPSTR sP1 = W2A( p1 );\n LPSTR sP2 = W2A( p2 );\n\n char LeftOf1[ 1024 ];\n char RightOf1[ 1024 ];\n char LeftOf2[ 1024 ];\n char RightOf2[ 1024 ];\n char * dotPos;\n long numOfDigits;\n int i;\n int amtOfZeroes;\n\n dotPos = strstr( sP1, \".\" );\n if ( dotPos == NULL ) {\n strcpy( LeftOf1, sP1 );\n *RightOf1 = '\\0';\n } else {\n *dotPos = '\\0';\n strcpy( LeftOf1, sP1 );\n strcpy( RightOf1, (dotPos + 1) );\n }\n\n dotPos = strstr( sP2, \".\" );\n if ( dotPos == NULL ) {\n strcpy( LeftOf2, sP2 );\n *RightOf2 = '\\0';\n } else {\n *dotPos = '\\0';\n strcpy( LeftOf2, sP2 );\n strcpy( RightOf2, (dotPos + 1) );\n }\n\n numOfDigits = strlen( RightOf1 ) &gt; strlen( RightOf2 ) ? strlen( RightOf1 ) : strlen( RightOf2 );\n\n strcpy( sP1, LeftOf1 );\n strcat( sP1, RightOf1 );\n amtOfZeroes = numOfDigits - strlen( RightOf1 );\n for ( i = 0; i &lt; amtOfZeroes; i++ ) {\n strcat( sP1, \"0\" );\n }\n strcpy( sP2, LeftOf2 );\n strcat( sP2, RightOf2 );\n amtOfZeroes = numOfDigits - strlen( RightOf2 );\n for ( i = 0; i &lt; amtOfZeroes; i++ ) {\n strcat( sP2, \"0\" );\n }\n\n\n Z(n1);\n Z(n2);\n Z(res);\n\n mpz_set_str( n1, sP1, 10 );\n mpz_set_str( n2, sP2, 10 );\n mpz_add( res, n1, n2 );\n\n char * buff = (char *) _alloca( mpz_sizeinbase( res, 10 ) + 2 + 1 );\n\n mpz_get_str(buff, 10, res);\n\n char * here = buff + strlen(buff) - numOfDigits; \n\n memmove( here + 1, here, strlen(buff)); // plus trailing null\n *(here) = '.';\n\n BSTR bResult = _com_util::ConvertStringToBSTR( buff );\n return bResult;\n}\n</code></pre>\n\n<p>I accept that the C is a bit ... well ... dodgy, so please feel free to critique it. All helpful comments gratefully received.</p>\n\n<p>I went on from here to implement FSUB and FMUL as well. FDIV was not nearly so satisfying, ending up in three versions and using rational numbers.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/426/" ]
In the code below I use `mpf_add` to add the string representation of two floating values. What I don't understand at this point is why `2.2 + 3.2 = 5.39999999999999999999999999999999999999`. I would have thought that `gmp` was smart enough to give `5.4`. What am I not comprehending about how gmp does floats? (BTW, when I first wrote this I wasn't sure how to insert a decimal point, thus the plus/minus digit stuff at the end) ``` BSTR __stdcall FBIGSUM(BSTR p1, BSTR p2 ) { USES_CONVERSION; F(n1); F(n2); F(res); LPSTR sNum1 = W2A( p1 ); LPSTR sNum2 = W2A( p2 ); mpf_set_str( n1, sNum1, 10 ); mpf_set_str( n2, sNum2, 10 ); mpf_add( res, n1, n2 ); char * buff = (char *) _alloca( 1024 ); char expBuffer[ 20 ]; mp_exp_t exp; mpf_get_str(buff, &exp, 10, 0, res); char * temp = ltoa( (long) exp, expBuffer, 10 ); if (exp >= 0) { strcat(buff, "+" ); } strcat(buff, expBuffer ); BSTR bResult = _com_util::ConvertStringToBSTR( buff ); return bResult; } ```
This is because of the inherent error of using floating-point arithmetic in a binary environment. See the [IEEE 754](http://en.wikipedia.org/wiki/IEEE_754) standard for more information.
178,963
<p>I have this working definition:</p> <pre><code>IDENTIFIER [a-zA-Z][a-zA-Z0-9]* </code></pre> <p>I don't want to keep repeating the [a-zA-Z] and [0-9], so I made two new definitions</p> <pre><code>DIGIT [0-9] VALID [a-zA-Z] </code></pre> <p>How can I rewrite the IDENTIFIER rule to use the DIGIT and VALID definitions?</p> <p>I don't know how to do the "second" match, I'm stuck here:</p> <pre><code>IDENTIFIER {VALID}[{VALID}{DIGIT}]* // This syntax is incorrect </code></pre> <p>Thanks.</p> <p>Edit: The entire test program that I'm using: <a href="http://pastebin.com/f5b64183f" rel="nofollow noreferrer">http://pastebin.com/f5b64183f</a>.</p>
[ { "answer_id": 178987, "author": "Keng", "author_id": 730, "author_profile": "https://Stackoverflow.com/users/730", "pm_score": -1, "selected": false, "text": "<p>I think this will do it, but I can't test it. Do you have sample data?</p>\n\n<pre><code>(?:[a-zA-Z])+(?:[0-9])+\n</code></pre>\n" }, { "answer_id": 179058, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 3, "selected": true, "text": "<p>It looks like you actually want:</p>\n\n<pre><code>IDENTIFIER {VALID}({VALID}|{DIGIT})*\n</code></pre>\n\n<p><code>[{VALID}{DIGIT}]</code> resolves to <code>[[A-Za-z][0-9]]</code> which is not a legal construct.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18403/" ]
I have this working definition: ``` IDENTIFIER [a-zA-Z][a-zA-Z0-9]* ``` I don't want to keep repeating the [a-zA-Z] and [0-9], so I made two new definitions ``` DIGIT [0-9] VALID [a-zA-Z] ``` How can I rewrite the IDENTIFIER rule to use the DIGIT and VALID definitions? I don't know how to do the "second" match, I'm stuck here: ``` IDENTIFIER {VALID}[{VALID}{DIGIT}]* // This syntax is incorrect ``` Thanks. Edit: The entire test program that I'm using: <http://pastebin.com/f5b64183f>.
It looks like you actually want: ``` IDENTIFIER {VALID}({VALID}|{DIGIT})* ``` `[{VALID}{DIGIT}]` resolves to `[[A-Za-z][0-9]]` which is not a legal construct.
178,964
<p><a href="https://stackoverflow.com/q/133925">JavaScript post request like a form submit</a> shows you how to submit a form that you create via POST in JavaScript. Below is my modified code.</p> <pre><code>var form = document.createElement("form"); form.setAttribute("method", "post"); form.setAttribute("action", "test.jsp"); var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", "id"); hiddenField.setAttribute("value", "bob"); form.appendChild(hiddenField); document.body.appendChild(form); // Not entirely sure if this is necessary form.submit(); </code></pre> <p>What I would like to do is open the results in a new window. I am currently using something like this to open a page in a new window:</p> <pre><code>onclick = window.open(test.html, '', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no'); </code></pre>
[ { "answer_id": 179015, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 9, "selected": true, "text": "<p>Add </p>\n\n<pre><code>&lt;form target=\"_blank\" ...&gt;&lt;/form&gt;\n</code></pre>\n\n<p>or</p>\n\n<pre><code>form.setAttribute(\"target\", \"_blank\");\n</code></pre>\n\n<p>to your form's definition.</p>\n" }, { "answer_id": 180999, "author": "Marko Dumic", "author_id": 5817, "author_profile": "https://Stackoverflow.com/users/5817", "pm_score": 7, "selected": false, "text": "<p>If you want to create and submit your form from Javascript as is in your question and you want to create popup window with custom features I propose this solution (I put comments above the lines i added):</p>\n\n<pre><code>var form = document.createElement(\"form\");\nform.setAttribute(\"method\", \"post\");\nform.setAttribute(\"action\", \"test.jsp\");\n\n// setting form target to a window named 'formresult'\nform.setAttribute(\"target\", \"formresult\");\n\nvar hiddenField = document.createElement(\"input\"); \nhiddenField.setAttribute(\"name\", \"id\");\nhiddenField.setAttribute(\"value\", \"bob\");\nform.appendChild(hiddenField);\ndocument.body.appendChild(form);\n\n// creating the 'formresult' window with custom features prior to submitting the form\nwindow.open('test.html', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');\n\nform.submit();\n</code></pre>\n" }, { "answer_id": 2390990, "author": "Edu Carrega", "author_id": 287546, "author_profile": "https://Stackoverflow.com/users/287546", "pm_score": 1, "selected": false, "text": "<p>I know this basic method:</p>\n\n<p>1)</p>\n\n<pre><code>&lt;input type=”image” src=”submit.png”&gt; (in any place)\n</code></pre>\n\n<p>2)</p>\n\n<pre><code>&lt;form name=”print”&gt;\n&lt;input type=”hidden” name=”a” value=”&lt;?= $a ?&gt;”&gt;\n&lt;input type=”hidden” name=”b” value=”&lt;?= $b ?&gt;”&gt;\n&lt;input type=”hidden” name=”c” value=”&lt;?= $c ?&gt;”&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>3)</p>\n\n<pre><code>&lt;script&gt;\n$(‘#submit’).click(function(){\n open(”,”results”);\n with(document.print)\n {\n method = “POST”;\n action = “results.php”;\n target = “results”;\n submit();\n }\n});\n&lt;/script&gt;\n</code></pre>\n\n<p>Works!</p>\n" }, { "answer_id": 12572772, "author": "luchaninov", "author_id": 437763, "author_profile": "https://Stackoverflow.com/users/437763", "pm_score": 3, "selected": false, "text": "<pre><code>var urlAction = 'whatever.php';\nvar data = {param1:'value1'};\n\nvar $form = $('&lt;form target=\"_blank\" method=\"POST\" action=\"' + urlAction + '\"&gt;');\n$.each(data, function(k,v){\n $form.append('&lt;input type=\"hidden\" name=\"' + k + '\" value=\"' + v + '\"&gt;');\n});\n$form.submit();\n</code></pre>\n" }, { "answer_id": 41526344, "author": "Grigory Kislin", "author_id": 548473, "author_profile": "https://Stackoverflow.com/users/548473", "pm_score": 2, "selected": false, "text": "<p>Simplest working solution for flow window (tested at Chrome):</p>\n\n<pre><code>&lt;form action='...' method=post target=\"result\" onsubmit=\"window.open('','result','width=800,height=400');\"&gt;\n &lt;input name=\"..\"&gt;\n ....\n&lt;/form&gt;\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
[JavaScript post request like a form submit](https://stackoverflow.com/q/133925) shows you how to submit a form that you create via POST in JavaScript. Below is my modified code. ``` var form = document.createElement("form"); form.setAttribute("method", "post"); form.setAttribute("action", "test.jsp"); var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", "id"); hiddenField.setAttribute("value", "bob"); form.appendChild(hiddenField); document.body.appendChild(form); // Not entirely sure if this is necessary form.submit(); ``` What I would like to do is open the results in a new window. I am currently using something like this to open a page in a new window: ``` onclick = window.open(test.html, '', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no'); ```
Add ``` <form target="_blank" ...></form> ``` or ``` form.setAttribute("target", "_blank"); ``` to your form's definition.
178,973
<p>I'm a big fan of <a href="http://logging.apache.org/log4net" rel="noreferrer">log4net</a>, but recently, some (in my department) have questioned its inclusion in our projects because of the seemingly heaviness of each logging method. I would argue that there are better techniques than others, but that's another question.</p> <p>I'm curious to know, what is the typical impact of a log4net DebugFormat-type call on your applications. I'm going to leave out variables like number of log statements per lines of code, etc, because I'm just looking for anything that you've seen in the real world.</p> <p>And, I am aware of the simple technique of adding a guard clause to long evaluation statements eg:</p> <pre><code>if (log.IsDebug) { log.DebugFormat(...); } </code></pre> <p>So, let's exclude that from consideration for now.</p>
[ { "answer_id": 179092, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://logging.apache.org/log4net/release/faq.html#perf-not-logging\" rel=\"nofollow noreferrer\">log4net FAQ has an answer to this</a>, although not to the level of detail you are looking for.</p>\n\n<p>In summary: use those guard clauses.</p>\n" }, { "answer_id": 179120, "author": "Will Hartung", "author_id": 13663, "author_profile": "https://Stackoverflow.com/users/13663", "pm_score": 5, "selected": true, "text": "<p>I am not familiar with log4net, or log.DebugFormat(...).</p>\n\n<p>But the cost of logging is really in two areas.</p>\n\n<p>The first is the logging call, and the second is the actual persisting of the log information.</p>\n\n<p>The guards help reduce the logging call to a minimum when the logging is not actually necessary. It tends to be very fast, since it's little more than a method call and a comparison of two scalars.</p>\n\n<p>However, when you don't use guards, the cost may well become the price of creating the actual logging arguments.</p>\n\n<p>For example, in log4j, this was a common idiom:</p>\n\n<pre><code>log.debug(\"Runtime error. Order #\" + order.getOrderNo() + \" is not posted.\");\n</code></pre>\n\n<p>Here, the cost is the actual evaluation of the string expression making the message. This is because regardless of the logging level, that expression, and the resulting string are created. Imagine if instead you had something like:</p>\n\n<pre><code>log.debug(\"Something wrong with this list: \" + longListOfData);\n</code></pre>\n\n<p>That could create a large and expensive string variable that, if the log level wasn't set for DEBUG, would simply be wasted.</p>\n\n<p>The guards:</p>\n\n<pre><code>if (log.isDebug()) {\n log.debug(...);\n}\n</code></pre>\n\n<p>Eliminate that problem, since the isDebug call is cheap, especially compared to the actual creation of the argument.</p>\n\n<p>In my code, I have written a wrapper for logging, and I can create logs like this:</p>\n\n<pre><code>log.debug(\"Runtime error. Order # {0} is not posted.\", order.getOrderNo());\n</code></pre>\n\n<p>This is a nice compromise. This relies on Java varargs, and my code checks the logging level, and then formats the message appropriately. This is almost as fast as the guards, but much cleaner to write.</p>\n\n<p>Now, log.DebugFormat may well do a similar thing, that I don't know.</p>\n\n<p>On top of this, of course, is the actual cost of logging (to the screen, to a file, to a socket, etc.). But that's just a cost you need to accept. My best practice for that, when practical, is to route the actual log messages to a queue, which is then reaped and output to the proper channel using a separate thread. This, at least, helps keep the logging out of line with the main computing, but it has expenses and complexity of its own.</p>\n" }, { "answer_id": 10606949, "author": "keisar", "author_id": 1344070, "author_profile": "https://Stackoverflow.com/users/1344070", "pm_score": 2, "selected": false, "text": "<p>Just Giving Will Hartung's answer a .NET perspective :)</p>\n\n<p>DebugFormat code is:</p>\n\n<pre><code>if (IsDebugEnabled)\n{\n Logger.Log(ThisDeclaringType, m_levelDebug, new SystemStringFormat(CultureInfo.InvariantCulture, format, args), null);\n}\n</code></pre>\n\n<p>Basically it is the same so it's my believe that when you use DebugFormat you don't need to use the guard clause (You may still have a small overhead but I think it's small enough to be ignored)</p>\n\n<p>would have left a comment but I don't have enough reputation :/</p>\n" }, { "answer_id": 13781018, "author": "Pablo Romeo", "author_id": 1373170, "author_profile": "https://Stackoverflow.com/users/1373170", "pm_score": 3, "selected": false, "text": "<p>I know this is an old thread, but how about using an approach that avoids filling the code with if statements based on log level, such as this one: \n<a href=\"http://www.beefycode.com/post/Extension-Methods-for-Deferred-Message-Formatting-in-Log4Net.aspx\">http://www.beefycode.com/post/Extension-Methods-for-Deferred-Message-Formatting-in-Log4Net.aspx</a></p>\n\n<p>Using lambda expression to build the message, you can avoid even evaluating it entirely.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5619/" ]
I'm a big fan of [log4net](http://logging.apache.org/log4net), but recently, some (in my department) have questioned its inclusion in our projects because of the seemingly heaviness of each logging method. I would argue that there are better techniques than others, but that's another question. I'm curious to know, what is the typical impact of a log4net DebugFormat-type call on your applications. I'm going to leave out variables like number of log statements per lines of code, etc, because I'm just looking for anything that you've seen in the real world. And, I am aware of the simple technique of adding a guard clause to long evaluation statements eg: ``` if (log.IsDebug) { log.DebugFormat(...); } ``` So, let's exclude that from consideration for now.
I am not familiar with log4net, or log.DebugFormat(...). But the cost of logging is really in two areas. The first is the logging call, and the second is the actual persisting of the log information. The guards help reduce the logging call to a minimum when the logging is not actually necessary. It tends to be very fast, since it's little more than a method call and a comparison of two scalars. However, when you don't use guards, the cost may well become the price of creating the actual logging arguments. For example, in log4j, this was a common idiom: ``` log.debug("Runtime error. Order #" + order.getOrderNo() + " is not posted."); ``` Here, the cost is the actual evaluation of the string expression making the message. This is because regardless of the logging level, that expression, and the resulting string are created. Imagine if instead you had something like: ``` log.debug("Something wrong with this list: " + longListOfData); ``` That could create a large and expensive string variable that, if the log level wasn't set for DEBUG, would simply be wasted. The guards: ``` if (log.isDebug()) { log.debug(...); } ``` Eliminate that problem, since the isDebug call is cheap, especially compared to the actual creation of the argument. In my code, I have written a wrapper for logging, and I can create logs like this: ``` log.debug("Runtime error. Order # {0} is not posted.", order.getOrderNo()); ``` This is a nice compromise. This relies on Java varargs, and my code checks the logging level, and then formats the message appropriately. This is almost as fast as the guards, but much cleaner to write. Now, log.DebugFormat may well do a similar thing, that I don't know. On top of this, of course, is the actual cost of logging (to the screen, to a file, to a socket, etc.). But that's just a cost you need to accept. My best practice for that, when practical, is to route the actual log messages to a queue, which is then reaped and output to the proper channel using a separate thread. This, at least, helps keep the logging out of line with the main computing, but it has expenses and complexity of its own.
178,976
<p>I am wondering what everyone thinks the best method of handling results from your own database is. Other teams may be involved and there is always the chance the procedure/data could be altered and erroneous results would occur. My question is this. Is it better to let and exception occur, catch and log it or try to handle all contingencies and hide the error? Say, something like below.</p> <pre><code>if (dr.Table.Columns.Contains("column") &amp;&amp; !dr["column"].Equals(DBNull.Value)) { this.value = (type)dr["column"]; } else { this.value= null; } </code></pre>
[ { "answer_id": 178990, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "<p>Personally I like failing fast - with an appropriately apologetic user message, of course. There are some things it's worth recovering from, but something like a column you expect to be non-null being null sounds more significant to me.</p>\n\n<p>Of course, I'd also try to set up some smoke tests to make sure you find out about it before production :)</p>\n" }, { "answer_id": 178999, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "<p>Database constraints should be taking care of most of this for you. For what isn't, I would suggest going back to the db design and fixing those constraints. </p>\n\n<p>Failing that, returning an exception on that field would be best so that the data can be fixed (or removed).</p>\n" }, { "answer_id": 182550, "author": "AJ.", "author_id": 7211, "author_profile": "https://Stackoverflow.com/users/7211", "pm_score": 0, "selected": false, "text": "<p>Handle everything you think is worth handling and catch exceptions if something \"impossible\" happens. </p>\n\n<p>As <a href=\"https://stackoverflow.com/questions/178976/sanitizing-database-return-data#178985\">@AviewAnew</a> says, you are perhaps being a little paranoid, but that doesn't mean you're wrong! </p>\n\n<p>I would have thought that a column missing would be much worse than a null value, so how about throwing an exception for a missing column? </p>\n\n<pre><code>try // wrap everything in a try/catch to handle things I haven't thought of\n{\n\n if ( !dr.Table.Columns.Contains(\"column\") )\n {\n throw new SomeSortOfException(\"cloumn: \" + column + \" is missing\" );\n }\n else // strictly don't need the else but it makes the code easier to follow\n {\n if (dr[\"column\"].Equals(DBNull.Value))\n {\n this.value= null;\n }\n else\n {\n this.value = (type) dr[\"column\"];\n }\n }\n}\ncatch( SomeSortOfException ex )\n{\n throw;\n}\ncatch( Exception ex )\n{\n // handle or throw impossible exceptions here\n}\n</code></pre>\n\n<p>On the other hand... if you're going to be putting all these checks throughout your code, the maintenance overhead is going to be considerable. ... it's another thing to consider. </p>\n\n<p>Your call!</p>\n" }, { "answer_id": 4219562, "author": "Stephanie Page", "author_id": 114529, "author_profile": "https://Stackoverflow.com/users/114529", "pm_score": 0, "selected": false, "text": "<p>I would put your effort into making sure it cannot happen in the first place or minimizing the chances that it can.</p>\n\n<p>For example from jonSkeet's post. If you expect a not-null condition for a column is there a constraint on that column? If no, you probably expect it because the DBA/DB developer told you it will be that way. I would tell them that you'll be relying on that fact and encourage, prod, cajole them into adding the not null constraint. If you're expect unique values, then ask for a unique constraint. Only uppercase characters, add a check constraint. There's little sense in your code checking for all uppercase and then the next app and the next app and the next app when it can be done once. Remember DRY -- Don't Repeat Yourself.</p>\n\n<p>For the missing column error, my proactive approach is to make sure that there's an understanding by the db development team as to which tables and views and procedures are used by applications. Each application should have it's own username, each app's username should be granted select on only the tables it needs - <em>not</em> as a security feature but as documentation. If you change THIS table, it's used by these apps. Same with procs, grant execute to the apps which use it. If you keep this tight, and inculcate a <em>\"check for external dependencies when making changes\"</em> attitude, you'll head a lot of those errors off.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8873/" ]
I am wondering what everyone thinks the best method of handling results from your own database is. Other teams may be involved and there is always the chance the procedure/data could be altered and erroneous results would occur. My question is this. Is it better to let and exception occur, catch and log it or try to handle all contingencies and hide the error? Say, something like below. ``` if (dr.Table.Columns.Contains("column") && !dr["column"].Equals(DBNull.Value)) { this.value = (type)dr["column"]; } else { this.value= null; } ```
Personally I like failing fast - with an appropriately apologetic user message, of course. There are some things it's worth recovering from, but something like a column you expect to be non-null being null sounds more significant to me. Of course, I'd also try to set up some smoke tests to make sure you find out about it before production :)
178,977
<p>In the Ajax toolkit you can use a Tab Container and add TabPanels to this. </p> <p>I have some controls that I want to be able to use across all tabs and the tailor the tabs with other controls as neccessary. </p> <p>My question is how do I reuse a panel on multiple tabs? Essentially I after something like this</p> <pre><code>&lt;TabContainer&gt; &lt;tabPanel1&gt; &lt;contentTemplate&gt; &lt;pnl1&gt;&lt;/pnl1&gt; //other controls here &lt;/contentTemplate&gt; &lt;/tabPanel1&gt; &lt;tabPanel2&gt; &lt;contentTemplate&gt; &lt;pnl1&gt;&lt;/pnl1&gt; //other controls here &lt;/contentTemplate&gt; &lt;tabPanel2&gt; &lt;/tabContainer&gt; &lt;pnl1&gt; //some controls here &lt;/pnl1&gt; </code></pre>
[ { "answer_id": 179246, "author": "Andy Brudtkuhl", "author_id": 12442, "author_profile": "https://Stackoverflow.com/users/12442", "pm_score": 2, "selected": true, "text": "<p>Make the panel a user control and then drop the user control in each tab panel.</p>\n\n<pre><code>&lt;TabContainer&gt;\n &lt;tabPanel1&gt;\n &lt;contentTemplate&gt;\n &lt;uc1:MyControl id=\"myControl\" runat=\"server\" /&gt;\n &lt;/contentTemplate&gt;\n &lt;/tablPanel1&gt;\n\n &lt;tabPanel2&gt;\n &lt;contentTemplate&gt;\n &lt;uc1:MyControl id=\"myControl2\" runat=\"server\" /&gt;\n &lt;/contentTemplate&gt;\n &lt;/tablPanel2&gt;\n&lt;/TabContainer&gt;\n\n&lt;uc1:MyControl id=\"myControl3\" runat=\"server\" /&gt;\n</code></pre>\n" }, { "answer_id": 179384, "author": "Dan Goldstein", "author_id": 23427, "author_profile": "https://Stackoverflow.com/users/23427", "pm_score": 0, "selected": false, "text": "<p>There isn't a way to reuse the same panel. I guess you could use JavaScript to attach the panel to a new parent every time a tab is clicked, but that seems like more trouble than its worth.</p>\n\n<p>Consider moving the panel outside the tabs so it's always be visible. Tabs are for changing content, and it may go against UI conventions to do what you're attempting.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/178977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11802/" ]
In the Ajax toolkit you can use a Tab Container and add TabPanels to this. I have some controls that I want to be able to use across all tabs and the tailor the tabs with other controls as neccessary. My question is how do I reuse a panel on multiple tabs? Essentially I after something like this ``` <TabContainer> <tabPanel1> <contentTemplate> <pnl1></pnl1> //other controls here </contentTemplate> </tabPanel1> <tabPanel2> <contentTemplate> <pnl1></pnl1> //other controls here </contentTemplate> <tabPanel2> </tabContainer> <pnl1> //some controls here </pnl1> ```
Make the panel a user control and then drop the user control in each tab panel. ``` <TabContainer> <tabPanel1> <contentTemplate> <uc1:MyControl id="myControl" runat="server" /> </contentTemplate> </tablPanel1> <tabPanel2> <contentTemplate> <uc1:MyControl id="myControl2" runat="server" /> </contentTemplate> </tablPanel2> </TabContainer> <uc1:MyControl id="myControl3" runat="server" /> ```
179,004
<p>Every time I make a project I develop several generic routines/modules/libraries that I expect I'll be using with other projects.</p> <p>Due to the speed of development I don't spend a lot of time making these modules perfect - just good enough for this project, and well enough documented and isolatable that I can easily add them to another project.</p> <p>So far so good.</p> <p>Now when I use them in another project inevitably I improve them - either adding new features/functions, fixing bugs, making them more general, etc.</p> <p>At that point I have several problems:</p> <ul> <li>I need to maintain the changes in the module for the code I'm working on</li> <li>I need to maintain those same changes in a central "module" repository</li> <li>I need to make sure that the updated modules are available for, but not automatically used in older projects, or sometimes even existing projects I'm already working on.</li> </ul> <p>How do you manage this? How are these problems different when you have teams working on various modules in different projects?</p> <p>-Adam</p>
[ { "answer_id": 179030, "author": "Simon Howard", "author_id": 24806, "author_profile": "https://Stackoverflow.com/users/24806", "pm_score": 0, "selected": false, "text": "<p>If the code is generic enough that you're using it in multiple projects, is it possible that you're reinventing the wheel? If, instead, you standardise on existing libraries, you'll have code that has already been well-tested and optimised, and you won't have anything to maintain.</p>\n" }, { "answer_id": 179059, "author": "PersistenceOfVision", "author_id": 6721, "author_profile": "https://Stackoverflow.com/users/6721", "pm_score": -1, "selected": false, "text": "<p>Take your pick of Software Version Control packages...</p>\n\n<p>For Example:<BR>\nSVN + TortoiseSVN is our current solution. (Free) <BR>\nSome prefer Visual Source Safe. (Not Free)</p>\n" }, { "answer_id": 179089, "author": "Lev", "author_id": 7224, "author_profile": "https://Stackoverflow.com/users/7224", "pm_score": 1, "selected": false, "text": "<p>Use version control, of course, as PersistenceOfVision said, and also keep a nightly build to make sure you don't break old projects.</p>\n" }, { "answer_id": 179116, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 5, "selected": true, "text": "<p>If you're using Subversion for all your projects, you can simply use <code>svn:externals</code>: this allows one repository to reference another repository, optionally fixed at a particular revision. For example,</p>\n\n<pre>svn://svn/shared\nsvn://svn/project1\n |- dir1\n |- dir2\n \\- svn:externals \"shared -r 3 svn://svn/shared\"\nsvn://svn/project2\n |- dir3\n \\- svn:externals \"shared -r 5 svn://svn/shared\"</pre>\n\n<p>Commit your changes to <code>svn://svn/shared</code>, and modify the <code>svn:externals</code> property in the individual projects when you're ready.</p>\n\n<p>Otherwise, using other VCS, you might simply keep a bunch of tags on <code>shared</code>, one for each project using <code>shared</code>, pointing to the version they use. Advance each tag to later versions when ready. This requires manually updating each project's copy of <code>shared</code>, though (one thing which makes <code>svn:externals</code> nice is that it happens automatically).</p>\n\n<p>If you're forking/branching <code>shared</code> for each individual project... well, that can work, but it takes manpower to maintain and merge changes.</p>\n\n<h2>[Edit]</h2>\n\n<p>Further references:</p>\n\n<p>See <a href=\"http://svnbook.red-bean.com/en/1.0/ch07s03.html\" rel=\"noreferrer\">External Definitions</a> in the <a href=\"http://svnbook.red-bean.com/\" rel=\"noreferrer\">svn book</a> for a tutorial and more details on <code>svn:externals</code>, and <a href=\"http://git.or.cz/gitwiki/GitSubmoduleTutorial\" rel=\"noreferrer\">git-submodule tutorial</a> for a similar feature in the DVCS <a href=\"http://git.or.cz/\" rel=\"noreferrer\">git</a>.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179004", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
Every time I make a project I develop several generic routines/modules/libraries that I expect I'll be using with other projects. Due to the speed of development I don't spend a lot of time making these modules perfect - just good enough for this project, and well enough documented and isolatable that I can easily add them to another project. So far so good. Now when I use them in another project inevitably I improve them - either adding new features/functions, fixing bugs, making them more general, etc. At that point I have several problems: * I need to maintain the changes in the module for the code I'm working on * I need to maintain those same changes in a central "module" repository * I need to make sure that the updated modules are available for, but not automatically used in older projects, or sometimes even existing projects I'm already working on. How do you manage this? How are these problems different when you have teams working on various modules in different projects? -Adam
If you're using Subversion for all your projects, you can simply use `svn:externals`: this allows one repository to reference another repository, optionally fixed at a particular revision. For example, ``` svn://svn/shared svn://svn/project1 |- dir1 |- dir2 \- svn:externals "shared -r 3 svn://svn/shared" svn://svn/project2 |- dir3 \- svn:externals "shared -r 5 svn://svn/shared" ``` Commit your changes to `svn://svn/shared`, and modify the `svn:externals` property in the individual projects when you're ready. Otherwise, using other VCS, you might simply keep a bunch of tags on `shared`, one for each project using `shared`, pointing to the version they use. Advance each tag to later versions when ready. This requires manually updating each project's copy of `shared`, though (one thing which makes `svn:externals` nice is that it happens automatically). If you're forking/branching `shared` for each individual project... well, that can work, but it takes manpower to maintain and merge changes. [Edit] ------ Further references: See [External Definitions](http://svnbook.red-bean.com/en/1.0/ch07s03.html) in the [svn book](http://svnbook.red-bean.com/) for a tutorial and more details on `svn:externals`, and [git-submodule tutorial](http://git.or.cz/gitwiki/GitSubmoduleTutorial) for a similar feature in the DVCS [git](http://git.or.cz/).
179,014
<p>I am using PHP with Apache on Linux, with Sendmail. I use the PHP <a href="http://php.net/manual/en/function.mail.php" rel="noreferrer"><code>mail</code></a> function. The email is sent, but the envelope has the <code>Apache_user@localhostname</code> in <code>MAIL FROM</code> (example [email protected]) and some remote mail servers reject this because the domain doesn't exist (obviously). Using <code>mail</code>, can I force it to change the envelope <code>MAIL FROM</code>?</p> <p>EDIT: If I add a header in the fourth field of the <code>mail</code>() function, that changes the <code>From</code> field in the headers of the body of the message, and DOES NOT change the envelope <code>MAIL FROM</code>.</p> <p>I can force it by spawning sendmail with <code>sendmail -t -odb -oi -frealname@realhost</code> and piping the email contents to it. Is this a better approach?</p> <p>Is there a better, simpler, more PHP appropriate way of doing this?</p> <p>EDIT: The bottom line is I should have RTM. Thanks for the answers folks, the fifth parameter works and all is well.</p>
[ { "answer_id": 179061, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 7, "selected": true, "text": "<p>mail() has a 4th and 5th parameter (optional). The 5th argument is what should be passed as options directly to sendmail. I use the following:</p>\n\n<pre><code>mail('[email protected]','subject!','body!','From: [email protected]','-f [email protected]');\n</code></pre>\n" }, { "answer_id": 179069, "author": "Joe Scylla", "author_id": 25771, "author_profile": "https://Stackoverflow.com/users/25771", "pm_score": 1, "selected": false, "text": "<p>You can try this (im not sure tho):</p>\n\n<pre><code>ini_set(\"sendmail_from\", [email protected]);\nmail(...);\nini_restore(\"sendmail_from\");\n</code></pre>\n" }, { "answer_id": 180004, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 1, "selected": false, "text": "<p>I would also recommend checking into <a href=\"http://phpmailer.codeworxtech.com\" rel=\"nofollow noreferrer\">PHPMailer</a>. It's great for creating and sending email, making the process a lot easier, along with support for SMTP.</p>\n" }, { "answer_id": 5433481, "author": "mr-euro", "author_id": 111600, "author_profile": "https://Stackoverflow.com/users/111600", "pm_score": -1, "selected": false, "text": "<p>What you actually need to do is <strong>change</strong> the <strong>hostname</strong> of the machine Apache is running on, plus the <strong>user</strong> Apache is running as.</p>\n\n<p>In your current case it is:</p>\n\n<ul>\n<li>Apache user:<strong>nobody</strong></li>\n<li>Server hostname: <strong>conniptin.internal</strong></li>\n</ul>\n\n<p>Changing those two values is pretty simple and will solve the root of your problem.</p>\n\n<p>Although if you need to do it from PHP then perhaps use the <code>system/exec</code> functions. I do not think it will work in practice though, as you need to restart Apache and probably also the entire host for the new names to be used.</p>\n" }, { "answer_id": 47109353, "author": "Vladimir Kornea", "author_id": 2407309, "author_profile": "https://Stackoverflow.com/users/2407309", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://php.net/manual/en/function.mail.php\" rel=\"nofollow noreferrer\">PHP Official documentation for mail()</a></p>\n\n<blockquote>\n <p><code>bool mail ( string $to , string $subject , string $message [, string\n $additional_headers [, string $additional_parameters ]] )</code></p>\n \n <p>...</p>\n \n <p><strong>additional_parameters (optional)</strong></p>\n \n <p>The <strong>additional_parameters</strong> parameter can be used to pass additional\n flags as command line options to the program configured to be used\n when sending mail, as defined by the <code>sendmail_path</code> configuration\n setting. For example, this can be used to <strong>set the envelope sender\n address</strong> when using sendmail with the <code>-f</code> sendmail option.</p>\n \n <p>This parameter is escaped by <code>escapeshellcmd()</code> internally to prevent\n command execution. <code>escapeshellcmd()</code> prevents command execution, but\n allows to add additional parameters. For security reasons, it is\n recommended for the user to sanitize this parameter to avoid adding\n unwanted parameters to the shell command.</p>\n \n <p>Since <code>escapeshellcmd()</code> is applied automatically, some characters that\n are allowed as email addresses by internet RFCs cannot be used. <strong>mail()</strong>\n can not allow such characters, so in programs where the use of such\n characters is required, alternative means of sending emails (such as\n using a framework or a library) is recommended.</p>\n \n <p>The user that the webserver runs as should be added as a trusted user\n to the sendmail configuration to prevent a '<code>X-Warning</code>' header from\n being added to the message when the envelope sender (<code>-f</code>) is set using\n this method. For sendmail users, this file is <code>/etc/mail/trusted-users</code>.</p>\n</blockquote>\n" }, { "answer_id": 74613715, "author": "Tony", "author_id": 6223639, "author_profile": "https://Stackoverflow.com/users/6223639", "pm_score": 0, "selected": false, "text": "<p>following to php manual additinal -f parameter need to be passed to mail function</p>\n<p>Not as many write here &quot;-f [email protected]&quot; but without white space &quot;[email protected]&quot;</p>\n<p><a href=\"https://www.php.net/manual/en/function.mail.php\" rel=\"nofollow noreferrer\">https://www.php.net/manual/en/function.mail.php</a></p>\n<p><a href=\"https://i.stack.imgur.com/gTEpP.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gTEpP.png\" alt=\"See example#4 in manual\" /></a></p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179014", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13667/" ]
I am using PHP with Apache on Linux, with Sendmail. I use the PHP [`mail`](http://php.net/manual/en/function.mail.php) function. The email is sent, but the envelope has the `Apache_user@localhostname` in `MAIL FROM` (example [email protected]) and some remote mail servers reject this because the domain doesn't exist (obviously). Using `mail`, can I force it to change the envelope `MAIL FROM`? EDIT: If I add a header in the fourth field of the `mail`() function, that changes the `From` field in the headers of the body of the message, and DOES NOT change the envelope `MAIL FROM`. I can force it by spawning sendmail with `sendmail -t -odb -oi -frealname@realhost` and piping the email contents to it. Is this a better approach? Is there a better, simpler, more PHP appropriate way of doing this? EDIT: The bottom line is I should have RTM. Thanks for the answers folks, the fifth parameter works and all is well.
mail() has a 4th and 5th parameter (optional). The 5th argument is what should be passed as options directly to sendmail. I use the following: ``` mail('[email protected]','subject!','body!','From: [email protected]','-f [email protected]'); ```
179,026
<p>In Gmail, I have a bunch of labeled messages.</p> <p>I'd like to use an IMAP client to get those messages, but I'm not sure what the search incantation is.</p> <pre><code>c = imaplib.IMAP4_SSL('imap.gmail.com') c.list() ('OK', [..., '(\\HasNoChildren) "/" "GM"', ...]) c.search(???) </code></pre> <p>I'm not finding many examples for this sort of thing.</p>
[ { "answer_id": 179356, "author": "Deestan", "author_id": 6848, "author_profile": "https://Stackoverflow.com/users/6848", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://mail.google.com/support/bin/answer.py?ctx=gmail&amp;hl=en&amp;answer=75725\" rel=\"noreferrer\">Labels are accessed exactly like IMAP folders</a>, according to Google.</p>\n" }, { "answer_id": 185499, "author": "Jeremy Dunck", "author_id": 17732, "author_profile": "https://Stackoverflow.com/users/17732", "pm_score": 0, "selected": false, "text": "<p>I've been pretty surprised that imaplib doesn't do a lot of the response parsing. And it seems that responses were crafted to be hard to parse.</p>\n\n<p>FWIW, to answer my own question:\n c.search(None, 'GM')</p>\n\n<p>(I have no idea what the '(\\HasNoChildren) \"/\"' part is about.)</p>\n" }, { "answer_id": 421752, "author": "cdleary", "author_id": 3594, "author_profile": "https://Stackoverflow.com/users/3594", "pm_score": 5, "selected": true, "text": "<p><code>imaplib</code> is intentionally a thin wrapper around the IMAP protocol, I assume to allow for a greater degree of user flexibility and a greater ability to adapt to changes in the IMAP specification. As a result, it doesn't really offer any structure for your search queries and requires you to be familiar with the <a href=\"http://www.faqs.org/rfcs/rfc3501.html\" rel=\"noreferrer\">IMAP specification</a>.</p>\n\n<p>As you'll see in section \"6.4.4. SEARCH Command\", there are many things you can specify for search criterion. Note that you have to <code>SELECT</code> a mailbox (IMAP's name for a folder) before you can search for anything. (Searching multiple folders simultaneously requires multiple IMAP connections, as I understand it.) <code>IMAP4.list</code> will help you figure out what the mailbox identifiers are.</p>\n\n<p>Also useful in formulating the strings you pass to <code>imaplib</code> is \"9. Formal Syntax\" from the RFC linked to above.</p>\n\n<p>The <code>r'(\\HasNoChildren) \"/\"'</code> is a mailbox flag on the root mailbox, <code>/</code>. See \"7.2.6. FLAGS Response\".</p>\n\n<p>Good luck!</p>\n" }, { "answer_id": 3101260, "author": "Avadhesh", "author_id": 365148, "author_profile": "https://Stackoverflow.com/users/365148", "pm_score": 3, "selected": false, "text": "<pre><code>import imaplib \nobj = imaplib.IMAP4_SSL('imap.gmail.com', 993)\nobj.login('username', 'password')\nobj.select('**label name**') # &lt;-- the label in which u want to search message\nobj.search(None, 'FROM', '\"LDJ\"')\n</code></pre>\n" }, { "answer_id": 36875058, "author": "Plínio César", "author_id": 1284485, "author_profile": "https://Stackoverflow.com/users/1284485", "pm_score": 2, "selected": false, "text": "<p>The easiest way to use imaplib with Gmail is to use the <code>X-GM-RAW</code> attribute as described in the <a href=\"https://developers.google.com/gmail/imap_extensions#special-use_extension_of_the_list_command\" rel=\"nofollow\">Gmail Imap Extensions page</a>.</p>\n\n<p>The process would be like this:</p>\n\n<p>First connect to the account with the appropriate email and password:</p>\n\n<pre><code>c = imaplib.IMAP4_SSL('imap.gmail.com', 993)\nemail = 'eggs@spam'\npassword = 'spamspamspam'\nc.login(email, password)\n</code></pre>\n\n<p>Then connect to one of the folders/labels:</p>\n\n<pre><code>c.select(\"INBOX\")\n</code></pre>\n\n<p>If necessary, you can list all the available folders/labels with <code>c.list()</code>.</p>\n\n<p>Finally, use the search method:</p>\n\n<pre><code>gmail_search = \"has:attachment eggs OR spam\"\nstatus, data = c.search(None, 'X-GM-RAW', gmail_search)\n</code></pre>\n\n<p>In the <code>gmail_search</code> you can use the same search syntax used in <a href=\"https://support.google.com/mail/answer/7190?hl=en\" rel=\"nofollow\">gmail advanced search</a>.</p>\n\n<p>The search command will return the status of the command and the ids of all the messages that match your gmail_search.</p>\n\n<p>After this you can fetch each messages by id with:</p>\n\n<pre><code>for id in data[0].split():\n status, data = gmail.fetch(id, '(BODY[TEXT])')\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17732/" ]
In Gmail, I have a bunch of labeled messages. I'd like to use an IMAP client to get those messages, but I'm not sure what the search incantation is. ``` c = imaplib.IMAP4_SSL('imap.gmail.com') c.list() ('OK', [..., '(\\HasNoChildren) "/" "GM"', ...]) c.search(???) ``` I'm not finding many examples for this sort of thing.
`imaplib` is intentionally a thin wrapper around the IMAP protocol, I assume to allow for a greater degree of user flexibility and a greater ability to adapt to changes in the IMAP specification. As a result, it doesn't really offer any structure for your search queries and requires you to be familiar with the [IMAP specification](http://www.faqs.org/rfcs/rfc3501.html). As you'll see in section "6.4.4. SEARCH Command", there are many things you can specify for search criterion. Note that you have to `SELECT` a mailbox (IMAP's name for a folder) before you can search for anything. (Searching multiple folders simultaneously requires multiple IMAP connections, as I understand it.) `IMAP4.list` will help you figure out what the mailbox identifiers are. Also useful in formulating the strings you pass to `imaplib` is "9. Formal Syntax" from the RFC linked to above. The `r'(\HasNoChildren) "/"'` is a mailbox flag on the root mailbox, `/`. See "7.2.6. FLAGS Response". Good luck!
179,054
<p>I'm writing an app which for various reasons involves Internet Explorer (IE7, for the record), ActiveX controls, and a heroic amount of JavaScript, which is spread across multiple .js includes. </p> <p>One of our remote testers is experiencing an error message and IE's error message says something to the effect of:</p> <pre><code>Line: 719 Char: 5 Error: Unspecified Error Code: 0 URL: (the URL of the machine) </code></pre> <p>There's only one JavaScript file which has over 719 lines and line 719 is a blank line (in this case).</p> <p>None of the HTML or other files involved in the project have 719 or more lines, but the resulting HTML (it's sort of a server-side-include thing), at least as IE shows from "View Source" does have 719 or more lines - but line 719 (in this case) is a closing table row tag (no JavaScript, in other words).</p> <p>The results of "View Generated Source" is only 310 lines in this case.</p> <p>I would imagine that it could possibly be that the entire page, with the contents of the JavaScript files represented inline with the rest of the HTML could be where the error is referring to but I don't know any good way to view what that would be,</p> <p>So, given a JavaScript error from Internet Explorer <strong>where the line number is the only hint</strong> but the page is actually spread across multiple files?</p> <p><strong>UPDATE:</strong> The issue is exacerbated by the fact that the user experiencing this is remote and for various network reasons, debugging it using something like Visual Studio 2008 (which has awesome JavaScript debugging, by the way) is impossible. I'm limited to having one of us look at the source to try and figure out what line of code it's crapping out on.</p> <p><strong>UPDATE 2:</strong> The real answer (as accepted below) seems to be "no, not really". For what it's worth though, Robert J. Walker's bit about it being off by one did get me pointed in the right direction as I think it was the offending line. But since that's not really what I'd call good or reliable (IE's fault, not Robert J. Walker's fault) I'm going to accept the "no, not really" answer. I'm not sure if this is proper SO etiquette. Please let me know if it's not via the comments.</p>
[ { "answer_id": 179076, "author": "Matt R", "author_id": 4298, "author_profile": "https://Stackoverflow.com/users/4298", "pm_score": 2, "selected": false, "text": "<p>The best way I found to debug javascript was to add several Response.Write() or alert message near the place i believed the code broke. The write or alert that doesn't show is closest to the problematic area of the code.</p>\n\n<p>I did it this way because I haven't found an easier way. </p>\n\n<p>Update: If you use this method of debugging you can use the writes/alerts to the contents of variables as well.</p>\n" }, { "answer_id": 179083, "author": "Zombies", "author_id": 17675, "author_profile": "https://Stackoverflow.com/users/17675", "pm_score": 1, "selected": false, "text": "<p>Try Firebug. I is available for IE: <a href=\"http://getfirebug.com/lite.html\" rel=\"nofollow noreferrer\">http://getfirebug.com/lite.html</a></p>\n" }, { "answer_id": 179095, "author": "steve_c", "author_id": 769, "author_profile": "https://Stackoverflow.com/users/769", "pm_score": 1, "selected": false, "text": "<p>Have you checked whether this error is also present in Firefox using Firebug? That would be my first step in attempting to figure out where this error is occurring. </p>\n\n<p>If it isn't present in Firefox, then I would progress to enabling script debugging in IE. </p>\n" }, { "answer_id": 179098, "author": "sebagomez", "author_id": 23893, "author_profile": "https://Stackoverflow.com/users/23893", "pm_score": 0, "selected": false, "text": "<p>I use <a href=\"http://projects.nikhilk.net/WebDevHelper/\" rel=\"nofollow noreferrer\">Web Development Helper</a></p>\n" }, { "answer_id": 179101, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 2, "selected": false, "text": "<p>The web developer toolbar in IE7 can give you a rendered source view.</p>\n\n<pre><code>View &gt; Source &gt; Dom (Page)\n</code></pre>\n\n<p>This might be more accurate when you consider the line numbers provided by IE for script errors.</p>\n" }, { "answer_id": 179107, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 1, "selected": false, "text": "<p>My only advice: don't use IE for debugging like this. It's the absolute worst of the mainstream browsers: I try to use Firefox (with Firebug) or Chrome/Safari to handle most issues.</p>\n\n<p>If you absolutely have to use IE, install the <a href=\"http://www.microsoft.com/en-us/download/details.aspx?id=18359\" rel=\"nofollow noreferrer\">IE Developer Toolbar</a> (which doesn't seem to help much with JavaScript errors), and/or install the Script Debugger</p>\n" }, { "answer_id": 179115, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 2, "selected": false, "text": "<p>By installing <a href=\"http://getfirebug.com/lite.html\" rel=\"nofollow noreferrer\">firebug lite</a> on your server for that page:</p>\n\n<pre><code>&lt;script type='text/javascript' \n src='http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js'&gt;\n&lt;/script&gt;\n</code></pre>\n\n<p>you can log to a virtual console with,</p>\n\n<pre><code>firebug.d.console.log(\"stuff and things\")\nfirebug.d.console.dir( {returnedObject:[\"404\", \"Object Not Found\"]} )\n</code></pre>\n\n<p>and ask your remote tester to get more details for you by pressing F12.</p>\n\n<p>I sort of suspect there's an unterminated string or an unmatched parenthesis or bracket out there.</p>\n" }, { "answer_id": 179117, "author": "noah", "author_id": 12034, "author_profile": "https://Stackoverflow.com/users/12034", "pm_score": 4, "selected": true, "text": "<p>In short. Not really. Try finding the error in FF first, and if that fails, you can get an almost as good debugger with <a href=\"http://www.berniecode.com/blog/2007/03/08/how-to-debug-javascript-with-visual-web-developer-express/\" rel=\"nofollow noreferrer\">Visual Web Developer</a>. Debugging IE just sucks for the most part.</p>\n" }, { "answer_id": 179371, "author": "morganizeit", "author_id": 25494, "author_profile": "https://Stackoverflow.com/users/25494", "pm_score": 2, "selected": false, "text": "<p>Nope, there isn't a way to make the built-in exception message suck less.</p>\n\n<p>Instead you'll need to use a debugger with IE. The best tutorial I've found for this is here:</p>\n\n<p><a href=\"http://www.berniecode.com/blog/2007/03/08/how-to-debug-javascript-with-visual-web-developer-express/\" rel=\"nofollow noreferrer\">http://www.berniecode.com/blog/2007/03/08/how-to-debug-javascript-with-visual-web-developer-express/</a></p>\n\n<p>Follow these instructions and when an error or exception occurs you will be shown the exact line in the correct file. You'll also see the value of variables in the current scope and you can setup \"watched\" items to help you debug.</p>\n\n<p>Aside from that, if you need logging and CSS Cascade inspection like Firebug I've had good results with DebugBar and JSCompanion:</p>\n\n<p><a href=\"http://www.debugbar.com/\" rel=\"nofollow noreferrer\">http://www.debugbar.com/</a>\n<a href=\"http://www.my-debugbar.com/wiki/CompanionJS/HomePage\" rel=\"nofollow noreferrer\">http://www.my-debugbar.com/wiki/CompanionJS/HomePage</a></p>\n" }, { "answer_id": 179635, "author": "Robert J. Walker", "author_id": 4287, "author_profile": "https://Stackoverflow.com/users/4287", "pm_score": 2, "selected": false, "text": "<p>Tip: I find that many IE error message line numbers are <em>off by one!</em></p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2577/" ]
I'm writing an app which for various reasons involves Internet Explorer (IE7, for the record), ActiveX controls, and a heroic amount of JavaScript, which is spread across multiple .js includes. One of our remote testers is experiencing an error message and IE's error message says something to the effect of: ``` Line: 719 Char: 5 Error: Unspecified Error Code: 0 URL: (the URL of the machine) ``` There's only one JavaScript file which has over 719 lines and line 719 is a blank line (in this case). None of the HTML or other files involved in the project have 719 or more lines, but the resulting HTML (it's sort of a server-side-include thing), at least as IE shows from "View Source" does have 719 or more lines - but line 719 (in this case) is a closing table row tag (no JavaScript, in other words). The results of "View Generated Source" is only 310 lines in this case. I would imagine that it could possibly be that the entire page, with the contents of the JavaScript files represented inline with the rest of the HTML could be where the error is referring to but I don't know any good way to view what that would be, So, given a JavaScript error from Internet Explorer **where the line number is the only hint** but the page is actually spread across multiple files? **UPDATE:** The issue is exacerbated by the fact that the user experiencing this is remote and for various network reasons, debugging it using something like Visual Studio 2008 (which has awesome JavaScript debugging, by the way) is impossible. I'm limited to having one of us look at the source to try and figure out what line of code it's crapping out on. **UPDATE 2:** The real answer (as accepted below) seems to be "no, not really". For what it's worth though, Robert J. Walker's bit about it being off by one did get me pointed in the right direction as I think it was the offending line. But since that's not really what I'd call good or reliable (IE's fault, not Robert J. Walker's fault) I'm going to accept the "no, not really" answer. I'm not sure if this is proper SO etiquette. Please let me know if it's not via the comments.
In short. Not really. Try finding the error in FF first, and if that fails, you can get an almost as good debugger with [Visual Web Developer](http://www.berniecode.com/blog/2007/03/08/how-to-debug-javascript-with-visual-web-developer-express/). Debugging IE just sucks for the most part.
179,072
<p>So, I was looking over my standard cache utility when preparing to unit test a controller and thought, hey, is accessing the HttpRuntime.Cache directly considered harmful in MVC?</p> <p>I wrap the cache in a proxy class that implements a cache-like interface (tho much simpler) so that I can mock it during tests. But I'm wondering if that's already done for me in the new framework. I can't find anything, however.</p> <p>Here's an idea of how I do it:</p> <pre><code>public ActionResult DoStuffLol(guid id) { var model = CacheUtil.GetOrCreateAndStore( "DoStuffLolModel", () =&gt; { /* construct model here; time consuming stuff */ return model; }); return View("DoStuffLol", model); } </code></pre> <p>So, has the old patterns of accessing the cache changed? Are there any better patterns for caching action results in MVC?</p>
[ { "answer_id": 179433, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 1, "selected": false, "text": "<p>Add the OutputCache attribute to your controller action in order to tell the framework to cache the output for you. You can read more about this attribute in <a href=\"http://weblogs.asp.net/scottgu/archive/2008/07/14/asp-net-mvc-preview-4-release-part-1.aspx\" rel=\"nofollow noreferrer\">ScottGu's blog post on ASP.NET Preview 4</a>.</p>\n\n<p><a href=\"http://weblogs.asp.net/stephenwalther/archive/2008/08/29/asp-net-mvc-tip-40-don-t-cache-pages-that-require-authorization.aspx\" rel=\"nofollow noreferrer\">Don't combine this with the Authorize attribute</a>, however.</p>\n" }, { "answer_id": 341596, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": true, "text": "<p>No, but the cache has changed in 3.5. 3.5 includes wrapper classes that make stubbing/mocking many of the static classes used in asp.net easy.</p>\n\n<p><a href=\"http://www.codethinked.com/post/2008/12/04/Using-SystemWebAbstractions-in-Your-WebForms-Apps.aspx\" rel=\"nofollow noreferrer\">http://www.codethinked.com/post/2008/12/04/Using-SystemWebAbstractions-in-Your-WebForms-Apps.aspx</a></p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
So, I was looking over my standard cache utility when preparing to unit test a controller and thought, hey, is accessing the HttpRuntime.Cache directly considered harmful in MVC? I wrap the cache in a proxy class that implements a cache-like interface (tho much simpler) so that I can mock it during tests. But I'm wondering if that's already done for me in the new framework. I can't find anything, however. Here's an idea of how I do it: ``` public ActionResult DoStuffLol(guid id) { var model = CacheUtil.GetOrCreateAndStore( "DoStuffLolModel", () => { /* construct model here; time consuming stuff */ return model; }); return View("DoStuffLol", model); } ``` So, has the old patterns of accessing the cache changed? Are there any better patterns for caching action results in MVC?
No, but the cache has changed in 3.5. 3.5 includes wrapper classes that make stubbing/mocking many of the static classes used in asp.net easy. <http://www.codethinked.com/post/2008/12/04/Using-SystemWebAbstractions-in-Your-WebForms-Apps.aspx>
179,085
<p>What is the difference between creating one index across multiple columns versus creating multiple indexes, one <em>per</em> column?</p> <p>Are there reasons why one should be used over the other?</p> <p>For example:</p> <pre><code>Create NonClustered Index IX_IndexName On TableName (Column1 Asc, Column2 Asc, Column3 Asc) </code></pre> <p>Versus:</p> <pre><code>Create NonClustered Index IX_IndexName1 On TableName (Column1 Asc) Create NonClustered Index IX_IndexName2 On TableName (Column2 Asc) Create NonClustered Index IX_IndexName3 On TableName (Column3 Asc) </code></pre>
[ { "answer_id": 179109, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 7, "selected": false, "text": "<p>Yes. I recommend you check out <a href=\"http://www.sqlskills.com/blogs/kimberly/category/indexes/\" rel=\"noreferrer\">Kimberly Tripp's articles on indexing</a>.</p>\n\n<p>If an index is \"covering\", then there is no need to use anything but the index. In SQL Server 2005, you can also add additional columns to the index that are not part of the key which can eliminate trips to the rest of the row.</p>\n\n<p>Having multiple indexes, each on a single column may mean that only one index gets used at all - you will have to refer to the execution plan to see what effects different indexing schemes offer.</p>\n\n<p>You can also use the tuning wizard to help determine what indexes would make a given query or workload perform the best.</p>\n" }, { "answer_id": 179129, "author": "Bob Probst", "author_id": 12424, "author_profile": "https://Stackoverflow.com/users/12424", "pm_score": 4, "selected": false, "text": "<p>If you have queries that will be frequently using a relatively static set of columns, creating a single covering index that includes them all will improve performance dramatically. </p>\n\n<p>By putting multiple columns in your index, the optimizer will only have to access the table directly if a column is not in the index. I use these a lot in data warehousing. The downside is that doing this can cost a lot of overhead, especially if the data is very volatile.</p>\n\n<p>Creating indexes on single columns is useful for lookup operations frequently found in OLTP systems.</p>\n\n<p>You should ask yourself why you're indexing the columns and how they'll be used. Run some query plans and see when they are being accessed. Index tuning is as much instinct as science.</p>\n" }, { "answer_id": 179133, "author": "MobyDX", "author_id": 3923, "author_profile": "https://Stackoverflow.com/users/3923", "pm_score": 6, "selected": false, "text": "<p>The multi-column index can be used for queries referencing <em>all</em> the columns:</p>\n\n<pre><code>SELECT *\nFROM TableName\nWHERE Column1=1 AND Column2=2 AND Column3=3\n</code></pre>\n\n<p>This can be looked up directly using the multi-column index. On the other hand, at most one of the single-column index can be used (it would have to look up all records having Column1=1, and then check Column2 and Column3 in each of those).</p>\n" }, { "answer_id": 179224, "author": "evilhomer", "author_id": 2806, "author_profile": "https://Stackoverflow.com/users/2806", "pm_score": 10, "selected": true, "text": "<p>I agree with <a href=\"https://stackoverflow.com/a/179109/50776\">Cade Roux</a>.</p>\n\n<p>This article should get you on the right track:</p>\n\n<ul>\n<li><a href=\"http://www.sqlskills.com/BLOGS/KIMBERLY/post.aspx?id=19f0ce1c-0d2f-4ad5-9b13-a615418422e0\" rel=\"noreferrer\">Indexes in SQL Server 2005/2008 – Best Practices, Part 1</a></li>\n<li><a href=\"http://www.sqlskills.com/blogs/kimberly/indexes-in-sql-server-20052008-part-2-internals/\" rel=\"noreferrer\">Indexes in SQL Server 2005/2008 – Part 2 – Internals</a> </li>\n</ul>\n\n<p>One thing to note, clustered indexes should have a unique key (an identity column I would recommend) as the first column. \nBasically it helps your data insert at the end of the index and not cause lots of disk IO and Page splits.</p>\n\n<p>Secondly, if you are creating other indexes on your data and they are constructed cleverly they will be reused. </p>\n\n<p>e.g. imagine you search a table on three columns</p>\n\n<p>state, county, zip. </p>\n\n<ul>\n<li>you sometimes search by state only. </li>\n<li>you sometimes search by state and county.</li>\n<li>you frequently search by state, county, zip. </li>\n</ul>\n\n<p>Then an index with state, county, zip. will be used in all three of these searches.</p>\n\n<p>If you search by zip alone quite a lot then the above index will not be used (by SQL Server anyway) as zip is the third part of that index and the query optimiser will not see that index as helpful. </p>\n\n<p>You could then create an index on Zip alone that would be used in this instance.</p>\n\n<p>By the way <a href=\"https://use-the-index-luke.com/sql/where-clause/the-equals-operator/concatenated-keys\" rel=\"noreferrer\">We can take advantage of the fact that with Multi-Column indexing the first index column is always usable for searching</a> and when you search only by 'state' it is efficient but yet not as efficient as Single-Column index on 'state'</p>\n\n<p>I guess the answer you are looking for is that it depends on your where clauses of your frequently used queries and also your group by's.</p>\n\n<p>The article will help a lot. :-)</p>\n" }, { "answer_id": 179925, "author": "ConcernedOfTunbridgeWells", "author_id": 15401, "author_profile": "https://Stackoverflow.com/users/15401", "pm_score": 4, "selected": false, "text": "<p>One item that seems to have been missed is star transformations. <a href=\"http://www.databasejournal.com/features/mssql/article.php/1438821\" rel=\"noreferrer\">Index Intersection </a>operators resolve the predicate by calculating the set of rows hit by each of the predicates before any I/O is done on the fact table. On a star schema you would index each individual dimension key and the query optimiser can resolve which rows to select by the index intersection computation. The indexes on individual columns give the best flexibility for this.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/383/" ]
What is the difference between creating one index across multiple columns versus creating multiple indexes, one *per* column? Are there reasons why one should be used over the other? For example: ``` Create NonClustered Index IX_IndexName On TableName (Column1 Asc, Column2 Asc, Column3 Asc) ``` Versus: ``` Create NonClustered Index IX_IndexName1 On TableName (Column1 Asc) Create NonClustered Index IX_IndexName2 On TableName (Column2 Asc) Create NonClustered Index IX_IndexName3 On TableName (Column3 Asc) ```
I agree with [Cade Roux](https://stackoverflow.com/a/179109/50776). This article should get you on the right track: * [Indexes in SQL Server 2005/2008 – Best Practices, Part 1](http://www.sqlskills.com/BLOGS/KIMBERLY/post.aspx?id=19f0ce1c-0d2f-4ad5-9b13-a615418422e0) * [Indexes in SQL Server 2005/2008 – Part 2 – Internals](http://www.sqlskills.com/blogs/kimberly/indexes-in-sql-server-20052008-part-2-internals/) One thing to note, clustered indexes should have a unique key (an identity column I would recommend) as the first column. Basically it helps your data insert at the end of the index and not cause lots of disk IO and Page splits. Secondly, if you are creating other indexes on your data and they are constructed cleverly they will be reused. e.g. imagine you search a table on three columns state, county, zip. * you sometimes search by state only. * you sometimes search by state and county. * you frequently search by state, county, zip. Then an index with state, county, zip. will be used in all three of these searches. If you search by zip alone quite a lot then the above index will not be used (by SQL Server anyway) as zip is the third part of that index and the query optimiser will not see that index as helpful. You could then create an index on Zip alone that would be used in this instance. By the way [We can take advantage of the fact that with Multi-Column indexing the first index column is always usable for searching](https://use-the-index-luke.com/sql/where-clause/the-equals-operator/concatenated-keys) and when you search only by 'state' it is efficient but yet not as efficient as Single-Column index on 'state' I guess the answer you are looking for is that it depends on your where clauses of your frequently used queries and also your group by's. The article will help a lot. :-)
179,102
<p>I want to get a <code>System.Type</code> given only the type name in a <code>string</code>.</p> <p>For instance, if I have an object:</p> <pre><code>MyClass abc = new MyClass(); </code></pre> <p>I can then say:</p> <pre><code>System.Type type = abc.GetType(); </code></pre> <p>But what if all I have is:</p> <pre><code>string className = "MyClass"; </code></pre>
[ { "answer_id": 179110, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 5, "selected": false, "text": "<pre><code>Type type = Type.GetType(\"foo.bar.MyClass, foo.bar\");\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx\" rel=\"noreferrer\">MSDN</a>. Make sure the name is <a href=\"http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx\" rel=\"noreferrer\">Assembly Qualified</a>.</p>\n" }, { "answer_id": 179111, "author": "jalbert", "author_id": 1360388, "author_profile": "https://Stackoverflow.com/users/1360388", "pm_score": 1, "selected": false, "text": "<pre><code>Type type = Type.GetType(\"MyClass\");\n</code></pre>\n\n<p>Make sure to include the namespace. There are overloads of the method that control case-sensitivity and whether an exception is thrown if the type name isn't found.</p>\n" }, { "answer_id": 179397, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": 2, "selected": false, "text": "<p>To create an instance of your class after you get the type, and invoke a method - </p>\n\n<pre><code>Type type = Type.GetType(\"foo.bar.MyClass, foo.bar\");\nobject instanceObject = System.Reflection.Activator.CreateInstance(type);\ntype.InvokeMember(method, BindingFlags.InvokeMethod, null, instanceObject, new object[0]);\n</code></pre>\n" }, { "answer_id": 7286512, "author": "dmihailescu", "author_id": 925434, "author_profile": "https://Stackoverflow.com/users/925434", "pm_score": 0, "selected": false, "text": "<p><code>Type.GetType(...)</code>might fail sometimes if the <code>typeof</code> operator can not be used.</p>\n\n<p>Instead you can reflect on the assemblies from the current domain in order to do it.</p>\n\n<p>check my response on <a href=\"https://stackoverflow.com/questions/2367652/how-type-gettype-works-when-given-partially-qualified-type-name/7286354#7286354\">this thread</a></p>\n" }, { "answer_id": 14625254, "author": "Chris W", "author_id": 890258, "author_profile": "https://Stackoverflow.com/users/890258", "pm_score": 1, "selected": false, "text": "<p>Another way to get the type from current or another assebly.</p>\n\n<p>(Assumes that the class namespace contains its assembly):</p>\n\n<hr>\n\n<pre><code>public static Type GetType(string fullName)\n{\n if (string.IsNullOrEmpty(fullName))\n return null;\n Type type = Type.GetType(fullName);\n if (type == null)\n {\n string targetAssembly = fullName;\n while (type == null &amp;&amp; targetAssembly.Length &gt; 0)\n {\n try\n {\n int dotInd = targetAssembly.LastIndexOf('.');\n targetAssembly = dotInd &gt;= 0 ? targetAssembly.Substring(0, dotInd) : \"\";\n if (targetAssembly.Length &gt; 0)\n type = Type.GetType(fullName + \", \" + targetAssembly);\n }\n catch { }\n }\n }\n return type;\n}\n</code></pre>\n" }, { "answer_id": 18997449, "author": "shadow", "author_id": 1393087, "author_profile": "https://Stackoverflow.com/users/1393087", "pm_score": 0, "selected": false, "text": "<p>Here is a simple method for creating and initializing a new object from its name and parameters:</p>\n\n<pre><code> // Creates and initializes a new object from its name and parameters\n public Object CreateObjectByName(string name, params Object[] args)\n {\n string s = \"&lt;prefix&gt;\" + name; // case sensitive; Type.FullName\n Type type = Type.GetType(s);\n Object o = System.Activator.CreateInstance(type, args);\n return o;\n }\n</code></pre>\n\n<p>One example of how one might use this is to read a file containing class names [or partial class names] and parameters and then add the objects returned to a list of objects of a base type that is common to the objects created.</p>\n\n<p>To see what your class name [or ] should look like, temporarily use something like this [if your class is named NewClass]:</p>\n\n<pre><code> string z = (new NewClass(args)).GetType().FullName;\n</code></pre>\n" }, { "answer_id": 20407903, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 5, "selected": false, "text": "<p>It depends on which assembly the class is. If it's in <code>mscorlib</code> or calling assembly all you need is </p>\n\n<pre><code>Type type = Type.GetType(\"namespace.class\");\n</code></pre>\n\n<p>But if it's referenced from some other assembly, you would need to do:</p>\n\n<pre><code>Assembly assembly = typeof(SomeKnownTypeInAssembly).Assembly;\nType type = assembly.GetType(\"namespace.class\");\n\n//or\n\nType type = Type.GetType(\"namespace.class, assembly\");\n</code></pre>\n\n<hr>\n\n<p>If you only have the class name \"MyClass\", then you have to somehow get the namespace name (or both namespace name and assembly name in case it's a referenced assembly) and concat that along with the class name. Something like:</p>\n\n<pre><code>//if class is in same assembly\nvar namespace = typeof(SomeKnownTypeInNamespace).Namespace;\nType type = Type.GetType(namespace + \".\" + \"MyClass\");\n\n\n//or for cases of referenced classes\nvar assembly = typeof(SomeKnownTypeInAssembly).Assembly;\nvar namespace = typeof(SomeKnownTypeInNamespace).Namespace;\nType type = assembly.GetType(namespace + \".\" + \"MyClass\");\n//or\nType type = Type.GetType(namespace + \".\" + \"MyClass\" + \", \" + assembly.GetName().Name);\n</code></pre>\n\n<hr>\n\n<p>If you have absolutely nothing (no preawareness of even assembly name or namespace name) but just the class name, then you can query the entire assemblies to select a matching string. <strong>But that should be a lot slower</strong>:</p>\n\n<pre><code>Type type = AppDomain.CurrentDomain.GetAssemblies()\n .SelectMany(x =&gt; x.GetTypes())\n .FirstOrDefault(x =&gt; x.Name == \"MyClass\");\n</code></pre>\n\n<p><strong>Note that this returns the first matching class, so need not be very accurate if you would have multiple classes with same name across assemblies/namespaces.</strong> In any case caching the values makes sense here. <strong>Slightly faster way is to assume there is one default namespace</strong>: </p>\n\n<pre><code>Type type = AppDomain.CurrentDomain.GetAssemblies()\n .Select(a =&gt; new { a, a.GetTypes().First().Namespace })\n .Select(x =&gt; x.a.GetType(x.Namespace + \".\" + \"MyClass\"))\n .FirstOrDefault(x =&gt; x != null);\n</code></pre>\n\n<p>But that's again an assumption that your type will have the same namespace as some other random class in the assembly; too brittle, not very good.</p>\n\n<hr>\n\n<p>If you want classes of other domains you can get a list of all application domains, following <a href=\"https://stackoverflow.com/questions/388554/list-appdomains-in-process\">this link.</a> You can then do the same querying as shown above for each domain. If your assembly where the type resides isn't loaded yet, then you have to manually load it using <code>Assembly.Load</code>, <code>Assembly.LoadFrom</code> etc.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10722/" ]
I want to get a `System.Type` given only the type name in a `string`. For instance, if I have an object: ``` MyClass abc = new MyClass(); ``` I can then say: ``` System.Type type = abc.GetType(); ``` But what if all I have is: ``` string className = "MyClass"; ```
``` Type type = Type.GetType("foo.bar.MyClass, foo.bar"); ``` [MSDN](http://msdn.microsoft.com/en-us/library/w3f99sx1.aspx). Make sure the name is [Assembly Qualified](http://msdn.microsoft.com/en-us/library/system.type.assemblyqualifiedname.aspx).
179,113
<p>Say I've got two scheduled processes: A and B.</p> <p>Given that B should not run until A has completed, how might I gracefully enforce this dependency?</p> <p>Approaches that have been considered:</p> <ol> <li><p>Have A schedule B upon completion. This has the downside of B never being scheduled if for some reason A failed.</p></li> <li><p>When B runs, have it ping A to see if the latter has completed. How this might be accomplished (network, file, database record, message queue) could be messy and problematic introducing a third dependency.</p></li> <li><p>Combine A and B into a single process. This has the downside of tightly binding the two, making it harder to re-run one or the other in isolation if need be.</p></li> </ol> <p>Thoughts?</p>
[ { "answer_id": 179118, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 3, "selected": true, "text": "<p>Your option 1 directly answers your question: if B is dependent on A, and A fails, A not scheduling B means that B can't happen.</p>\n\n<p>Unless B merely has to run after A does, whether or not A was successful.</p>\n\n<p>In that case, something like the following (in bash) would work:</p>\n\n<pre><code>A &amp;&amp; B\n</code></pre>\n" }, { "answer_id": 179124, "author": "Craig Walker", "author_id": 3488, "author_profile": "https://Stackoverflow.com/users/3488", "pm_score": 1, "selected": false, "text": "<p>You could modify step 3: Create your two processes to run in isolation, and then create a third process that runs the other two.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4061/" ]
Say I've got two scheduled processes: A and B. Given that B should not run until A has completed, how might I gracefully enforce this dependency? Approaches that have been considered: 1. Have A schedule B upon completion. This has the downside of B never being scheduled if for some reason A failed. 2. When B runs, have it ping A to see if the latter has completed. How this might be accomplished (network, file, database record, message queue) could be messy and problematic introducing a third dependency. 3. Combine A and B into a single process. This has the downside of tightly binding the two, making it harder to re-run one or the other in isolation if need be. Thoughts?
Your option 1 directly answers your question: if B is dependent on A, and A fails, A not scheduling B means that B can't happen. Unless B merely has to run after A does, whether or not A was successful. In that case, something like the following (in bash) would work: ``` A && B ```
179,123
<p>I wrote the wrong thing in a commit message.</p> <p>How can I change the message? The commit has not been pushed yet.</p>
[ { "answer_id": 179147, "author": "EfForEffort", "author_id": 14113, "author_profile": "https://Stackoverflow.com/users/14113", "pm_score": 15, "selected": true, "text": "<h1>Amending the most recent commit message</h1>\n<pre class=\"lang-sh prettyprint-override\"><code>git commit --amend\n</code></pre>\n<p>will open your editor, allowing you to change the commit message of the most recent commit. Additionally, you can set the commit message directly in the command line with:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>git commit --amend -m &quot;New commit message&quot;\n</code></pre>\n<p>…however, this can make multi-line commit messages or small corrections more cumbersome to enter.</p>\n<p>Make sure you don't have any working copy changes <em>staged</em> before doing this or they will get committed too. (<em>Unstaged</em> changes will not get committed.)</p>\n<h2>Changing the message of a commit that you've already pushed to your remote branch</h2>\n<p>If you've already pushed your commit up to your remote branch, then - after amending your commit locally (as described above) - you'll also <a href=\"https://stackoverflow.com/questions/41003071/why-must-i-force-push-after-changing-a-commit-message\">need to force push the commit</a> with:</p>\n<pre class=\"lang-bash prettyprint-override\"><code>git push &lt;remote&gt; &lt;branch&gt; --force\n# Or\ngit push &lt;remote&gt; &lt;branch&gt; -f\n</code></pre>\n<p><strong>Warning: force-pushing will overwrite the remote branch with the state of your local one</strong>. If there are commits on the remote branch that you don't have in your local branch, you <em>will</em> lose those commits.</p>\n<p><strong>Warning: be cautious about amending commits that you have already shared with other people.</strong> Amending commits essentially <em>rewrites</em> them to have different <a href=\"https://en.wikipedia.org/wiki/SHA-1\" rel=\"noreferrer\">SHA</a> IDs, which poses a problem if other people have copies of the old commit that you've rewritten. Anyone who has a copy of the old commit will need to synchronize their work with your newly re-written commit, which can sometimes be difficult, so make sure you coordinate with others when attempting to rewrite shared commit history, or just avoid rewriting shared commits altogether.</p>\n<hr />\n<h3>Perform an interactive rebase</h3>\n<p>Another option is to use interactive rebase.\nThis allows you to edit any message you want to update even if it's not the latest message.</p>\n<p>In order to do a Git squash, follow these steps:</p>\n<pre><code>// n is the number of commits up to the last commit you want to be able to edit\ngit rebase -i HEAD~n\n</code></pre>\n<p>Once you squash your commits - choose the <code>e/r</code> for editing the message:</p>\n<p><a href=\"https://i.stack.imgur.com/LVcm9.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/LVcm9.png\" alt=\"Screenshot of terminal while editing commit\" /></a></p>\n<h3>Important note about interactive rebase</h3>\n<p>When you use <code>git rebase -i HEAD~n</code> there can be <strong>more</strong> than n commits. Git will &quot;collect&quot; all the commits in the last n commits, and if there was a merge somewhere in between that range you will see all the commits as well, so the outcome will be n + .</p>\n<h3>Good tip:</h3>\n<p>If you have to do it for more than a single branch and you might face conflicts when amending the content, set up <a href=\"https://stackoverflow.com/questions/35415925/is-it-possible-to-setup-git-merge-for-automatic-resolving-git-rerere/35417944#35417944\"><code>git rerere</code></a> and let Git resolve those conflicts automatically for you.</p>\n<hr />\n<h2>Documentation</h2>\n<ul>\n<li><p><a href=\"https://www.kernel.org/pub/software/scm/git/docs/git-commit.html\" rel=\"noreferrer\">git-commit(1) Manual Page</a></p>\n</li>\n<li><p><a href=\"https://www.kernel.org/pub/software/scm/git/docs/git-rebase.html\" rel=\"noreferrer\">git-rebase(1) Manual Page</a></p>\n</li>\n<li><p><a href=\"https://www.kernel.org/pub/software/scm/git/docs/git-push.html\" rel=\"noreferrer\">git-push(1) Manual Page</a></p>\n</li>\n</ul>\n" }, { "answer_id": 180085, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 11, "selected": false, "text": "<p>If the commit you want to fix isn’t the most recent one:</p>\n\n<ol>\n<li><p><code>git rebase --interactive $parent_of_flawed_commit</code></p>\n\n<p>If you want to fix several flawed commits, pass the parent of the oldest one of them.</p></li>\n<li><p>An editor will come up, with a list of all commits since the one you gave.</p>\n\n<ol>\n<li>Change <code>pick</code> to <code>reword</code> (or on old versions of Git, to <code>edit</code>) in front of any commits you want to fix.</li>\n<li>Once you save, Git will replay the listed commits. <br /> <br /></li>\n</ol></li>\n<li><p>For each commit you want to <em>reword</em>, Git will drop you back into your editor. For each commit you want to <em>edit</em>, Git drops you into the shell. If you’re in the shell:</p>\n\n<ol>\n<li>Change the commit in any way you like.</li>\n<li><code>git commit --amend</code></li>\n<li><code>git rebase --continue</code></li>\n</ol></li>\n</ol>\n\n<p>Most of this sequence will be explained to you by the output of the various commands as you go. It’s very easy; you don’t need to memorise it – just remember that <code>git rebase --interactive</code> lets you correct commits no matter how long ago they were.</p>\n\n<hr>\n\n<p>Note that you will not want to change commits that you have already pushed. Or maybe you do, but in that case you will have to take great care to communicate with everyone who may have pulled your commits and done work on top of them. <em><a href=\"https://stackoverflow.com/questions/4084868/how-do-i-recover-resynchronise-after-someone-pushes-a-rebase-or-a-reset-to-a-pub\">How do I recover/resynchronise after someone pushes a rebase or a reset to a published branch?</a></em></p>\n" }, { "answer_id": 2219560, "author": "lfx_cool", "author_id": 268413, "author_profile": "https://Stackoverflow.com/users/268413", "pm_score": 11, "selected": false, "text": "<pre class=\"lang-sh prettyprint-override\"><code>git commit --amend -m \"your new message\"\n</code></pre>\n" }, { "answer_id": 6258114, "author": "John", "author_id": 768136, "author_profile": "https://Stackoverflow.com/users/768136", "pm_score": 9, "selected": false, "text": "<p>As already mentioned, <code>git commit --amend</code> is the way to overwrite the last commit. One note: if you would like to also <strong>overwrite the files</strong>, the command would be </p>\n\n<pre class=\"lang-c prettyprint-override\"><code>git commit -a --amend -m \"My new commit message\"\n</code></pre>\n" }, { "answer_id": 7070976, "author": "Fatih Acet", "author_id": 480949, "author_profile": "https://Stackoverflow.com/users/480949", "pm_score": 10, "selected": false, "text": "<p>To amend the previous commit, make the changes you want and stage those changes, and then run</p>\n\n\n\n<pre class=\"lang-none prettyprint-override\"><code>git commit --amend\n</code></pre>\n\n<p>This will open a file in your text editor representing your new commit message. It starts out populated with the text from your old commit message. Change the commit message as you want, then save the file and quit your editor to finish.</p>\n\n<p>To amend the previous commit and keep the same log message, run</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>git commit --amend -C HEAD\n</code></pre>\n\n<p>To fix the previous commit by removing it entirely, run</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>git reset --hard HEAD^\n</code></pre>\n\n<p>If you want to edit more than one commit message, run</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>git rebase -i HEAD~<b>commit_count</b></code></pre>\n\n<p>(Replace <b>commit_count</b> with number of commits that you want to edit.) This command launches your editor. Mark the first commit (the one that you want to change) as “edit” instead of “pick”, then save and exit your editor. Make the change you want to commit and then run</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>git commit --amend\ngit rebase --continue\n</code></pre>\n\n<p>Note: You can also \"Make the change you want\" from the editor opened by <code>git commit --amend</code></p>\n" }, { "answer_id": 12231177, "author": "Mark", "author_id": 710388, "author_profile": "https://Stackoverflow.com/users/710388", "pm_score": 9, "selected": false, "text": "<p>You also can use <code>git filter-branch</code> for that.</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>git filter-branch -f --msg-filter \"sed 's/errror/error/'\" $flawed_commit..HEAD\n</code></pre>\n\n<p>It's not as easy as a trivial <code>git commit --amend</code>, but it's especially useful, if you already have some merges after your erroneous commit message.</p>\n\n<p>Note that this will try to rewrite <em>every</em> commit between <code>HEAD</code> and the flawed commit, so you should choose your <code>msg-filter</code> command very wisely ;-)</p>\n" }, { "answer_id": 13010393, "author": "Heena Hussain", "author_id": 1369257, "author_profile": "https://Stackoverflow.com/users/1369257", "pm_score": 8, "selected": false, "text": "<ol>\n<li><p>If you only want to modify your last commit message, then do:</p>\n\n<pre><code>git commit --amend\n</code></pre></li>\n</ol>\n\n<p>That will drop you into your text editor and let you change the last commit message.</p>\n\n<ol start=\"2\">\n<li><p>If you want to change the last three commit messages, or any of the commit messages up to that point, supply <code>HEAD~3</code> to the <code>git rebase -i</code> command:</p>\n\n<pre><code>git rebase -i HEAD~3\n</code></pre></li>\n</ol>\n" }, { "answer_id": 13282142, "author": "Akhilraj N S", "author_id": 1556933, "author_profile": "https://Stackoverflow.com/users/1556933", "pm_score": 8, "selected": false, "text": "<p>If you are using the Git GUI tool, there is a button named <em>Amend last commit</em>. Click on that button and then it will display your last commit files and message. Just edit that message, and you can commit it with a new commit message.</p>\n\n<p>Or use this command from a console/terminal:</p>\n\n<pre><code>git commit -a --amend -m \"My new commit message\"\n</code></pre>\n" }, { "answer_id": 13394598, "author": "sebers", "author_id": 1812509, "author_profile": "https://Stackoverflow.com/users/1812509", "pm_score": 8, "selected": false, "text": "<p>If you have to change an old commit message over multiple branches (i.e., the commit with the erroneous message is present in multiple branches) you might want to use:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>git filter-branch -f --msg-filter \\\n'sed \"s/&lt;old message&gt;/&lt;new message&gt;/g\"' -- --all\n</code></pre>\n\n<p>Git will create a temporary directory for rewriting and additionally backup old references in <code>refs/original/</code>.</p>\n\n<ul>\n<li><p><code>-f</code> will enforce the execution of the operation. This is necessary if the temporary directory is already present or if there are already references stored under <code>refs/original</code>. If that is not the case, you can drop this flag.</p></li>\n<li><p><code>--</code> separates filter-branch options from revision options.</p></li>\n<li><p><code>--all</code> will make sure that all <em>branches</em> and <em>tags</em> are rewritten.</p></li>\n</ul>\n\n<p>Due to the backup of your old references, you can easily go back to the state before executing the command.</p>\n\n<p>Say, you want to recover your master and access it in branch <code>old_master</code>:</p>\n\n<pre><code>git checkout -b old_master refs/original/refs/heads/master\n</code></pre>\n" }, { "answer_id": 13656530, "author": "gulchrider", "author_id": 289447, "author_profile": "https://Stackoverflow.com/users/289447", "pm_score": 8, "selected": false, "text": "<p>If you are using the Git GUI, you can amend the last commit which hasn't been pushed with: </p>\n\n<pre><code>Commit/Amend Last Commit\n</code></pre>\n" }, { "answer_id": 14260056, "author": "krevedko", "author_id": 1785348, "author_profile": "https://Stackoverflow.com/users/1785348", "pm_score": 8, "selected": false, "text": "<p>I prefer this way:</p>\n\n<pre><code>git commit --amend -c &lt;commit ID&gt;\n</code></pre>\n\n<p>Otherwise, there will be a new commit with a new commit ID.</p>\n" }, { "answer_id": 14391252, "author": "wallerjake", "author_id": 1876427, "author_profile": "https://Stackoverflow.com/users/1876427", "pm_score": 8, "selected": false, "text": "<h3>Amend</h3>\n\n<p>You have a couple of options here. You can do</p>\n\n<pre><code>git commit --amend\n</code></pre>\n\n<p>as long as it's your last commit.</p>\n\n<h3>Interactive rebase</h3>\n\n<p>Otherwise, if it's not your last commit, you can do an interactive rebase,</p>\n\n<pre><code>git rebase -i [branched_from] [hash before commit]\n</code></pre>\n\n<p>Then inside the interactive rebase you simply add edit to that commit. When it comes up, do a <code>git commit --amend</code> and modify the commit message. If you want to roll back before that commit point, you could also use <code>git reflog</code> and just delete that commit. Then you just do a <code>git commit</code> again.</p>\n" }, { "answer_id": 14464406, "author": "Shoaib Ud-Din", "author_id": 1613679, "author_profile": "https://Stackoverflow.com/users/1613679", "pm_score": 8, "selected": false, "text": "<p>You can use <a href=\"http://git-scm.com/book/en/Git-Branching-Rebasing\">Git rebasing</a>. For example, if you want to modify back to commit bbc643cd, run</p>\n\n<pre><code>$ git rebase bbc643cd^ --interactive\n</code></pre>\n\n<p>In the default editor, modify 'pick' to 'edit' in the line whose commit you want to modify. Make your changes and then stage them with</p>\n\n<pre><code>$ git add &lt;filepattern&gt;\n</code></pre>\n\n<p>Now you can use</p>\n\n<pre><code>$ git commit --amend\n</code></pre>\n\n<p>to modify the commit, and after that</p>\n\n<pre><code>$ git rebase --continue\n</code></pre>\n\n<p>to return back to the previous head commit.</p>\n" }, { "answer_id": 15669052, "author": "skin", "author_id": 563746, "author_profile": "https://Stackoverflow.com/users/563746", "pm_score": 8, "selected": false, "text": "<p>Use</p>\n\n<pre><code>git commit --amend\n</code></pre>\n\n<p>To understand it in detail, an excellent post is <em><a href=\"https://www.atlassian.com/git/tutorials/rewriting-history#git-commit--amend\" rel=\"noreferrer\">4. Rewriting Git History</a></em>. It also talks about <strong>when not to use</strong> <code>git commit --amend</code>.</p>\n" }, { "answer_id": 18048546, "author": "Havard Graff", "author_id": 1856278, "author_profile": "https://Stackoverflow.com/users/1856278", "pm_score": 7, "selected": false, "text": "<p>I use the <a href=\"http://git-scm.com/docs/git-gui\">Git GUI</a> as much as I can, and that gives you the option to amend the last commit:</p>\n\n<p><img src=\"https://i.stack.imgur.com/qXMzu.png\" alt=\"Tick that box\" title=\"Check that box &quot;Amend Last Commit&quot;!\"></p>\n\n<p>Also, <code>git rebase -i origin/master</code>is a nice mantra that will always present you with the commits you have done on top of master, and give you the option to amend, delete, reorder or squash. No need to get hold of that hash first.</p>\n" }, { "answer_id": 20338254, "author": "Radu Murzea", "author_id": 995822, "author_profile": "https://Stackoverflow.com/users/995822", "pm_score": 7, "selected": false, "text": "<p>Wow, so there are a lot of ways to do this.</p>\n\n<p>Yet another way to do this is to delete the last commit, but keep its changes so that you won't lose your work. You can then do another commit with the corrected message. This would look something like this:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>git reset --soft HEAD~1\ngit commit -m 'New and corrected commit message'\n</code></pre>\n\n<p>I always do this if I forget to add a file or do a change.</p>\n\n<p><strong>Remember</strong> to specify <code>--soft</code> instead of <code>--hard</code>, otherwise you lose that commit entirely.</p>\n" }, { "answer_id": 20945012, "author": "Chu-Siang Lai", "author_id": 686105, "author_profile": "https://Stackoverflow.com/users/686105", "pm_score": 6, "selected": false, "text": "<p>I have added the aliases <code>reci</code> and <code>recm</code> for <code>recommit (amend)</code> it. Now I can do it with <code>git recm</code> or <code>git recm -m</code>:</p>\n\n<pre><code>$ vim ~/.gitconfig\n\n[alias]\n\n ......\n cm = commit\n reci = commit --amend\n recm = commit --amend\n ......\n</code></pre>\n" }, { "answer_id": 20960146, "author": "Shubham Chaudhary", "author_id": 2670370, "author_profile": "https://Stackoverflow.com/users/2670370", "pm_score": 7, "selected": false, "text": "<p>If you just want to edit the latest commit, use:</p>\n\n<pre><code>git commit --amend\n</code></pre>\n\n<p>or</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>git commit --amend -m 'one line message'\n</code></pre>\n\n<p>But if you want to edit several commits in a row, you should use rebasing instead:</p>\n\n<pre><code>git rebase -i &lt;hash of one commit before the wrong commit&gt;\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/jRTRr.png\" alt=\"Git rebase editing\"></p>\n\n<p>In a file, like the one above, write <code>edit/e</code> or one of the other options, and hit save and exit.</p>\n\n<p>Now you'll be at the first wrong commit. Make changes in the files, and they'll be automatically staged for you. Type</p>\n\n<pre><code>git commit --amend\n</code></pre>\n\n<p>Save and exit that and type</p>\n\n<pre><code>git rebase --continue\n</code></pre>\n\n<p>to move to next selection until finished with all your selections.</p>\n\n<p>Note that these things change all your SHA hashes after that particular commit.</p>\n" }, { "answer_id": 21278288, "author": "przbadu", "author_id": 2553311, "author_profile": "https://Stackoverflow.com/users/2553311", "pm_score": 7, "selected": false, "text": "<p>Update your last wrong commit message with the new commit message in one line:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>git commit --amend -m \"your new commit message\"\n</code></pre>\n\n<p>Or, try Git reset like below:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code># You can reset your head to n number of commit\n# NOT a good idea for changing last commit message,\n# but you can get an idea to split commit into multiple commits\ngit reset --soft HEAD^\n\n# It will reset you last commit. Now, you\n# can re-commit it with new commit message.\n</code></pre>\n\n<h3>Using reset to split commits into smaller commits</h3>\n\n<p><code>git reset</code> can help you to break one commit into multiple commits too:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code># Reset your head. I am resetting to last commits:\ngit reset --soft HEAD^\n# (You can reset multiple commit by doing HEAD~2(no. of commits)\n\n# Now, reset your head for splitting it to multiple commits\ngit reset HEAD\n\n# Add and commit your files separately to make multiple commits: e.g\ngit add app/\ngit commit -m \"add all files in app directory\"\n\ngit add config/\ngit commit -m \"add all files in config directory\"\n</code></pre>\n\n<p>Here you have successfully broken your last commit into two commits.</p>\n" }, { "answer_id": 23824606, "author": "David Ongaro", "author_id": 2727750, "author_profile": "https://Stackoverflow.com/users/2727750", "pm_score": 7, "selected": false, "text": "<p>If you only want to change your last message you should use the <code>--only</code> flag or its shortcut <code>-o</code> with <code>commit --amend</code>:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>git commit --amend -o -m \"New commit message\"\n</code></pre>\n\n<p>This ensures that you don't accidentally enhance your commit with staged stuff. Of course it's best to have a proper <code>$EDITOR</code> configuration. Then you can leave the <code>-m</code> option out, and Git will pre-fill the commit message with the old one. In this way it can be easily edited.</p>\n" }, { "answer_id": 24843054, "author": "neoneye", "author_id": 78336, "author_profile": "https://Stackoverflow.com/users/78336", "pm_score": 6, "selected": false, "text": "<p>I realised that I had pushed a commit with a typo in it. In order to undo, I did the following:</p>\n\n<pre class=\"lang-bash prettyprint-override\"><code>git commit --amend -m \"T-1000, advanced prototype\"\ngit push --force\n</code></pre>\n\n<p><strong>Warning:</strong> force pushing your changes will overwrite the remote branch with your local one. Make sure that you aren't going to be overwriting anything that you want to keep. Also be cautious about force pushing an amended (rewritten) commit if anyone else shares the branch with you, because they'll need to rewrite their own history if they have the old copy of the commit that you've just rewritten.</p>\n" }, { "answer_id": 25178676, "author": "Marijn", "author_id": 3510188, "author_profile": "https://Stackoverflow.com/users/3510188", "pm_score": 7, "selected": false, "text": "<p>On this question there are a lot of answers, but none of them explains in super detail how to change older commit messages using <a href=\"http://en.wikipedia.org/wiki/Vim_%28text_editor%29\" rel=\"noreferrer\">Vim</a>. I was stuck trying to do this myself, so here I'll write down in detail how I did this especially for people who have no experience in Vim!</p>\n\n<p>I wanted to change my five latest commits that I already pushed to the server. This is quite 'dangerous' because if someone else already pulled from this, you can mess things up by changing the commit messages. However, when you’re working on your own little branch and are sure no one pulled it you can change it like this:</p>\n\n<p>Let's say you want to change your five latest commits, and then you type this in the terminal:</p>\n\n<pre><code>git rebase -i HEAD~5\n</code></pre>\n\n<p>*Where 5 is the number of commit messages you want to change (so if you want to change the 10th to last commit, you type in 10).</p>\n\n<p>This command will get you into Vim there you can ‘edit’ your commit history. You’ll see your last five commits at the top like this:</p>\n\n<pre><code>pick &lt;commit hash&gt; commit message\n</code></pre>\n\n<p>Instead of <code>pick</code> you need to write <code>reword</code>. You can do this in Vim by typing in <code>i</code>. That makes you go in to <em>insert</em> mode. (You see that you’re in insert mode by the word <em>INSERT</em> at the bottom.) For the commits you want to change, type in <code>reword</code> instead of <code>pick</code>.</p>\n\n<p>Then you need to save and quit this screen. You do that by first going in to ‘command-mode’ by pressing the <kbd>Esc</kbd>button (you can check that you’re in command-mode if the word <em>INSERT</em> at the bottom has disappeared). Then you can type in a command by typing <code>:</code>. The command to save and quit is <code>wq</code>. So if you type in <code>:wq</code> you’re on the right track.</p>\n\n<p>Then Vim will go over every commit message you want to reword, and here you can actually change the commit messages. You’ll do this by going into insert mode, changing the commit message, going into the command-mode, and save and quit. Do this five times and you’re out of Vim!</p>\n\n<p>Then, if you already pushed your wrong commits, you need to <code>git push --force</code> to overwrite them. Remember that <code>git push --force</code> is quite a dangerous thing to do, so make sure that no one pulled from the server since you pushed your wrong commits!</p>\n\n<p>Now you have changed your commit messages!</p>\n\n<p>(As you see, I'm not that experienced in Vim, so if I used the wrong 'lingo' to explain what's happening, feel free to correct me!)</p>\n" }, { "answer_id": 25720830, "author": "Kedar Adhikari", "author_id": 3600772, "author_profile": "https://Stackoverflow.com/users/3600772", "pm_score": 6, "selected": false, "text": "<p>I like to use the following:</p>\n\n<ol>\n<li><code>git status</code></li>\n<li><code>git add --all</code></li>\n<li><code>git commit -am \"message goes here about the change\"</code></li>\n<li><code>git pull &lt;origin master&gt;</code></li>\n<li><code>git push &lt;origin master&gt;</code></li>\n</ol>\n" }, { "answer_id": 26782560, "author": "Steve Chambers", "author_id": 1063716, "author_profile": "https://Stackoverflow.com/users/1063716", "pm_score": 7, "selected": false, "text": "<p>For anyone looking for a Windows/Mac GUI to help with editing older messages (i.e. not just the latest message), I'd recommend <a href=\"http://www.sourcetreeapp.com\" rel=\"noreferrer\">Sourcetree</a>. The steps to follow are below the image.</p>\n<p><img src=\"https://i.stack.imgur.com/CcA2P.png\" alt=\"Sourcetree interactive rebase\" /></p>\n<p><strong>For commits that haven't been pushed to a remote yet:</strong></p>\n<ol>\n<li>Make sure you've committed or stashed all current changes (i.e., so there are no files listed in the &quot;File Status&quot; tab) - it won't work otherwise.</li>\n<li>In the &quot;Log / History&quot; tab, right click on the entry with an adjoining line in the graph <strong>one below</strong> the commit(s) you wish to edit and select &quot;Rebase children of <em>&lt;commit ref&gt;</em> interactively...&quot;</li>\n<li>Select the whole row for a commit message you wish to change <em>(click on the &quot;Message&quot; column)</em>.</li>\n<li>Click the &quot;Edit Message&quot; button.</li>\n<li>Edit the message as desired in the dialog that comes up and then click <kbd>OK</kbd>.</li>\n<li>Repeat steps 3-4 if there are other commit messages to change.</li>\n<li>Click <kbd>OK</kbd>: Rebasing will commence. If all is well, the output will end &quot;Completed successfully&quot;. <em><strong>NOTE:</strong> I've sometimes seen this fail with <code>Unable to create 'project_path/.git/index.lock': File exists.</code> when trying to modify multiple commit messages at the same time. Not sure exactly what the issue is, or whether it will be fixed in a future version of Sourcetree, but if this happens would recommend rebasing them one at a time (slower but seems more reliable).</em></li>\n</ol>\n<p><strong>...Or... for commits that have already been pushed:</strong></p>\n<p>Follow the steps in <a href=\"https://stackoverflow.com/questions/17604232#23239109\">this answer</a>, which are similar to above, but require a further command to be run from the command line (<code>git push origin &lt;branch&gt; -f</code>) to force-push the branch. I'd recommend reading it all and applying the necessary caution!</p>\n" }, { "answer_id": 27916548, "author": "Prabhakar Undurthi", "author_id": 2200417, "author_profile": "https://Stackoverflow.com/users/2200417", "pm_score": 6, "selected": false, "text": "<p>If you have not pushed the code to your remote branch (<a href=\"http://en.wikipedia.org/wiki/GitHub\">GitHub</a>/<a href=\"http://en.wikipedia.org/wiki/Bitbucket\">Bitbucket</a>) you can change the commit message on the command line as below.</p>\n\n<pre><code> git commit --amend -m \"Your new message\"\n</code></pre>\n\n<p>If you're working on a specific branch do this:</p>\n\n<pre><code>git commit --amend -m \"BRANCH-NAME: new message\"\n</code></pre>\n\n<p>If you've already pushed the code with the wrong message, and you need to be careful when changing the message. That is, after you change the commit message and try pushing it again, you end up with having issues. To make it smooth, follow these steps.</p>\n\n<p><strong>Please read my entire answer before doing it.</strong></p>\n\n<pre><code>git commit --amend -m \"BRANCH-NAME : your new message\"\n\ngit push -f origin BRANCH-NAME # Not a best practice. Read below why?\n</code></pre>\n\n<p><strong>Important note:</strong> When you use the force push directly you might end up with code issues that other developers are working on the same branch. So to avoid those conflicts, you need to pull the code from your branch before making the <strong>force push</strong>:</p>\n\n<pre><code> git commit --amend -m \"BRANCH-NAME : your new message\"\n git pull origin BRANCH-NAME\n git push -f origin BRANCH-NAME\n</code></pre>\n\n<p>This is the best practice when changing the commit message, if it was already pushed.</p>\n" }, { "answer_id": 28421811, "author": "Zaz", "author_id": 405550, "author_profile": "https://Stackoverflow.com/users/405550", "pm_score": 8, "selected": false, "text": "<p>If it's your last commit, just <strong>amend</strong> the commit:</p>\n\n<pre><code>git commit --amend -o -m \"New commit message\"\n</code></pre>\n\n<p><em>(Using the <code>-o</code> (<code>--only</code>) flag to make sure you change only the commit message)</em></p>\n\n<p><br/></p>\n\n<p>If it's a buried commit, use the awesome <strong>interactive rebase</strong>:</p>\n\n<pre><code>git rebase -i @~9 # Show the last 9 commits in a text editor\n</code></pre>\n\n<p>Find the commit you want, change <code>pick</code> to <code>r</code> (<code>reword</code>), and save and close the file. Done!</p>\n\n<p><br></p>\n\n<hr>\n\n<p>Miniature Vim tutorial (or, how to rebase with only 8 keystrokes <kbd><code>3j</code></kbd><kbd><code>cw</code></kbd><code>r</code><kbd>Esc</kbd><kbd><code>ZZ</code></kbd>):</p>\n\n<ul>\n<li>Run <code>vimtutor</code> if you have time</li>\n<li><kbd><code>h</code></kbd><kbd><code>j</code></kbd><kbd><code>k</code></kbd><kbd><code>l</code></kbd> correspond to movement keys <kbd>←</kbd><kbd>↓</kbd><kbd>↑</kbd><kbd>→</kbd></li>\n<li>All commands can be prefixed with a \"range\", e.g. <kbd><code>3j</code></kbd> moves down three lines</li>\n<li><kbd><code>i</code></kbd> to enter insert mode — text you type will appear in the file</li>\n<li><kbd>Esc</kbd> or <kbd>Ctrl</kbd><kbd><code>c</code></kbd> to exit insert mode and return to \"normal\" mode</li>\n<li><kbd><code>u</code></kbd> to undo</li>\n<li><kbd>Ctrl</kbd><kbd><code>r</code></kbd> to redo</li>\n<li><kbd><code>dd</code></kbd>, <kbd><code>dw</code></kbd>, <kbd><code>dl</code></kbd> to delete a line, word, or letter, respectively</li>\n<li><kbd><code>cc</code></kbd>, <kbd><code>cw</code></kbd>, <kbd><code>cl</code></kbd> to change a line, word, or letter, respectively (same as <kbd><code>dd</code></kbd><kbd><code>i</code></kbd>)</li>\n<li><kbd><code>yy</code></kbd>, <kbd><code>yw</code></kbd>, <kbd><code>yl</code></kbd> to copy (\"yank\") a line, word, or letter, respectively</li>\n<li><kbd><code>p</code></kbd> or <kbd><code>P</code></kbd> to paste after, or before current position, respectively</li>\n<li><kbd><code>:w</code></kbd><kbd>Enter</kbd> to save (write) a file</li>\n<li><kbd><code>:q!</code></kbd><kbd>Enter</kbd> to quit without saving</li>\n<li><kbd><code>:wq</code></kbd><kbd>Enter</kbd> or <kbd><code>ZZ</code></kbd> to save and quit</li>\n</ul>\n\n<p>If you edit text a lot, then switch to the <a href=\"https://en.wikipedia.org/wiki/Dvorak_keyboard_layout\" rel=\"noreferrer\">Dvorak keyboard layout</a>, learn to touch-type, and learn Vim. <a href=\"https://stackoverflow.com/questions/597077/is-learning-vim-worth-the-effort\">Is it worth the effort?</a> Yes.</p>\n\n<p><br/></p>\n\n<hr>\n\n<p>ProTip™: Don't be afraid to experiment with \"dangerous\" commands that rewrite history* — Git doesn't delete your commits for 90 days by default; you can find them in the reflog:</p>\n\n<pre><code>$ git reset @~3 # Go back three commits\n$ git reflog\nc4f708b HEAD@{0}: reset: moving to @~3\n2c52489 HEAD@{1}: commit: more changes\n4a5246d HEAD@{2}: commit: make important changes\ne8571e4 HEAD@{3}: commit: make some changes\n... earlier commits ...\n$ git reset 2c52489\n... and you're back where you started\n</code></pre>\n\n<p>* <em>Watch out for options like <code>--hard</code> and <code>--force</code> though — they can discard data.</em>\n* <em>Also, don't rewrite history on any branches you're collaborating on.</em></p>\n" }, { "answer_id": 28645738, "author": "albfan", "author_id": 848072, "author_profile": "https://Stackoverflow.com/users/848072", "pm_score": 6, "selected": false, "text": "<p>You can use <a href=\"https://github.com/albfan/git-rebase-reword\">git-rebase-reword</a></p>\n\n<p>It is designed to edit any commit (not just last) same way as <code>commit --amend</code></p>\n\n<pre><code>$ git rebase-reword &lt;commit-or-refname&gt;\n</code></pre>\n\n<p>It is named after the action on rebase interactive to amend a commit: \"reword\". See <a href=\"https://robots.thoughtbot.com/git-interactive-rebase-squash-amend-rewriting-history\">this post</a> and <a href=\"http://git-scm.com/docs/git-rebase\">man</a> -section interactive mode-</p>\n\n<p>Examples:</p>\n\n<pre><code>$ git rebase-reword b68f560\n$ git rebase-reword HEAD^\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7473/" ]
I wrote the wrong thing in a commit message. How can I change the message? The commit has not been pushed yet.
Amending the most recent commit message ======================================= ```sh git commit --amend ``` will open your editor, allowing you to change the commit message of the most recent commit. Additionally, you can set the commit message directly in the command line with: ```sh git commit --amend -m "New commit message" ``` …however, this can make multi-line commit messages or small corrections more cumbersome to enter. Make sure you don't have any working copy changes *staged* before doing this or they will get committed too. (*Unstaged* changes will not get committed.) Changing the message of a commit that you've already pushed to your remote branch --------------------------------------------------------------------------------- If you've already pushed your commit up to your remote branch, then - after amending your commit locally (as described above) - you'll also [need to force push the commit](https://stackoverflow.com/questions/41003071/why-must-i-force-push-after-changing-a-commit-message) with: ```bash git push <remote> <branch> --force # Or git push <remote> <branch> -f ``` **Warning: force-pushing will overwrite the remote branch with the state of your local one**. If there are commits on the remote branch that you don't have in your local branch, you *will* lose those commits. **Warning: be cautious about amending commits that you have already shared with other people.** Amending commits essentially *rewrites* them to have different [SHA](https://en.wikipedia.org/wiki/SHA-1) IDs, which poses a problem if other people have copies of the old commit that you've rewritten. Anyone who has a copy of the old commit will need to synchronize their work with your newly re-written commit, which can sometimes be difficult, so make sure you coordinate with others when attempting to rewrite shared commit history, or just avoid rewriting shared commits altogether. --- ### Perform an interactive rebase Another option is to use interactive rebase. This allows you to edit any message you want to update even if it's not the latest message. In order to do a Git squash, follow these steps: ``` // n is the number of commits up to the last commit you want to be able to edit git rebase -i HEAD~n ``` Once you squash your commits - choose the `e/r` for editing the message: [![Screenshot of terminal while editing commit](https://i.stack.imgur.com/LVcm9.png)](https://i.stack.imgur.com/LVcm9.png) ### Important note about interactive rebase When you use `git rebase -i HEAD~n` there can be **more** than n commits. Git will "collect" all the commits in the last n commits, and if there was a merge somewhere in between that range you will see all the commits as well, so the outcome will be n + . ### Good tip: If you have to do it for more than a single branch and you might face conflicts when amending the content, set up [`git rerere`](https://stackoverflow.com/questions/35415925/is-it-possible-to-setup-git-merge-for-automatic-resolving-git-rerere/35417944#35417944) and let Git resolve those conflicts automatically for you. --- Documentation ------------- * [git-commit(1) Manual Page](https://www.kernel.org/pub/software/scm/git/docs/git-commit.html) * [git-rebase(1) Manual Page](https://www.kernel.org/pub/software/scm/git/docs/git-rebase.html) * [git-push(1) Manual Page](https://www.kernel.org/pub/software/scm/git/docs/git-push.html)
179,128
<p>I'm starting a project which requires reading outlook msg files in c#. I have the specs for compound documents but am having trouble reading them in c#. Any pointers would be greatly appreciated.</p> <p>Thanks.</p>
[ { "answer_id": 179205, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook.aspx\" rel=\"nofollow noreferrer\">Outlook Interop</a>. While I have never used the outlook interop, you <strong>SHOULD</strong> be able to open the email messages with it.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/microsoft.office.interop.outlook._mailitem.aspx\" rel=\"nofollow noreferrer\">MailItem Interface</a> should be the interface that you need to access it.</p>\n\n<p>Also, make sure that you release the <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.releasecomobject(VS.80).aspx\" rel=\"nofollow noreferrer\">com references</a> after you are done with them</p>\n" }, { "answer_id": 179323, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 5, "selected": true, "text": "<p>Here is my shot. This is an initial translation of this <a href=\"http://www.codeguru.com/cpp/cpp/cpp_mfc/files/article.php/c13487__1/\" rel=\"noreferrer\">article</a>.</p>\n\n<pre><code>namespace cs_console_app\n{\n using System;\n using System.Runtime.InteropServices;\n using System.Runtime.InteropServices.ComTypes;\n\n [ComImport]\n [Guid(\"0000000d-0000-0000-C000-000000000046\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n public interface IEnumSTATSTG\n {\n // The user needs to allocate an STATSTG array whose size is celt.\n [PreserveSig]\n uint Next(\n uint celt,\n [MarshalAs(UnmanagedType.LPArray), Out]\n System.Runtime.InteropServices.ComTypes.STATSTG[] rgelt,\n out uint pceltFetched\n );\n\n void Skip(uint celt);\n\n void Reset();\n\n [return: MarshalAs(UnmanagedType.Interface)]\n IEnumSTATSTG Clone();\n }\n\n [ComImport]\n [Guid(\"0000000b-0000-0000-C000-000000000046\")]\n [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]\n interface IStorage\n {\n void CreateStream(\n /* [string][in] */ string pwcsName,\n /* [in] */ uint grfMode,\n /* [in] */ uint reserved1,\n /* [in] */ uint reserved2,\n /* [out] */ out IStream ppstm);\n\n void OpenStream(\n /* [string][in] */ string pwcsName,\n /* [unique][in] */ IntPtr reserved1,\n /* [in] */ uint grfMode,\n /* [in] */ uint reserved2,\n /* [out] */ out IStream ppstm);\n\n void CreateStorage(\n /* [string][in] */ string pwcsName,\n /* [in] */ uint grfMode,\n /* [in] */ uint reserved1,\n /* [in] */ uint reserved2,\n /* [out] */ out IStorage ppstg);\n\n void OpenStorage(\n /* [string][unique][in] */ string pwcsName,\n /* [unique][in] */ IStorage pstgPriority,\n /* [in] */ uint grfMode,\n /* [unique][in] */ IntPtr snbExclude,\n /* [in] */ uint reserved,\n /* [out] */ out IStorage ppstg);\n\n void CopyTo(\n /* [in] */ uint ciidExclude,\n /* [size_is][unique][in] */ Guid rgiidExclude, // should this be an array?\n /* [unique][in] */ IntPtr snbExclude,\n /* [unique][in] */ IStorage pstgDest);\n\n void MoveElementTo(\n /* [string][in] */ string pwcsName,\n /* [unique][in] */ IStorage pstgDest,\n /* [string][in] */ string pwcsNewName,\n /* [in] */ uint grfFlags);\n\n void Commit(\n /* [in] */ uint grfCommitFlags);\n\n void Revert();\n\n void EnumElements(\n /* [in] */ uint reserved1,\n /* [size_is][unique][in] */ IntPtr reserved2,\n /* [in] */ uint reserved3,\n /* [out] */ out IEnumSTATSTG ppenum);\n\n void DestroyElement(\n /* [string][in] */ string pwcsName);\n\n void RenameElement(\n /* [string][in] */ string pwcsOldName,\n /* [string][in] */ string pwcsNewName);\n\n void SetElementTimes(\n /* [string][unique][in] */ string pwcsName,\n /* [unique][in] */ System.Runtime.InteropServices.ComTypes.FILETIME pctime,\n /* [unique][in] */ System.Runtime.InteropServices.ComTypes.FILETIME patime,\n /* [unique][in] */ System.Runtime.InteropServices.ComTypes.FILETIME pmtime);\n\n void SetClass(\n /* [in] */ Guid clsid);\n\n void SetStateBits(\n /* [in] */ uint grfStateBits,\n /* [in] */ uint grfMask);\n\n void Stat(\n /* [out] */ out System.Runtime.InteropServices.ComTypes.STATSTG pstatstg,\n /* [in] */ uint grfStatFlag);\n\n }\n\n [Flags]\n public enum STGM : int\n {\n DIRECT = 0x00000000,\n TRANSACTED = 0x00010000,\n SIMPLE = 0x08000000,\n READ = 0x00000000,\n WRITE = 0x00000001,\n READWRITE = 0x00000002,\n SHARE_DENY_NONE = 0x00000040,\n SHARE_DENY_READ = 0x00000030,\n SHARE_DENY_WRITE = 0x00000020,\n SHARE_EXCLUSIVE = 0x00000010,\n PRIORITY = 0x00040000,\n DELETEONRELEASE = 0x04000000,\n NOSCRATCH = 0x00100000,\n CREATE = 0x00001000,\n CONVERT = 0x00020000,\n FAILIFTHERE = 0x00000000,\n NOSNAPSHOT = 0x00200000,\n DIRECT_SWMR = 0x00400000,\n }\n\n public enum STATFLAG : uint\n {\n STATFLAG_DEFAULT = 0,\n STATFLAG_NONAME = 1,\n STATFLAG_NOOPEN = 2\n }\n\n public enum STGTY : int\n {\n STGTY_STORAGE = 1,\n STGTY_STREAM = 2,\n STGTY_LOCKBYTES = 3,\n STGTY_PROPERTY = 4\n }\n\n class Program\n {\n [DllImport(\"ole32.dll\")]\n private static extern int StgIsStorageFile(\n [MarshalAs(UnmanagedType.LPWStr)] string pwcsName);\n\n [DllImport(\"ole32.dll\")]\n static extern int StgOpenStorage(\n [MarshalAs(UnmanagedType.LPWStr)] string pwcsName,\n IStorage pstgPriority,\n STGM grfMode,\n IntPtr snbExclude,\n uint reserved,\n out IStorage ppstgOpen);\n\n static void Main(string[] args)\n {\n string filename = @\"f:\\temp\\treta2.msg\";\n if (StgIsStorageFile(filename) == 0)\n {\n IStorage storage = null;\n if (StgOpenStorage(\n filename,\n null,\n STGM.DIRECT | STGM.READ | STGM.SHARE_EXCLUSIVE,\n IntPtr.Zero,\n 0,\n out storage) == 0)\n {\n System.Runtime.InteropServices.ComTypes.STATSTG statstg;\n storage.Stat(out statstg, (uint) STATFLAG.STATFLAG_DEFAULT);\n\n IEnumSTATSTG pIEnumStatStg = null;\n storage.EnumElements(0, IntPtr.Zero, 0, out pIEnumStatStg);\n\n System.Runtime.InteropServices.ComTypes.STATSTG[] regelt = { statstg };\n uint fetched = 0;\n uint res = pIEnumStatStg.Next(1, regelt, out fetched);\n\n if (res == 0)\n {\n while (res != 1)\n {\n string strNode = statstg.pwcsName;\n bool bNodeFound = false;\n\n Console.WriteLine(strNode);\n\n if (strNode == \"__substg1.0_0E04001E\"\n || strNode == \"__substg1.0_0E1D001E\"\n || strNode == \"__substg1.0_1000001E\"\n || strNode == \"__substg1.0_1013001E\")\n {\n bNodeFound = true;\n }\n\n if (bNodeFound)\n {\n switch (statstg.type)\n {\n case (int) STGTY.STGTY_STORAGE:\n {\n IStorage pIChildStorage;\n storage.OpenStorage(statstg.pwcsName,\n null,\n (uint) (STGM.READ | STGM.SHARE_EXCLUSIVE),\n IntPtr.Zero,\n 0,\n out pIChildStorage);\n }\n break;\n case (int) STGTY.STGTY_STREAM:\n {\n IStream pIStream;\n storage.OpenStream(statstg.pwcsName,\n IntPtr.Zero,\n (uint)(STGM.READ | STGM.SHARE_EXCLUSIVE),\n 0,\n out pIStream);\n\n byte[] data = new byte[255];\n\n pIStream.Read(data, 255, IntPtr.Zero);\n }\n break;\n }\n }\n\n if ((res = pIEnumStatStg.Next(1, regelt, out fetched)) != 1)\n {\n statstg = regelt[0];\n }\n }\n }\n }\n }\n\n Console.ReadLine();\n }\n }\n}\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16834/" ]
I'm starting a project which requires reading outlook msg files in c#. I have the specs for compound documents but am having trouble reading them in c#. Any pointers would be greatly appreciated. Thanks.
Here is my shot. This is an initial translation of this [article](http://www.codeguru.com/cpp/cpp/cpp_mfc/files/article.php/c13487__1/). ``` namespace cs_console_app { using System; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; [ComImport] [Guid("0000000d-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IEnumSTATSTG { // The user needs to allocate an STATSTG array whose size is celt. [PreserveSig] uint Next( uint celt, [MarshalAs(UnmanagedType.LPArray), Out] System.Runtime.InteropServices.ComTypes.STATSTG[] rgelt, out uint pceltFetched ); void Skip(uint celt); void Reset(); [return: MarshalAs(UnmanagedType.Interface)] IEnumSTATSTG Clone(); } [ComImport] [Guid("0000000b-0000-0000-C000-000000000046")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] interface IStorage { void CreateStream( /* [string][in] */ string pwcsName, /* [in] */ uint grfMode, /* [in] */ uint reserved1, /* [in] */ uint reserved2, /* [out] */ out IStream ppstm); void OpenStream( /* [string][in] */ string pwcsName, /* [unique][in] */ IntPtr reserved1, /* [in] */ uint grfMode, /* [in] */ uint reserved2, /* [out] */ out IStream ppstm); void CreateStorage( /* [string][in] */ string pwcsName, /* [in] */ uint grfMode, /* [in] */ uint reserved1, /* [in] */ uint reserved2, /* [out] */ out IStorage ppstg); void OpenStorage( /* [string][unique][in] */ string pwcsName, /* [unique][in] */ IStorage pstgPriority, /* [in] */ uint grfMode, /* [unique][in] */ IntPtr snbExclude, /* [in] */ uint reserved, /* [out] */ out IStorage ppstg); void CopyTo( /* [in] */ uint ciidExclude, /* [size_is][unique][in] */ Guid rgiidExclude, // should this be an array? /* [unique][in] */ IntPtr snbExclude, /* [unique][in] */ IStorage pstgDest); void MoveElementTo( /* [string][in] */ string pwcsName, /* [unique][in] */ IStorage pstgDest, /* [string][in] */ string pwcsNewName, /* [in] */ uint grfFlags); void Commit( /* [in] */ uint grfCommitFlags); void Revert(); void EnumElements( /* [in] */ uint reserved1, /* [size_is][unique][in] */ IntPtr reserved2, /* [in] */ uint reserved3, /* [out] */ out IEnumSTATSTG ppenum); void DestroyElement( /* [string][in] */ string pwcsName); void RenameElement( /* [string][in] */ string pwcsOldName, /* [string][in] */ string pwcsNewName); void SetElementTimes( /* [string][unique][in] */ string pwcsName, /* [unique][in] */ System.Runtime.InteropServices.ComTypes.FILETIME pctime, /* [unique][in] */ System.Runtime.InteropServices.ComTypes.FILETIME patime, /* [unique][in] */ System.Runtime.InteropServices.ComTypes.FILETIME pmtime); void SetClass( /* [in] */ Guid clsid); void SetStateBits( /* [in] */ uint grfStateBits, /* [in] */ uint grfMask); void Stat( /* [out] */ out System.Runtime.InteropServices.ComTypes.STATSTG pstatstg, /* [in] */ uint grfStatFlag); } [Flags] public enum STGM : int { DIRECT = 0x00000000, TRANSACTED = 0x00010000, SIMPLE = 0x08000000, READ = 0x00000000, WRITE = 0x00000001, READWRITE = 0x00000002, SHARE_DENY_NONE = 0x00000040, SHARE_DENY_READ = 0x00000030, SHARE_DENY_WRITE = 0x00000020, SHARE_EXCLUSIVE = 0x00000010, PRIORITY = 0x00040000, DELETEONRELEASE = 0x04000000, NOSCRATCH = 0x00100000, CREATE = 0x00001000, CONVERT = 0x00020000, FAILIFTHERE = 0x00000000, NOSNAPSHOT = 0x00200000, DIRECT_SWMR = 0x00400000, } public enum STATFLAG : uint { STATFLAG_DEFAULT = 0, STATFLAG_NONAME = 1, STATFLAG_NOOPEN = 2 } public enum STGTY : int { STGTY_STORAGE = 1, STGTY_STREAM = 2, STGTY_LOCKBYTES = 3, STGTY_PROPERTY = 4 } class Program { [DllImport("ole32.dll")] private static extern int StgIsStorageFile( [MarshalAs(UnmanagedType.LPWStr)] string pwcsName); [DllImport("ole32.dll")] static extern int StgOpenStorage( [MarshalAs(UnmanagedType.LPWStr)] string pwcsName, IStorage pstgPriority, STGM grfMode, IntPtr snbExclude, uint reserved, out IStorage ppstgOpen); static void Main(string[] args) { string filename = @"f:\temp\treta2.msg"; if (StgIsStorageFile(filename) == 0) { IStorage storage = null; if (StgOpenStorage( filename, null, STGM.DIRECT | STGM.READ | STGM.SHARE_EXCLUSIVE, IntPtr.Zero, 0, out storage) == 0) { System.Runtime.InteropServices.ComTypes.STATSTG statstg; storage.Stat(out statstg, (uint) STATFLAG.STATFLAG_DEFAULT); IEnumSTATSTG pIEnumStatStg = null; storage.EnumElements(0, IntPtr.Zero, 0, out pIEnumStatStg); System.Runtime.InteropServices.ComTypes.STATSTG[] regelt = { statstg }; uint fetched = 0; uint res = pIEnumStatStg.Next(1, regelt, out fetched); if (res == 0) { while (res != 1) { string strNode = statstg.pwcsName; bool bNodeFound = false; Console.WriteLine(strNode); if (strNode == "__substg1.0_0E04001E" || strNode == "__substg1.0_0E1D001E" || strNode == "__substg1.0_1000001E" || strNode == "__substg1.0_1013001E") { bNodeFound = true; } if (bNodeFound) { switch (statstg.type) { case (int) STGTY.STGTY_STORAGE: { IStorage pIChildStorage; storage.OpenStorage(statstg.pwcsName, null, (uint) (STGM.READ | STGM.SHARE_EXCLUSIVE), IntPtr.Zero, 0, out pIChildStorage); } break; case (int) STGTY.STGTY_STREAM: { IStream pIStream; storage.OpenStream(statstg.pwcsName, IntPtr.Zero, (uint)(STGM.READ | STGM.SHARE_EXCLUSIVE), 0, out pIStream); byte[] data = new byte[255]; pIStream.Read(data, 255, IntPtr.Zero); } break; } } if ((res = pIEnumStatStg.Next(1, regelt, out fetched)) != 1) { statstg = regelt[0]; } } } } } Console.ReadLine(); } } } ```
179,173
<p>I have an XmlDocument that already exists and is read from a file. </p> <p>I would like to add a chunk of Xml to a node in the document. Is there a good way to create and add all the nodes without cluttering my code with many .CreateNote and .AppendChild calls?</p> <p>I would like some way of making a string or stringBuilder of a valid Xml section and just appending that to an XmlNode.</p> <p>ex: Original XmlDoc:</p> <pre><code>&lt;MyXml&gt; &lt;Employee&gt; &lt;/Employee&gt; &lt;/MyXml&gt; </code></pre> <p>and, I would like to add a Demographic (with several children) tag to Employee:</p> <pre><code>&lt;MyXml&gt; &lt;Employee&gt; &lt;Demographic&gt; &lt;Age/&gt; &lt;DOB/&gt; &lt;/Demographic&gt; &lt;/Employee&gt; &lt;/MyXml&gt; </code></pre>
[ { "answer_id": 179191, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 8, "selected": true, "text": "<p>I suggest using <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.createdocumentfragment.aspx\" rel=\"noreferrer\">XmlDocument.CreateDocumentFragment</a> if you have the data in free form strings. You'll still have to use AppendChild to add the fragment to a node, but you have the freedom of building the XML in your StringBuilder.</p>\n\n<pre><code>XmlDocument xdoc = new XmlDocument();\nxdoc.LoadXml(@\"&lt;MyXml&gt;&lt;Employee&gt;&lt;/Employee&gt;&lt;/MyXml&gt;\");\n\nXmlDocumentFragment xfrag = xdoc.CreateDocumentFragment();\nxfrag.InnerXml = @\"&lt;Demographic&gt;&lt;Age/&gt;&lt;DOB/&gt;&lt;/Demographic&gt;\";\n\nxdoc.DocumentElement.FirstChild.AppendChild(xfrag);\n</code></pre>\n" }, { "answer_id": 179198, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 4, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>employeeNode.InnerXml = \"&lt;Demographic&gt;&lt;Age/&gt;&lt;DOB/&gt;&lt;/Demographic&gt;\";\n</code></pre>\n\n<p>Alternatively (if you have another XML document that you want to use):</p>\n\n<pre><code>employeeNode.AppendChild(employeeNode.OwnerDocument.ImportNode(otherXmlDocument.DocumentElement, true));\n</code></pre>\n" }, { "answer_id": 179204, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 2, "selected": false, "text": "<p>Consider using an XmlWriter for building your fragments on a StringBuilder as this will provide validation and character substitution for you.</p>\n" }, { "answer_id": 179309, "author": "Echostorm", "author_id": 12862, "author_profile": "https://Stackoverflow.com/users/12862", "pm_score": 3, "selected": false, "text": "<p>As an alternative, this is how you could do it in a more LINQy 3.5 manner:</p>\n\n<pre><code> XDocument doc = XDocument.Load(@\"c:\\temp\\test.xml\");\n XElement demoNode = new XElement(\"Demographic\");\n demoNode.Add(new XElement(\"Age\"));\n demoNode.Add(new XElement(\"DOB\"));\n doc.Descendants(\"Employee\").Single().Add(demoNode);\n doc.Save(@\"c:\\temp\\test2.xml\");\n</code></pre>\n" }, { "answer_id": 514370, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>All that I do is creating a new dataset object and open the xml file using ReadXML <code>myDataset.ReadXML(path and file name)</code>. </p>\n\n<p>Then add or remove the rows that I need and save the document again using <code>myDataset.WriteXML(path and file name)</code>.</p>\n\n<p>Bye.</p>\n" }, { "answer_id": 39797079, "author": "Peter Gruppelaar", "author_id": 3790025, "author_profile": "https://Stackoverflow.com/users/3790025", "pm_score": 0, "selected": false, "text": "<p>None of this was working for me so i played around abit and here is my solution.</p>\n\n<p>First load up a text field(you can put it to visible = false in public version)\nload the data in to the text field like so.</p>\n\n<pre><code>string Path = Directory.GetCurrentDirectory() + \"/2016\";\n string pathFile = Path + \"/klanten.xml\";\n StreamReader sr = new StreamReader(pathFile);\n txt.Text = sr.ReadToEnd();\n sr.Close();\n</code></pre>\n\n<p>on the save button load up the text field en save it.\nDont forget u will have to refresh the text field after that, if u want to add multiple addresses/names, i have not included that part.</p>\n\n<pre><code>string name = Globals.s_Name;\n string klanten = txt.Text;\n string s = klanten;\n XmlDocument xdoc = new XmlDocument();\n\n string klant = \"&lt;voornaam&gt;\" + naamBox1.Text + \"&lt;/voornaam&gt;\";\n xdoc.LoadXml(s);\n XmlDocumentFragment xfrag = xdoc.CreateDocumentFragment();\n xfrag.InnerXml = klant;\n xdoc.DocumentElement.FirstChild.AppendChild(xfrag);\n xdoc.Save(name + \"/klanten.xml\");\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2871/" ]
I have an XmlDocument that already exists and is read from a file. I would like to add a chunk of Xml to a node in the document. Is there a good way to create and add all the nodes without cluttering my code with many .CreateNote and .AppendChild calls? I would like some way of making a string or stringBuilder of a valid Xml section and just appending that to an XmlNode. ex: Original XmlDoc: ``` <MyXml> <Employee> </Employee> </MyXml> ``` and, I would like to add a Demographic (with several children) tag to Employee: ``` <MyXml> <Employee> <Demographic> <Age/> <DOB/> </Demographic> </Employee> </MyXml> ```
I suggest using [XmlDocument.CreateDocumentFragment](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.createdocumentfragment.aspx) if you have the data in free form strings. You'll still have to use AppendChild to add the fragment to a node, but you have the freedom of building the XML in your StringBuilder. ``` XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(@"<MyXml><Employee></Employee></MyXml>"); XmlDocumentFragment xfrag = xdoc.CreateDocumentFragment(); xfrag.InnerXml = @"<Demographic><Age/><DOB/></Demographic>"; xdoc.DocumentElement.FirstChild.AppendChild(xfrag); ```
179,186
<p>The problem is that the compiler says that there is a redefinition of a function between a library that belongs to MySQL and math.h from the std library.</p> <p>I have been over this for two days and I still can't figure it out. </p> <p>Has this ever happened to anyone?</p> <p>This is the output from the compiler</p> <hr> <pre> C:\mingw\bin\mingw32-make.exe all 'Building file: ../src/interfaz/ventanaconf.cpp' 'Invoking: GCC C++ Compiler' C:\mingw\bin\mingw32-g++.exe -mms-bitfields -I"c:\dev-cpp\gtkmm\include\gtkmm-2.4" -I"c:\dev-cpp\gtkmm\lib\gtkmm-2.4\include" -I"c:\dev-cpp\gtkmm\include\glibmm-2.4" -I"c:\dev-cpp\gtkmm\lib\glibmm-2.4\include" -I"c:\dev-cpp\gtkmm\include\gdkmm-2.4" -I"c:\dev-cpp\gtkmm\lib\gdkmm-2.4\include" -I"c:\dev-cpp\gtkmm\include\pangomm-1.4" -I"c:\dev-cpp\gtkmm\include\atkmm-1.6" -I"c:\dev-cpp\gtkmm\include\sigc++-2.0" -I"c:\dev-cpp\gtkmm\lib\sigc++-2.0\include" -I"c:\dev-cpp\gtkmm\include\cairomm-1.0" -I"c:\gtk\include\gtk-2.0" -I"c:\gtk\include\glib-2.0" -I"c:\gtk\lib\glib-2.0\include" -I"c:\gtk\lib\gtk-2.0\include" -I"c:\gtk\include\pango-1.0" -I"c:\gtk\include\cairo" -I"c:\gtk\include\freetype2" -I"c:\gtk\include" -I"c:\gtk\include\atk-1.0" -I"c:\Archivos de programa\MySQL\MySQL Server 5.0\include" -O0 -g3 -w -c -fmessage-length=0 -MMD -MP -MF"src/interfaz/ventanaconf.d" -MT"src/interfaz/ventanaconf.d" -o"src/interfaz/ventanaconf.o" "../src/interfaz/ventanaconf.cpp" In file included from c:/Archivos de programa/MySQL/MySQL Server 5.0/include/my_global.h:73, from ../src/interfaz/../gestiondb/gestordb.h:6, from ../src/interfaz/../gestiondb/operacionesdb.h:5, from ../src/interfaz/ventanamodulos.h:20, from ../src/interfaz/ventanaconf.h:27, from ../src/interfaz/ventanaconf.cpp:1: c:/Archivos de programa/MySQL/MySQL Server 5.0/include/config-win.h: **In function `double rint(double)': c:/Archivos de programa/MySQL/MySQL Server 5.0/include/config-win.h:228: error: redefinition of `double rint(double)' C:/mingw/bin/../lib/gcc/mingw32/3.4.2/../../../../include/math.h:620: **error: `double rint(double)' previously defined here** C:\mingw\bin\mingw32-make.exe: *** [src/interfaz/ventanaconf.o] Error 1** </pre> <hr> <p>Thanks in advance!!!</p>
[ { "answer_id": 179215, "author": "TToni", "author_id": 20703, "author_profile": "https://Stackoverflow.com/users/20703", "pm_score": 0, "selected": false, "text": "<p>In line 228 of c:/Archivos de programa/MySQL/MySQL Server 5.0/include/config-win.h you should find a declaration/definition of function named \"rint\". In line 620 of C:/mingw/bin/../lib/gcc/mingw32/3.4.2/../../../../include/math.h you should find another definition of a function with the same name (which probably even does the same).</p>\n\n<p>To solve the problem you will have to delete/outcomment/undefine one of these definitions.</p>\n\n<p>Be prepared to get a similar problem when linking, if you also link two libraries with the same function.</p>\n" }, { "answer_id": 179247, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://bugs.mysql.com/bug.php?id=15936\" rel=\"nofollow noreferrer\">This thread</a> in the mysql support area seems to indicate that they've taken the definition of rint() out of their config_win.h file as of April this year (even though the patch was proposed in 2006). Are you using a version of the MySQL source newer than that?</p>\n" }, { "answer_id": 531847, "author": "Pablo Herrero", "author_id": 366094, "author_profile": "https://Stackoverflow.com/users/366094", "pm_score": 2, "selected": true, "text": "<p>The problem was about an included library, which linux simply ignores, but windows want out. There is no problem letting it out in linux neither...</p>\n\n<p>Somedays i feel SOOOOOOOOOOOOOOOOOOOOOOO STUPID:..</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/366094/" ]
The problem is that the compiler says that there is a redefinition of a function between a library that belongs to MySQL and math.h from the std library. I have been over this for two days and I still can't figure it out. Has this ever happened to anyone? This is the output from the compiler --- ``` C:\mingw\bin\mingw32-make.exe all 'Building file: ../src/interfaz/ventanaconf.cpp' 'Invoking: GCC C++ Compiler' C:\mingw\bin\mingw32-g++.exe -mms-bitfields -I"c:\dev-cpp\gtkmm\include\gtkmm-2.4" -I"c:\dev-cpp\gtkmm\lib\gtkmm-2.4\include" -I"c:\dev-cpp\gtkmm\include\glibmm-2.4" -I"c:\dev-cpp\gtkmm\lib\glibmm-2.4\include" -I"c:\dev-cpp\gtkmm\include\gdkmm-2.4" -I"c:\dev-cpp\gtkmm\lib\gdkmm-2.4\include" -I"c:\dev-cpp\gtkmm\include\pangomm-1.4" -I"c:\dev-cpp\gtkmm\include\atkmm-1.6" -I"c:\dev-cpp\gtkmm\include\sigc++-2.0" -I"c:\dev-cpp\gtkmm\lib\sigc++-2.0\include" -I"c:\dev-cpp\gtkmm\include\cairomm-1.0" -I"c:\gtk\include\gtk-2.0" -I"c:\gtk\include\glib-2.0" -I"c:\gtk\lib\glib-2.0\include" -I"c:\gtk\lib\gtk-2.0\include" -I"c:\gtk\include\pango-1.0" -I"c:\gtk\include\cairo" -I"c:\gtk\include\freetype2" -I"c:\gtk\include" -I"c:\gtk\include\atk-1.0" -I"c:\Archivos de programa\MySQL\MySQL Server 5.0\include" -O0 -g3 -w -c -fmessage-length=0 -MMD -MP -MF"src/interfaz/ventanaconf.d" -MT"src/interfaz/ventanaconf.d" -o"src/interfaz/ventanaconf.o" "../src/interfaz/ventanaconf.cpp" In file included from c:/Archivos de programa/MySQL/MySQL Server 5.0/include/my_global.h:73, from ../src/interfaz/../gestiondb/gestordb.h:6, from ../src/interfaz/../gestiondb/operacionesdb.h:5, from ../src/interfaz/ventanamodulos.h:20, from ../src/interfaz/ventanaconf.h:27, from ../src/interfaz/ventanaconf.cpp:1: c:/Archivos de programa/MySQL/MySQL Server 5.0/include/config-win.h: **In function `double rint(double)': c:/Archivos de programa/MySQL/MySQL Server 5.0/include/config-win.h:228: error: redefinition of `double rint(double)' C:/mingw/bin/../lib/gcc/mingw32/3.4.2/../../../../include/math.h:620: **error: `double rint(double)' previously defined here** C:\mingw\bin\mingw32-make.exe: *** [src/interfaz/ventanaconf.o] Error 1** ``` --- Thanks in advance!!!
The problem was about an included library, which linux simply ignores, but windows want out. There is no problem letting it out in linux neither... Somedays i feel SOOOOOOOOOOOOOOOOOOOOOOO STUPID:..
179,213
<p>This is a multiple question for the same pre-processing instruction.</p> <h2>1 - &lt;&gt; or &quot;&quot; ?</h2> <p>Apart from the info found in the MSDN:</p> <p><a href="https://msdn.microsoft.com/en-us/library/36k2cdd4.aspx" rel="noreferrer" title="#include Directive (C-C++)">#include Directive (C-C++)</a></p> <p>1.a: What are the differences between the two notations?<br> 1.b: Do all compilers implement them the same way?<br> 1.c: When would you use the &lt;&gt;, and when would you use the &quot;&quot; (i.e. what are the criteria you would use to use one or the other for a header include)?<br></p> <h2>2 - #include {TheProject/TheHeader.hpp} or {TheHeader.hpp} ?</h2> <p>I've seen at least two ways of writing includes of one's project headers. Considering that you have at least 4 types of headers, that is:</p> <ul> <li>private headers of your project?</li> <li>headers of your project, but which are exporting symbols (and thus, &quot;public&quot;)</li> <li>headers of another project your module links with</li> <li>headers of a compiler or standard library</li> </ul> <p>For each kind of headers:</p> <p>2.a: Would you use &lt;&gt; or &quot;&quot; ?<br> 2.b: Would you include with {TheProject/TheHeader.hpp}, or with {TheHeader.hpp} only?<br></p> <h2>3 - Bonus</h2> <p>3.a: Do you work on project with sources and/or headers within a tree-like organisation (i.e., directories inside directories, as opposed to &quot;every file in one directory&quot;) and what are the pros/cons?</p>
[ { "answer_id": 179244, "author": "J.J.", "author_id": 21204, "author_profile": "https://Stackoverflow.com/users/21204", "pm_score": 1, "selected": false, "text": "<p>If I remember right.</p>\n\n<p>You use the diamond for all libraries that can be found in your \"path\". So any library that is in the STL, or ones that you have installed. In Linux your path is usually \"/usr/include\", in windows I am not sure, but I would guess it is under \"C:\\windows\".</p>\n\n<p>You use the \"\" then to specify everything else. \"my_bla.cpp\" with no starting directory information will resolve to the directory your code is residing/compiling in. or you can also specify the exact location of your include with it. Like this \"c:\\myproj\\some_code.cpp\"</p>\n\n<p>The type of header doesn't matter, just the location.</p>\n" }, { "answer_id": 179248, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 3, "selected": false, "text": "<p>I typically use &lt;> for system headers and \"\" for project headers. As for paths, that is only neccessary if the file you want is in a sub-directory of an include path.</p>\n\n<p>for example, if you need a file in /usr/include/SDL/, but only /usr/include/ is in your include path, then you could just use:</p>\n\n<pre><code>#include &lt;SDL/whatever.h&gt;\n</code></pre>\n\n<p>Also, keep in mind that unless the path you put starts with a /, it is relative to the current working directory.</p>\n\n<p>EDIT TO ANSWER COMMENT: It depends, if there is only a few includes for a library, I'd just include it's subdirectory in the include path, but if the library has many headers (like dozens) then I'd prefer to just have it in a subdir that I specify. A good example of this is Linux's system headers. You use them like:</p>\n\n<pre><code>#include &lt;sys/io.h&gt;\n#include &lt;linux/limits.h&gt;\n</code></pre>\n\n<p>etc.</p>\n\n<p>EDIT TO INCLUDE ANOTHER GOOD ANSWER: also, if it is conceivable that two or more libraries provide headers by the same name, then the sub-directory solution basically gives each header a namespace.</p>\n" }, { "answer_id": 179249, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>I use &lt;...> from system header file (stdio, iostreams, string etc), and \"...\" for headers specific to that project. </p>\n" }, { "answer_id": 179261, "author": "coppro", "author_id": 16855, "author_profile": "https://Stackoverflow.com/users/16855", "pm_score": 1, "selected": false, "text": "<p>There are two primary differences between <code>&lt;&gt;</code> and <code>\"\"</code>. The first is which character will end the name - there are no escape sequences in header names, and so you may be forced to do <code>#include &lt;bla\"file.cpp&gt;</code> or <code>\"bla&gt;file.cpp\"</code>. That probably won't come up often, though. The other difference is that system includes aren't supposed to occur on <code>\"\"</code>, just <code>&lt;&gt;</code>. So <code>#include \"iostream\"</code> is not guaranteed to work; <code>#include &lt;iostream&gt;</code> is. My personal preference is to use <code>\"\"</code> for files that are part of the project, and <code>&lt;&gt;</code> for files that aren't. Some people only use <code>&lt;&gt;</code> for standard library headers and <code>\"\"</code> for all else. Some people even use <code>&lt;&gt;</code> only for Boost and std; it depends on the project. Like all style aspects, the most important thing is to be consistent.</p>\n\n<p>As for the path, an external library will specify the convention for headers; e.g. <code>&lt;boost/preprocessor.hpp&gt;</code> <code>&lt;wx/window.h&gt;</code> <code>&lt;Magic++.h&gt;</code>. In a local project, I would write all paths relative to the top-level srcdir (or in a library project where they are different, the include directory).</p>\n\n<p>When writing a library, you may also find it helpful to use &lt;> to differentiate between private and public headers, or to not <code>-I</code> the source directory, but the directory above, so you <code>#include \"public_header.hpp\"</code> and <code>\"src/private_header.hpp\"</code>. It's really up to you.</p>\n\n<p>EDIT: As for projects with directory structures, I would highly recommend them. Imagine if all of boost were in one directory (and no subnamespaces)! Directory structure is good because it lets you find files easier, and it allows you more flexibility in naming (<code>\"module\\_text\\_processor.hpp\"</code> as opposed to <code>\"module/text\\_processor.hpp\"</code>). The latter is more natural and easier to use.</p>\n" }, { "answer_id": 179262, "author": "Trent", "author_id": 9083, "author_profile": "https://Stackoverflow.com/users/9083", "pm_score": 2, "selected": false, "text": "<p>I'll tackle the second part of your question:</p>\n\n<p>I normally use <code>&lt;project/libHeader.h&gt;</code> when I am including headers from a 3rd party. And <code>\"myHeader.h\"</code> when including headers from within the project.</p>\n\n<p>The reason I use <code>&lt;project/libHeader.h&gt;</code> instead of <code>&lt;libHeader.h&gt;</code> is because it's possible that more than one library has a \"libHeader.h\" file. In order to include them both you need the library name as part of the included filename.</p>\n" }, { "answer_id": 179436, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 3, "selected": false, "text": "<p>To quote from the C99 standard (at a glance the wording appears to be identical in the C90 standard, but I can't cut-n-paste from that):</p>\n\n<blockquote>\n <p>A preprocessing directive of the form</p>\n \n <p><code># include \"q-char-sequence\" new-line</code></p>\n \n <p>causes the replacement of that\n directive by the entire contents of\n the source file identified by the\n specified sequence between the \"\n delimiters. The named source file is\n searched for in an\n implementation-defined manner. If this\n search is not supported, or if the\n search fails, the directive is\n reprocessed as if it read</p>\n \n <p><code># include &lt;h-char-sequence&gt; new-line</code></p>\n \n <p>with the identical contained sequence\n (including > characters, if any) from\n the original directive.</p>\n</blockquote>\n\n<p>So the locations searched by <code>#include \"whatever\"</code> is a super-set of the locations searched by <code>#include &lt;whatever&gt;</code>. The intent is that the first style would be used for headers that in general \"belong\" to you, and the second method would be used for headers that \"belong\" to the compiler/environment. Of course, there are often some grey areas - which should you use for Boost headers, for example? I'd use <code>#include &lt;&gt;</code>, but I wouldn't argue too much if someone else on my team wanted <code>#include \"\"</code>. </p>\n\n<p>In practice, I don't think anyone pays much attention to which form is used as long as the build doesn't break. I certainly don't recall it ever being mentioned in a code review (or otherwise, even).</p>\n" }, { "answer_id": 179554, "author": "Brian Stewart", "author_id": 3114, "author_profile": "https://Stackoverflow.com/users/3114", "pm_score": 0, "selected": false, "text": "<p>We use #include \"header.h\" for headers local to the project and #include for system includes, third party includes, and other projects in the solution. We use Visual Studio, and it's much easier to use the project directory in a header include, this way whenever we create a new project, we only have to specify the include path for the directory containing all the project directories, not a separate path for each project.</p>\n" }, { "answer_id": 179631, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>1.a: What are the differences between the two notations?</p>\n\n<p>\"\" starts search in the directory where C/C++ file is located. &lt;> starts search in -I directories and in default locations (such as /usr/include). Both of them ultimately search the same set of locations, only the order is different.</p>\n\n<p>1.b: Do all compilers implement them the same way?</p>\n\n<p>I hope so, but I am not sure.</p>\n\n<p>1.c: When would you use the &lt;>, and when would you use the \"\" (i.e. what are the criteria you would use to use one or the other for a header include)?</p>\n\n<p>I use \"\" when the include file is supposed to be next to C file, &lt;> in all other cases. IN particular, in our project all \"public\" include files are in project/include directory, so I use &lt;> for them.</p>\n\n<p>2 - #include {TheProject/TheHeader.hpp} or {TheHeader.hpp} ?</p>\n\n<p>As already pointed out, xxx/filename.h allows you to do things like diskio/ErrorCodes.h and netio/ErrorCodes.h</p>\n\n<p>* private headers of your project?</p>\n\n<p>Private header of my subsystem in project. Use \"filename.h\"\nPublic header of my subsystem in project (not visible outside the project, but accessible to other subsystems). Use or , depending on the convention adapted for the project. I'd rather use </p>\n\n<p>* headers of your project, but which are exporting symbols (and thus, \"public\")</p>\n\n<p>include exactly like the users of your library would include them. Probably </p>\n\n<p>* headers of another project your module links with</p>\n\n<p>Determined by the project, but certainly using &lt;>\n* headers of a compiler or standard library\nDefinitely &lt;>, according to standard.</p>\n\n<p>3.a: Do you work on project with sources and/or headers within a tree-like organisation (i.e., directories inside directories, as opposed to \"every file in one directory\") and what are the pros/cons?</p>\n\n<p>I do work on a structured project. As soon as you have more than a score of files, some division will become apparent. You should go the way the code is pulling you.</p>\n" }, { "answer_id": 179786, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 1, "selected": false, "text": "<p>Re &lt;> vs \"\". At my shop, I'm very hands-off as far as matters of \"style\" are concerned. One of the few areas where I have a requirement is with the use of angle brackets in #include statements -- the rule is this: if you are #including an operating system or compiler file, you may use angle brackets if appropriate. In all other cases, they are forbidden. If you are #including a file written either by someone here or a 3rd party library, &lt;> is forbidden.</p>\n\n<p>The reason is this: #include \"x.h\" and #include don't search the same paths. #include will only search the system path and whatever you have -i'ed in. Importantly, it will not search the path where the file x.h is located, if that directory isn't included in the search path in some other way.</p>\n\n<p>For example, suppose you have the following files:</p>\n\n<p>c:\\dev\\angles\\main.cpp</p>\n\n<pre><code>#include \"c:\\utils\\mylib\\mylibrary.h\"\n\nint main()\n{\n return 0;\n}\n</code></pre>\n\n<p>c:\\utils\\mylib\\mylibrary.h</p>\n\n<pre><code>#ifndef MYLIB_H\n#define MYLIB_H\n\n#include &lt;speech.h&gt;\n\nnamespace mylib\n{\n void Speak(SpeechType speechType); \n};\n\n#endif\n</code></pre>\n\n<p>c:\\utils\\mhlib\\speech.h</p>\n\n<pre><code>#ifndef SPEECH_H\n#define SPEECH_H\n\nnamespace mylib\n{\n enum SpeechType {Bark, Growl};\n};\n\n#endif\n</code></pre>\n\n<p>This will not compile without changing the path either by setting the PATH environment variable or -i'ing in the c:\\utils\\mhlib\\ directory. The compiler won't be able to resove <code>#include &lt;speech.h&gt;</code> even though that file is in the same directory as <code>mylibrary.h</code>!</p>\n\n<p>We make extensive use of relative and absolute pathnames in #include statements in our code, for two reasons.</p>\n\n<p>1) By keeping libraries and components off the main source tree (ie, putting utility libraries in a special directory), we don;t couple the lifecycle of the library to the lifecycle of the application. This is particularly important when you have several distinct products that use common libraries.</p>\n\n<p>2) We use <a href=\"http://technet.microsoft.com/en-us/sysinternals/bb896768.aspx\" rel=\"nofollow noreferrer\">Junctions</a> to map a physical location on the hard drive to a directory on a logical drive, and then use a fully-qualified path on the logical drive in all #includes. For example:</p>\n\n<p><code>#include \"x:\\utils\\mylib.h\"</code> -- good, x: is a subst'ed drive, and x:\\utils points to c:\\code\\utils_1.0 on the hard drive</p>\n\n<p><code>#include \"c:\\utils_1.0\\mylib.h\"</code> -- bad! the application tha t#includes mylib.h is now coupled to a specific version of the MYLIB library, and all developers must have it on the same directory on thier hard drive, c:\\utils_1.0</p>\n\n<p>Finally, a broad but difficult to achieve goal of my team is to be able to support 1-click compiles. This includes being able to compile the main source tree by doing nothing more than getting code from source control and then hitting 'compile'. In particular, I abhor having to set paths &amp; machine-wide #include directories in order to be able to compile, because every little additional step you add to the set-up phase in buildign a development machine just makes it harder, easier to mess up, and it takes longer to get a new machine up to speed &amp; generating code.</p>\n" }, { "answer_id": 1251308, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 5, "selected": false, "text": "<p>After reading all answers, as well as compiler documentation, I decided I would follow the following standard.</p>\n<p>For all files, be them project headers or external headers, always use the pattern:</p>\n<pre><code>#include &lt;namespace/header.hpp&gt;\n</code></pre>\n<p>The namespace being at least one directory deep, to avoid collision.</p>\n<p>Of course, this means that the project directory where the project headers are should be added as &quot;default include header&quot; to the makefile, too.</p>\n<p>The reason for this choice is that I found the following information:</p>\n<h1>1. The include &quot;&quot; pattern is compiler-dependent</h1>\n<p>I'll give the answers below</p>\n<h2>1.a The Standard</h2>\n<p>Source:</p>\n<ul>\n<li>C++14 Working Draft n3797 : <a href=\"https://isocpp.org/files/papers/N3797.pdf\" rel=\"noreferrer\">https://isocpp.org/files/papers/N3797.pdf</a></li>\n<li>C++11, C++98, C99, C89 (the section quoted is unchanged in all those standards)</li>\n</ul>\n<p>In the section 16.2 Source file inclusion, we can read that:</p>\n<blockquote>\n<p>A preprocessing directive of the form</p>\n<pre><code> #include &lt;h-char-sequence&gt; new-line\n</code></pre>\n<p>searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the &lt; and &gt; delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.</p>\n</blockquote>\n<p>This means that #include &lt;...&gt; will search a file in an implementation defined manner.</p>\n<p>Then, the next paragraph:</p>\n<blockquote>\n<p>A preprocessing directive of the form</p>\n<pre><code> #include &quot;q-char-sequence&quot; new-line\n</code></pre>\n<p>causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the &quot; delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read</p>\n<pre><code> #include &lt;h-char-sequence&gt; new-line\n</code></pre>\n<p>with the identical contained sequence (including &gt; characters, if any) from the original directive.</p>\n</blockquote>\n<p>This means that #include &quot;...&quot; will search a file in an implementation defined manner and then, if the file is not found, will do another search as if it had been an #include &lt;...&gt;</p>\n<p>The conclusion is that we have to read the compilers documentation.</p>\n<p>Note that, for some reason, nowhere in the standards the difference is made between &quot;system&quot; or &quot;library&quot; headers or other headers. The only difference seem that #include &lt;...&gt; seems to target headers, while #include &quot;...&quot; seems to target source (at least, in the english wording).</p>\n<h2>1.b Visual C++:</h2>\n<p>Source:</p>\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx</a></li>\n</ul>\n<h3>#include &quot;MyFile.hpp&quot;</h3>\n<p>The preprocessor searches for include files in the following order:</p>\n<ol>\n<li>In the same directory as the file that contains the #include statement.</li>\n<li>In the directories of any previously opened include files in the reverse order in which they were opened. The search starts from the directory of the include file that was opened last and continues through the directory of the include file that was opened first.</li>\n<li>Along the path specified by each /I compiler option.</li>\n<li>(*) Along the paths specified by the INCLUDE environment variable or the development environment default includes.</li>\n</ol>\n<h3>#include &lt;MyFile.hpp&gt;</h3>\n<p>The preprocessor searches for include files in the following order:</p>\n<ol>\n<li>Along the path specified by each /I compiler option.</li>\n<li>(*) Along the paths specified by the INCLUDE environment variable or the development environment default includes.</li>\n</ol>\n<h3>Note about the last step</h3>\n<p>The document is not clear about the &quot;Along the paths specified by the INCLUDE environment variable&quot; part for both <code>&lt;...&gt;</code> and <code>&quot;...&quot;</code> includes. The following quote makes it stick with the standard:</p>\n<blockquote>\n<p>For include files that are specified as #include &quot;path-spec&quot;, directory searching begins with the directory of the parent file and then proceeds through the directories of any grandparent files. That is, searching begins relative to the directory that contains the source file that contains the #include directive that's being processed. If there is no grandparent file and the file has not been found, the search continues as if the file name were enclosed in angle brackets.</p>\n</blockquote>\n<p>The last step (marked by an asterisk) is thus an interpretation from reading the whole document.</p>\n<h2>1.c g++</h2>\n<p>Source:</p>\n<ul>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html\" rel=\"noreferrer\">https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/cpp/Include-Syntax.html\" rel=\"noreferrer\">https://gcc.gnu.org/onlinedocs/cpp/Include-Syntax.html</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/cpp/Include-Operation.html\" rel=\"noreferrer\">https://gcc.gnu.org/onlinedocs/cpp/Include-Operation.html</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/cpp/Invocation.html\" rel=\"noreferrer\">https://gcc.gnu.org/onlinedocs/cpp/Invocation.html</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/cpp/Search-Path.html\" rel=\"noreferrer\">https://gcc.gnu.org/onlinedocs/cpp/Search-Path.html</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/cpp/Once-Only-Headers.html\" rel=\"noreferrer\">https://gcc.gnu.org/onlinedocs/cpp/Once-Only-Headers.html</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/cpp/Wrapper-Headers.html\" rel=\"noreferrer\">https://gcc.gnu.org/onlinedocs/cpp/Wrapper-Headers.html</a></li>\n<li><a href=\"https://gcc.gnu.org/onlinedocs/cpp/System-Headers.html\" rel=\"noreferrer\">https://gcc.gnu.org/onlinedocs/cpp/System-Headers.html</a></li>\n</ul>\n<p>The following quote summarizes the process:</p>\n<blockquote>\n<p>GCC [...] will look for headers requested with #include <code>&lt;file&gt;</code> in [system directories] [...] All the directories named by -I are searched, in left-to-right order, before the default directories</p>\n<p>GCC looks for headers requested with #include &quot;file&quot; first in the directory containing the current file, then in the directories as specified by -iquote options, then in the same places it would have looked for a header requested with angle brackets.</p>\n</blockquote>\n<h3>#include &quot;MyFile.hpp&quot;</h3>\n<p>This variant is used for header files of your own program. The preprocessor searches for include files in the following order:</p>\n<ol>\n<li>In the same directory as the file that contains the #include statement.</li>\n<li>Along the path specified by each -iquote compiler option.</li>\n<li>As for the #include <code>&lt;MyFile.hpp&gt;</code></li>\n</ol>\n<h3>#include &lt;MyFile.hpp&gt;</h3>\n<p>This variant is used for system header files. The preprocessor searches for include files in the following order:</p>\n<ol>\n<li>Along the path specified by each -I compiler option.</li>\n<li>Inside the system directories.</li>\n</ol>\n<h2>1.d Oracle/Sun Studio CC</h2>\n<p>Source:</p>\n<ul>\n<li><a href=\"http://docs.oracle.com/cd/E19205-01/819-5265/bjadq/index.html\" rel=\"noreferrer\">http://docs.oracle.com/cd/E19205-01/819-5265/bjadq/index.html</a></li>\n</ul>\n<p>Note that the text contradict itself somewhat (see the example to understand). The key phrase is: &quot;<i>The difference is that the current directory is searched only for header files whose names you have enclosed in quotation marks.</i>&quot;</p>\n<h3>#include &quot;MyFile.hpp&quot;</h3>\n<p>This variant is used for header files of your own program. The preprocessor searches for include files in the following order:</p>\n<ol>\n<li>The current directory (that is, the directory containing the “including” file)</li>\n<li>The directories named with -I options, if any</li>\n<li>The system directory (e.g. the /usr/include directory)</li>\n</ol>\n<h3>#include &lt;MyFile.hpp&gt;</h3>\n<p>This variant is used for system header files. The preprocessor searches for include files in the following order:</p>\n<ol>\n<li>The directories named with -I options, if any</li>\n<li>The system directory (e.g. the /usr/include directory)</li>\n</ol>\n<h2>1.e XL C/C++ Compiler Reference - IBM/AIX</h2>\n<p>Source:</p>\n<ul>\n<li><a href=\"http://www.bluefern.canterbury.ac.nz/ucsc%20userdocs/forucscwebsite/c/aix/compiler.pdf\" rel=\"noreferrer\">http://www.bluefern.canterbury.ac.nz/ucsc%20userdocs/forucscwebsite/c/aix/compiler.pdf</a></li>\n<li><a href=\"http://www-01.ibm.com/support/docview.wss?uid=swg27024204&amp;aid=1\" rel=\"noreferrer\">http://www-01.ibm.com/support/docview.wss?uid=swg27024204&amp;aid=1</a></li>\n</ul>\n<p>Both documents are titled &quot;XL C/C++ Compiler Reference&quot; The first document is older (8.0), but is easier to understand. The second is newer (12.1), but is a bit more difficult to decrypt.</p>\n<h3>#include &quot;MyFile.hpp&quot;</h3>\n<p>This variant is used for header files of your own program. The preprocessor searches for include files in the following order:</p>\n<ol>\n<li>The current directory (that is, the directory containing the “including” file)</li>\n<li>The directories named with -I options, if any</li>\n<li>The system directory (e.g. the /usr/vac[cpp]/include or /usr/include directories)</li>\n</ol>\n<h3>#include &lt;MyFile.hpp&gt;</h3>\n<p>This variant is used for system header files. The preprocessor searches for include files in the following order:</p>\n<ol>\n<li>The directories named with -I options, if any</li>\n<li>The system directory (e.g. the /usr/vac[cpp]/include or /usr/include directory)</li>\n</ol>\n<h2>1.e Conclusion</h2>\n<p>The pattern &quot;&quot; could lead to subtle compilation error across compilers, and as I currently work both on Windows Visual C++, Linux g++, Oracle/Solaris CC and AIX XL, this is not acceptable.</p>\n<p>Anyway, the advantage of &quot;&quot; described features are far from interesting anyway, so...</p>\n<h1>2. Use the {namespace}/header.hpp pattern</h1>\n<p>I saw at work (<i>i.e. this is not theory, this is real-life, painful professional experience</i>) two headers with the same name, one in the local project directory, and the other in the global include.</p>\n<p>As we were using the &quot;&quot; pattern, and that file was included both in local headers and global headers, there was no way to understand what was really going on, when strange errors appeared.</p>\n<p>Using the directory in the include would have saved us time because the user would have had to either write:</p>\n<pre><code>#include &lt;MyLocalProject/Header.hpp&gt;\n</code></pre>\n<p>or</p>\n<pre><code>#include &lt;GlobalInclude/Header.hpp&gt;\n</code></pre>\n<p>You'll note that while</p>\n<pre><code>#include &quot;Header.hpp&quot;\n</code></pre>\n<p>would have compiled successfully, thus, still hiding the problem, whereas</p>\n<pre><code>#include &lt;Header.hpp&gt;\n</code></pre>\n<p>would not have compiled in normal circonstances.</p>\n<p>Thus, sticking to the &lt;&gt; notation would have made mandatory for the developer the prefixing of the include with the right directory, another reason to prefer &lt;&gt; to &quot;&quot;.</p>\n<h1>3. Conclusion</h1>\n<p>Using both the &lt;&gt; notation and namespaced notation together removes from the pre-compiler the possibility to guess for files, instead searching only the default include directories.</p>\n<p>Of course, the standard libraries are still included as usual, that is:</p>\n<pre><code>#include &lt;cstdlib&gt;\n#include &lt;vector&gt;\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14089/" ]
This is a multiple question for the same pre-processing instruction. 1 - <> or "" ? -------------- Apart from the info found in the MSDN: [#include Directive (C-C++)](https://msdn.microsoft.com/en-us/library/36k2cdd4.aspx "#include Directive (C-C++)") 1.a: What are the differences between the two notations? 1.b: Do all compilers implement them the same way? 1.c: When would you use the <>, and when would you use the "" (i.e. what are the criteria you would use to use one or the other for a header include)? 2 - #include {TheProject/TheHeader.hpp} or {TheHeader.hpp} ? ------------------------------------------------------------ I've seen at least two ways of writing includes of one's project headers. Considering that you have at least 4 types of headers, that is: * private headers of your project? * headers of your project, but which are exporting symbols (and thus, "public") * headers of another project your module links with * headers of a compiler or standard library For each kind of headers: 2.a: Would you use <> or "" ? 2.b: Would you include with {TheProject/TheHeader.hpp}, or with {TheHeader.hpp} only? 3 - Bonus --------- 3.a: Do you work on project with sources and/or headers within a tree-like organisation (i.e., directories inside directories, as opposed to "every file in one directory") and what are the pros/cons?
After reading all answers, as well as compiler documentation, I decided I would follow the following standard. For all files, be them project headers or external headers, always use the pattern: ``` #include <namespace/header.hpp> ``` The namespace being at least one directory deep, to avoid collision. Of course, this means that the project directory where the project headers are should be added as "default include header" to the makefile, too. The reason for this choice is that I found the following information: 1. The include "" pattern is compiler-dependent =============================================== I'll give the answers below 1.a The Standard ---------------- Source: * C++14 Working Draft n3797 : <https://isocpp.org/files/papers/N3797.pdf> * C++11, C++98, C99, C89 (the section quoted is unchanged in all those standards) In the section 16.2 Source file inclusion, we can read that: > > A preprocessing directive of the form > > > > ``` > #include <h-char-sequence> new-line > > ``` > > searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined. > > > This means that #include <...> will search a file in an implementation defined manner. Then, the next paragraph: > > A preprocessing directive of the form > > > > ``` > #include "q-char-sequence" new-line > > ``` > > causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read > > > > ``` > #include <h-char-sequence> new-line > > ``` > > with the identical contained sequence (including > characters, if any) from the original directive. > > > This means that #include "..." will search a file in an implementation defined manner and then, if the file is not found, will do another search as if it had been an #include <...> The conclusion is that we have to read the compilers documentation. Note that, for some reason, nowhere in the standards the difference is made between "system" or "library" headers or other headers. The only difference seem that #include <...> seems to target headers, while #include "..." seems to target source (at least, in the english wording). 1.b Visual C++: --------------- Source: * <http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx> ### #include "MyFile.hpp" The preprocessor searches for include files in the following order: 1. In the same directory as the file that contains the #include statement. 2. In the directories of any previously opened include files in the reverse order in which they were opened. The search starts from the directory of the include file that was opened last and continues through the directory of the include file that was opened first. 3. Along the path specified by each /I compiler option. 4. (\*) Along the paths specified by the INCLUDE environment variable or the development environment default includes. ### #include <MyFile.hpp> The preprocessor searches for include files in the following order: 1. Along the path specified by each /I compiler option. 2. (\*) Along the paths specified by the INCLUDE environment variable or the development environment default includes. ### Note about the last step The document is not clear about the "Along the paths specified by the INCLUDE environment variable" part for both `<...>` and `"..."` includes. The following quote makes it stick with the standard: > > For include files that are specified as #include "path-spec", directory searching begins with the directory of the parent file and then proceeds through the directories of any grandparent files. That is, searching begins relative to the directory that contains the source file that contains the #include directive that's being processed. If there is no grandparent file and the file has not been found, the search continues as if the file name were enclosed in angle brackets. > > > The last step (marked by an asterisk) is thus an interpretation from reading the whole document. 1.c g++ ------- Source: * <https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html> * <https://gcc.gnu.org/onlinedocs/cpp/Include-Syntax.html> * <https://gcc.gnu.org/onlinedocs/cpp/Include-Operation.html> * <https://gcc.gnu.org/onlinedocs/cpp/Invocation.html> * <https://gcc.gnu.org/onlinedocs/cpp/Search-Path.html> * <https://gcc.gnu.org/onlinedocs/cpp/Once-Only-Headers.html> * <https://gcc.gnu.org/onlinedocs/cpp/Wrapper-Headers.html> * <https://gcc.gnu.org/onlinedocs/cpp/System-Headers.html> The following quote summarizes the process: > > GCC [...] will look for headers requested with #include `<file>` in [system directories] [...] All the directories named by -I are searched, in left-to-right order, before the default directories > > > GCC looks for headers requested with #include "file" first in the directory containing the current file, then in the directories as specified by -iquote options, then in the same places it would have looked for a header requested with angle brackets. > > > ### #include "MyFile.hpp" This variant is used for header files of your own program. The preprocessor searches for include files in the following order: 1. In the same directory as the file that contains the #include statement. 2. Along the path specified by each -iquote compiler option. 3. As for the #include `<MyFile.hpp>` ### #include <MyFile.hpp> This variant is used for system header files. The preprocessor searches for include files in the following order: 1. Along the path specified by each -I compiler option. 2. Inside the system directories. 1.d Oracle/Sun Studio CC ------------------------ Source: * <http://docs.oracle.com/cd/E19205-01/819-5265/bjadq/index.html> Note that the text contradict itself somewhat (see the example to understand). The key phrase is: "*The difference is that the current directory is searched only for header files whose names you have enclosed in quotation marks.*" ### #include "MyFile.hpp" This variant is used for header files of your own program. The preprocessor searches for include files in the following order: 1. The current directory (that is, the directory containing the “including” file) 2. The directories named with -I options, if any 3. The system directory (e.g. the /usr/include directory) ### #include <MyFile.hpp> This variant is used for system header files. The preprocessor searches for include files in the following order: 1. The directories named with -I options, if any 2. The system directory (e.g. the /usr/include directory) 1.e XL C/C++ Compiler Reference - IBM/AIX ----------------------------------------- Source: * <http://www.bluefern.canterbury.ac.nz/ucsc%20userdocs/forucscwebsite/c/aix/compiler.pdf> * <http://www-01.ibm.com/support/docview.wss?uid=swg27024204&aid=1> Both documents are titled "XL C/C++ Compiler Reference" The first document is older (8.0), but is easier to understand. The second is newer (12.1), but is a bit more difficult to decrypt. ### #include "MyFile.hpp" This variant is used for header files of your own program. The preprocessor searches for include files in the following order: 1. The current directory (that is, the directory containing the “including” file) 2. The directories named with -I options, if any 3. The system directory (e.g. the /usr/vac[cpp]/include or /usr/include directories) ### #include <MyFile.hpp> This variant is used for system header files. The preprocessor searches for include files in the following order: 1. The directories named with -I options, if any 2. The system directory (e.g. the /usr/vac[cpp]/include or /usr/include directory) 1.e Conclusion -------------- The pattern "" could lead to subtle compilation error across compilers, and as I currently work both on Windows Visual C++, Linux g++, Oracle/Solaris CC and AIX XL, this is not acceptable. Anyway, the advantage of "" described features are far from interesting anyway, so... 2. Use the {namespace}/header.hpp pattern ========================================= I saw at work (*i.e. this is not theory, this is real-life, painful professional experience*) two headers with the same name, one in the local project directory, and the other in the global include. As we were using the "" pattern, and that file was included both in local headers and global headers, there was no way to understand what was really going on, when strange errors appeared. Using the directory in the include would have saved us time because the user would have had to either write: ``` #include <MyLocalProject/Header.hpp> ``` or ``` #include <GlobalInclude/Header.hpp> ``` You'll note that while ``` #include "Header.hpp" ``` would have compiled successfully, thus, still hiding the problem, whereas ``` #include <Header.hpp> ``` would not have compiled in normal circonstances. Thus, sticking to the <> notation would have made mandatory for the developer the prefixing of the include with the right directory, another reason to prefer <> to "". 3. Conclusion ============= Using both the <> notation and namespaced notation together removes from the pre-compiler the possibility to guess for files, instead searching only the default include directories. Of course, the standard libraries are still included as usual, that is: ``` #include <cstdlib> #include <vector> ```
179,223
<p>I want to add my own member to the StringBuilder class, but when I go to create it IntelliSense doesn't bring it up.</p> <pre><code>public class myStringBuilder() Inherits System.Text.[StringBuilder should be here] .... end class </code></pre> <p>Is it even possible? thanks</p>
[ { "answer_id": 179235, "author": "bdukes", "author_id": 2688, "author_profile": "https://Stackoverflow.com/users/2688", "pm_score": 2, "selected": false, "text": "<p>No, <a href=\"http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx\" rel=\"nofollow noreferrer\">StringBuilder</a> is a <a href=\"http://msdn.microsoft.com/en-us/library/h278d2d4.aspx\" rel=\"nofollow noreferrer\">NotInheritable</a> class. You could try wrapping a <a href=\"http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx\" rel=\"nofollow noreferrer\">StringBuilder</a> instance, but can't inherit from it. You can also use <a href=\"http://msdn.microsoft.com/en-us/library/bb384936.aspx\" rel=\"nofollow noreferrer\">extension methods</a>, if you're using .NET 3.5.</p>\n" }, { "answer_id": 179237, "author": "bobwienholt", "author_id": 24257, "author_profile": "https://Stackoverflow.com/users/24257", "pm_score": 1, "selected": false, "text": "<p>StringBuilder is a sealed class... so inheritance is not allowed.</p>\n" }, { "answer_id": 179239, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 1, "selected": false, "text": "<p>StringBuilder is sealed. You cannot inherit from it.</p>\n" }, { "answer_id": 179240, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 5, "selected": true, "text": "<p><code>StringBuilder</code> is <code>NotInheritable</code> (aka <code>sealed</code> in C#) so you cannot derive from it. You could try wrapping <code>StringBuilder</code> in your own class or consider using <a href=\"http://msdn.microsoft.com/en-us/library/bb384936.aspx\" rel=\"nofollow noreferrer\">extension methods</a> instead.</p>\n" }, { "answer_id": 179406, "author": "Jeff B", "author_id": 25879, "author_profile": "https://Stackoverflow.com/users/25879", "pm_score": 1, "selected": false, "text": "<p>If you're using an earlier version of .Net, you can write basically the same StringBuilderExtensions class and then explicitly call the static method instead.</p>\n\n<p>With .Net 3.5: <code>myStringBuilder.MyExtensionMethod(etc...);</code></p>\n\n<p>Pre- .Net 3.5: <code>StringBuilderExtensions.MyExtensionMethod(myStringBuilder, etc...);</code></p>\n" }, { "answer_id": 179728, "author": "Anders", "author_id": 25515, "author_profile": "https://Stackoverflow.com/users/25515", "pm_score": 2, "selected": false, "text": "<p>This is what I came up with, for those who are curious:</p>\n\n<pre><code>Imports System.Runtime.CompilerServices\nModule sbExtension\n &lt;Extension()&gt; _\n Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _\n ByVal format As String, _\n ByVal arg0 As Object)\n oStr.AppendFormat(\"{0}{1}\", String.Format(format, arg0), ControlChars.NewLine)\n End Sub\n &lt;Extension()&gt; _\n Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _\n ByVal format As String, ByVal arg0 As Object, _\n ByVal arg1 As Object)\n oStr.AppendFormat(\"{0}{1}\", String.Format(format, arg0, arg1), ControlChars.NewLine)\n End Sub\n &lt;Extension()&gt; _\n Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _\n ByVal format As String, _\n ByVal arg0 As Object, _\n ByVal arg1 As Object, _\n ByVal arg2 As Object)\n oStr.AppendFormat(\"{0}{1}\", String.Format(format, arg0, arg1, arg2), ControlChars.NewLine)\n End Sub\n &lt;Extension()&gt; _\n Public Sub AppendFormattedLine(ByVal oStr As System.Text.StringBuilder, _\n ByVal format As String, _\n ByVal ParamArray args() As Object)\n oStr.AppendFormat(\"{0}{1}\", String.Format(format, args), ControlChars.NewLine)\n End Sub\nEnd Module\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25515/" ]
I want to add my own member to the StringBuilder class, but when I go to create it IntelliSense doesn't bring it up. ``` public class myStringBuilder() Inherits System.Text.[StringBuilder should be here] .... end class ``` Is it even possible? thanks
`StringBuilder` is `NotInheritable` (aka `sealed` in C#) so you cannot derive from it. You could try wrapping `StringBuilder` in your own class or consider using [extension methods](http://msdn.microsoft.com/en-us/library/bb384936.aspx) instead.
179,254
<p>Has anyone got this working in a web application? </p> <p>No matter what I do it seems that my appSettings section (redirected from web.config using appSettings file=".\Site\site.config") does not get reloaded. </p> <p>Am I doomed to the case of having to just restart the application? I was hoping this method would lead me to a more performant solution.</p> <p>Update:</p> <p>By 'reloading' I mean refreshing ConfigurationManager.AppSettings without having to completely restart my ASP.NET application and having to incur the usual startup latency.</p>
[ { "answer_id": 179360, "author": "Seibar", "author_id": 357, "author_profile": "https://Stackoverflow.com/users/357", "pm_score": -1, "selected": false, "text": "<p>The App.Config settings are cached in memory when the application starts. For this reason, I don't think you'll be able to change those settings without restarting your application. One alternative that should be pretty straight forward would be to create a separate, simple XML configuration file, and handle loading/caching/reloading it yourself.</p>\n" }, { "answer_id": 330735, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>This seems to be a flaw (maybe a bug) when using an external config file for your appSettings. I've tried it using the configSource attribute and RefreshSection simply never works, I'm assuming this is the same when using the file attribute. \nIf you move your appSettings back inside your web.config RefreshSection will work perfectly but otherwise I'm afraid you're doomed. </p>\n" }, { "answer_id": 494972, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>To write, call it this way:</p>\n\n<p>Dim config As System.Configuration.Configuration = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(\"~\")</p>\n\n<p>Return AddOrUpdateAppSetting(config, \"YourSettingKey\", \"YourValueForTheKey\")</p>\n\n<p>To read and be sure you get the values in file, instead of those in cache, read it this way:</p>\n\n<pre><code>Dim config As System.Configuration.Configuration = WebConfigurationManager.OpenWebConfiguration(\"~\")\n Return config.AppSettings.Settings(\"TheKeyYouWantTheValue\").Value\n</code></pre>\n\n<p>Full example:</p>\n\n<pre><code>Protected Shared Function AddOrUpdateAppSetting( _\n ByVal Config As System.Configuration.Configuration _\n , ByVal TheKey As String _\n , ByVal TheValue As String _\n ) As Boolean&lt;/p&gt;\n\n Dim retval As Boolean = True\n\n Dim Itm As System.Configuration.KeyValueConfigurationElement = _\n Config.AppSettings.Settings.Item(TheKey)\n If Itm Is Nothing Then\n If Config.AppSettings.Settings.IsReadOnly Then\n retval = False\n Else\n Config.AppSettings.Settings.Add(TheKey, TheValue)\n End If\n\n\n Else\n ' config.AppSettings.Settings(thekey).Value = thevalue\n If Itm.IsReadOnly Then\n retval = False\n Else\n Itm.Value = TheValue\n End If\n\n\n End If\n If retval Then\n Try\n Config.Save(ConfigurationSaveMode.Modified)\n\n Catch ex As Exception\n retval = False\n End Try\n\n End If\n\n Return retval\n\nEnd Function\n</code></pre>\n" }, { "answer_id": 1592129, "author": "G-Wiz", "author_id": 29805, "author_profile": "https://Stackoverflow.com/users/29805", "pm_score": 7, "selected": true, "text": "<p>Make sure you are passing the correct <a href=\"http://en.wikipedia.org/wiki/Case_sensitivity\" rel=\"noreferrer\">case sensitive</a> value to RefreshSection, i.e. </p>\n\n<pre><code>ConfigurationManager.RefreshSection(\"appSettings\");\n</code></pre>\n" }, { "answer_id": 2595281, "author": "Vince", "author_id": 291719, "author_profile": "https://Stackoverflow.com/users/291719", "pm_score": -1, "selected": false, "text": "<p>Have you tried storing your AppSettings in its own external file?</p>\n\n<p>From app.config/web.config:</p>\n\n<pre><code>&lt;appSettings configSource=\"appSettings.config\"&gt;&lt;/appSettings&gt;\n</code></pre>\n\n<p>appSettings.config:</p>\n\n<pre><code>&lt;?xml version=\"1.0\"?&gt;\n&lt;appSettings&gt;\n &lt;add key=\"SomeKey\" value=\"SomeValue\" /&gt;\n&lt;/appSettings&gt;\n</code></pre>\n\n<p>Changes made to appSettings.config should be reflected instantly.\nMore info:\n<a href=\"http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource.aspx</a></p>\n" }, { "answer_id": 2852111, "author": "yamspog", "author_id": 69983, "author_profile": "https://Stackoverflow.com/users/69983", "pm_score": 0, "selected": false, "text": "<p>Yes. you are stuck with iis restarting.</p>\n\n<p>There is a feature with asp.net 4.0 and iis 7.5 where the initial startup is removed.</p>\n" }, { "answer_id": 3049405, "author": "badpanda", "author_id": 259648, "author_profile": "https://Stackoverflow.com/users/259648", "pm_score": 0, "selected": false, "text": "<p>I am not sure if this is possible in a web app, but it works in a desktop app. Try using ConfigurationSettings rather than ConfigurationManager (it will yell at you for using outdated classes...), then reading all the data into a class. When you wish to refresh, simply create a new instance and drop all references to the old instance. My theory for why this works (might be wrong): when you don't directly access the app.config file the entire time you are running, the file lock is dropped by the application. Then, edits can be made when you are not accessing the file.</p>\n" }, { "answer_id": 8481926, "author": "Martin Meixger", "author_id": 64466, "author_profile": "https://Stackoverflow.com/users/64466", "pm_score": 2, "selected": false, "text": "<p>As an alternative you could write your own <code>ConfigSection</code> and set <code>restartOnExternalChanges=\"false\"</code>.</p>\n\n<p>Then, when reading the section with <code>ConfigurationManager.GetSection(\"yourSection\")</code> the settings will be <strong>auto-refreshed without an application restart</strong>.</p>\n\n<p>And you could implement your settings strongly typed or as NameValueCollection.</p>\n" }, { "answer_id": 15218973, "author": "Willem van Ketwich", "author_id": 512965, "author_profile": "https://Stackoverflow.com/users/512965", "pm_score": 3, "selected": false, "text": "<p>For some reason <code>ConfigurationManager.RefreshSection(\"appSettings\")</code> wasn't working for me. Reloading the Web.Config into a Configuration object seems to work correctly. The following code assumes the Web.Config file is one directory below the executing (bin) folder.</p>\n\n<pre><code>ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();\nUri uriAssemblyFolder = new Uri(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase));\nstring appPath = uriAssemblyFolder.LocalPath;\nconfigMap.ExeConfigFilename = appPath + @\"\\..\\\" + \"Web.config\";\nConfiguration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None); \n</code></pre>\n\n<p>And is used like: </p>\n\n<pre><code>string webConfigVariable = config.AppSettings.Settings[\"webConfigVariable\"].Value;\n</code></pre>\n" }, { "answer_id": 41505562, "author": "Allie", "author_id": 1986822, "author_profile": "https://Stackoverflow.com/users/1986822", "pm_score": 2, "selected": false, "text": "<p>.RefreshSection() does not work when the appSettings is external.</p>\n\n<p>You can however use the following to change a value:</p>\n\n<pre><code>ConfigurationManager.AppSettings.Set(key, value)\n</code></pre>\n\n<p>This will NOT change the setting on file, only the loaded value in memory.</p>\n\n<p>So instead of using RefreshSection I did the following:</p>\n\n<pre><code>string configFile=\"path to your config file\";\nXmlDocument xml = new XmlDocument();\nxml.Load(configFile);\n\nforeach (XmlNode node in xml.SelectNodes(\"/appSettings/add\"))\n{\n string key = node.Attributes[\"key\"].Value;\n string value= node.Attributes[\"value\"].Value;\n ConfigurationManager.AppSettings.Set(key, value);\n}\n</code></pre>\n\n<p>Any subsequent calls to AppSettings.Get will contain the updated value.</p>\n\n<p>The appSettings will then be updated without needing to restart the application.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5777/" ]
Has anyone got this working in a web application? No matter what I do it seems that my appSettings section (redirected from web.config using appSettings file=".\Site\site.config") does not get reloaded. Am I doomed to the case of having to just restart the application? I was hoping this method would lead me to a more performant solution. Update: By 'reloading' I mean refreshing ConfigurationManager.AppSettings without having to completely restart my ASP.NET application and having to incur the usual startup latency.
Make sure you are passing the correct [case sensitive](http://en.wikipedia.org/wiki/Case_sensitivity) value to RefreshSection, i.e. ``` ConfigurationManager.RefreshSection("appSettings"); ```
179,255
<p>If I have an Address object which implements IEditableObject, I might have EndEdit implementation like this:</p> <pre><code>public void EndEdit() { // BeginEdit would set _editInProgress and update *Editing fields; if (_editInProgress) { _line1 = _line1Editing; _line2 = _line2Editing; _city = _cityEditing; _state = _stateEditing; _postalCode = _postalCodeEditing; _editInProgress = false; } } </code></pre> <p>If there is an exception updating <strong><em>_state</em></strong>, for example, then all 5 properties should reset. This atomic update issue probably isn't limited to EndEdit.</p>
[ { "answer_id": 179458, "author": "akmad", "author_id": 1314, "author_profile": "https://Stackoverflow.com/users/1314", "pm_score": 1, "selected": false, "text": "<p>First off, Kent is correct in wondering why setting a field would throw an exception.<br>\nIgnoring that question; you could just use a simple:</p>\n\n<pre><code>try {\n //do stuff\n}\ncatch (Exception ex) {\n //reset\n\n //rethrow exception\n throw;\n}\n</code></pre>\n\n<p>The complications come in with regards to what constitutes the reset value for each field? </p>\n\n<ul>\n<li>The last value</li>\n<li>A default value</li>\n<li>Some token value denoting an invalid state</li>\n<li>A mix of the above</li>\n</ul>\n\n<p>If you need to \"reset\" to the last value then you'll likely want some way to easily store the object state before doing something to it, along with the ability to easily restore that state should something go wrong. Check out the <a href=\"http://www.primos.com.au/primos/Default.aspx?PageContentID=8&amp;tabid=63\" rel=\"nofollow noreferrer\">Momento Pattern</a> on a nifty way to deal with that problem.</p>\n" }, { "answer_id": 3260716, "author": "Jonathan Allen", "author_id": 5274, "author_profile": "https://Stackoverflow.com/users/5274", "pm_score": 0, "selected": false, "text": "<p>I don't use fields for storing values. Instead I use a hash table that the properties can read and write. This gives me a really simple design.</p>\n\n<pre><code>Friend Sub BeginEdit()\n m_Backup = New Dictionary(Of String, Object)(m_DataPoints, StringComparer.OrdinalIgnoreCase)\nEnd Sub\n\nFriend Sub CancelEdit()\n If m_Backup IsNot Nothing Then m_DataPoints = m_Backup\nEnd Sub\n\nFriend Sub EndEdit()\n m_Backup = Nothing\nEnd Sub\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25856/" ]
If I have an Address object which implements IEditableObject, I might have EndEdit implementation like this: ``` public void EndEdit() { // BeginEdit would set _editInProgress and update *Editing fields; if (_editInProgress) { _line1 = _line1Editing; _line2 = _line2Editing; _city = _cityEditing; _state = _stateEditing; _postalCode = _postalCodeEditing; _editInProgress = false; } } ``` If there is an exception updating ***\_state***, for example, then all 5 properties should reset. This atomic update issue probably isn't limited to EndEdit.
First off, Kent is correct in wondering why setting a field would throw an exception. Ignoring that question; you could just use a simple: ``` try { //do stuff } catch (Exception ex) { //reset //rethrow exception throw; } ``` The complications come in with regards to what constitutes the reset value for each field? * The last value * A default value * Some token value denoting an invalid state * A mix of the above If you need to "reset" to the last value then you'll likely want some way to easily store the object state before doing something to it, along with the ability to easily restore that state should something go wrong. Check out the [Momento Pattern](http://www.primos.com.au/primos/Default.aspx?PageContentID=8&tabid=63) on a nifty way to deal with that problem.
179,259
<p>In my app I have these Hibernate-mapped types (general case):</p> <pre><code>class RoleRule { private Role role; private PermissionAwareEntity entity; // hibernate-mapped entity for which permission is granted private PermissionType permissionType; // enum @ManyToOne @JoinColumn(name = "ROLE_ID") public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } } class Role { private Set&lt;RoleRule&gt; rules = new HashSet&lt;RoleRule&gt;(0); @OneToMany(cascade=CascadeType.ALL) @JoinColumn(name="ROLE_ID") public Set&lt;RoleRule&gt; getRules() { return rules; } public void setRules(Set&lt;RoleRule&gt; rules) { this.rules = rules; } } </code></pre> <p>All classes have <code>equals() &amp; hashCode()</code> overrides.</p> <p>My application allows tweaking of roles (by sysadmins only, don't worry), and among other fields, allows creation of new role rules. When a new rule is created I try to create a new <code>RoleRule</code> object and insert it into the role's field <code>rules</code>. I call <code>session.update(role)</code> to apply the changes to the database.</p> <p>Now comes the ugly part... Hibernate decides to do the following when closing the transaction and flushing:</p> <ol> <li>Insert the new rule into the database. Excellent.</li> <li>Update the other role fields (not collections). So far so good.</li> <li>Update the existing rules, even if nothing has changed in them. I can live with this.</li> <li>Update the existing rules <em>again</em>. Here's a paste from the log, including the automatic comment:<br></li> </ol> <pre>/* delete one-to-many row Role.rules */ update ROLE_RULE set ROLE_ID=null where ROLE_ID=? and ROLE_RULE_ID=?</pre> <p>Of course, all fields are not-null, and this operation fails spectacularly.</p> <p>Can anyone try to explain why Hibernate would do this??? And even more important, how the frak do I get around this???</p> <p><strong>EDIT</strong>: I was so sure it was something to do with the mapping, and then my boss, on a whim, deleted the <code>equals()</code> and <code>hashCode()</code> in both classes, recreated them using Eclipse, and mysteriously this solved the problem.</p> <p>I'm still very curious about my question though. Can anyone suggest why Hibernate would do this?</p>
[ { "answer_id": 179324, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 2, "selected": false, "text": "<p>I'm not sure if this is the solution, but you might want to try:</p>\n\n<pre><code>@OneToMany(mappedBy = \"role\")\n</code></pre>\n\n<p>And not have the @JoinColumn annotation? I think both entities are trying to 'own' the association, which is why the SQL might be messed up?</p>\n\n<p>Also, if you want to ensure only affected columns get updated, you can use a hibernate-specific annotation on the class:</p>\n\n<pre><code>@Entity\[email protected](\n dynamicInsert = true, dynamicUpdate = true\n)\n</code></pre>\n" }, { "answer_id": 179524, "author": "Brian Deterling", "author_id": 14619, "author_profile": "https://Stackoverflow.com/users/14619", "pm_score": 3, "selected": false, "text": "<p>I've generally used two methods of updating a collection (the many side of a one-to-many) in Hibernate. The brute force way is to clear the collection, call save on the parent, and then call flush. Then add all of the collection members back and call save on the parent again. This will delete all and then insert all. The flush in the middle is key because it forces the delete to happen before the insert. It's probably best to only use this method on small collections since it does re-insert all of them.</p>\n\n<p>The second way is harder to code, but more efficient. You loop through the new set of children and manually modify the ones that are still there, delete the ones that aren't, and then add the new ones. In pseudo-code that would be:</p>\n\n<pre><code>copy the list of existing records to a list_to_delete\nfor each record from the form\n remove it from the list_to_delete\n if the record exists (based on equals()? key?)\n change each field that the user can enter\n else if the record doesn't exist\n add it to the collection\nend for\nfor each list_to_delete\n remove it\nend for\nsave\n</code></pre>\n\n<p>I've searched the Hibernate forums for many hours trying to find the right way to solve this problem. You should be able to just update your collection to make it accurate and then save the parent, but as you've found out, Hibernate tries to detach the children from the parent before deleting them and if the foreign key is not-null, it will fail.</p>\n" }, { "answer_id": 1078295, "author": "HeDinges", "author_id": 11466, "author_profile": "https://Stackoverflow.com/users/11466", "pm_score": 3, "selected": false, "text": "<p>See the answer of the question '<a href=\"https://stackoverflow.com/questions/27581/overriding-equals-and-hashcode-in-java\">Overriding equals and hashCode in Java</a>'.</p>\n\n<p>It explains how to override the equals and hashCode methods, which seemed to be your problem as it worked after having them rewritten.</p>\n\n<p>Wrongly overriding them can lead hibernate to delete your collections and reinsert them. (as the hash key is used as keys in maps) </p>\n" }, { "answer_id": 49102915, "author": "Jeya Balaji", "author_id": 5338935, "author_profile": "https://Stackoverflow.com/users/5338935", "pm_score": -1, "selected": false, "text": "<p>Brian Deterling's answer helped me to overcome the phantom delete. I wish he had put a real code. Here is what I got from his suggestion 1. Posting for someone to use it or to comment my code.</p>\n\n<pre><code>// snFile and task share many to many relationship\n\n@PersistenceContext\nprivate EntityManager em;\n\npublic SnFile merge(SnFile snFile) {\n log.debug(\"Request to merge SnFile : {}\", snFile);\n\n Set&lt;Task&gt; tasks = taskService.findBySnFilesId(snFile.getId());\n if(snFile.getTasks() != null) {\n snFile.getTasks().clear();\n }\n em.merge(snFile);\n em.flush();\n if(tasks != null) {\n if(snFile.getTasks() != null)\n snFile.getTasks().addAll(tasks);\n else\n snFile.setTasks(tasks);\n }\n\n return em.merge(snFile);\n }\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2819/" ]
In my app I have these Hibernate-mapped types (general case): ``` class RoleRule { private Role role; private PermissionAwareEntity entity; // hibernate-mapped entity for which permission is granted private PermissionType permissionType; // enum @ManyToOne @JoinColumn(name = "ROLE_ID") public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } } class Role { private Set<RoleRule> rules = new HashSet<RoleRule>(0); @OneToMany(cascade=CascadeType.ALL) @JoinColumn(name="ROLE_ID") public Set<RoleRule> getRules() { return rules; } public void setRules(Set<RoleRule> rules) { this.rules = rules; } } ``` All classes have `equals() & hashCode()` overrides. My application allows tweaking of roles (by sysadmins only, don't worry), and among other fields, allows creation of new role rules. When a new rule is created I try to create a new `RoleRule` object and insert it into the role's field `rules`. I call `session.update(role)` to apply the changes to the database. Now comes the ugly part... Hibernate decides to do the following when closing the transaction and flushing: 1. Insert the new rule into the database. Excellent. 2. Update the other role fields (not collections). So far so good. 3. Update the existing rules, even if nothing has changed in them. I can live with this. 4. Update the existing rules *again*. Here's a paste from the log, including the automatic comment: ``` /* delete one-to-many row Role.rules */ update ROLE_RULE set ROLE_ID=null where ROLE_ID=? and ROLE_RULE_ID=? ``` Of course, all fields are not-null, and this operation fails spectacularly. Can anyone try to explain why Hibernate would do this??? And even more important, how the frak do I get around this??? **EDIT**: I was so sure it was something to do with the mapping, and then my boss, on a whim, deleted the `equals()` and `hashCode()` in both classes, recreated them using Eclipse, and mysteriously this solved the problem. I'm still very curious about my question though. Can anyone suggest why Hibernate would do this?
I've generally used two methods of updating a collection (the many side of a one-to-many) in Hibernate. The brute force way is to clear the collection, call save on the parent, and then call flush. Then add all of the collection members back and call save on the parent again. This will delete all and then insert all. The flush in the middle is key because it forces the delete to happen before the insert. It's probably best to only use this method on small collections since it does re-insert all of them. The second way is harder to code, but more efficient. You loop through the new set of children and manually modify the ones that are still there, delete the ones that aren't, and then add the new ones. In pseudo-code that would be: ``` copy the list of existing records to a list_to_delete for each record from the form remove it from the list_to_delete if the record exists (based on equals()? key?) change each field that the user can enter else if the record doesn't exist add it to the collection end for for each list_to_delete remove it end for save ``` I've searched the Hibernate forums for many hours trying to find the right way to solve this problem. You should be able to just update your collection to make it accurate and then save the parent, but as you've found out, Hibernate tries to detach the children from the parent before deleting them and if the foreign key is not-null, it will fail.
179,264
<p>I have an ASP.Net 3.5 platform and windows 2003 server with all the updates. </p> <p>There is a limit with .Net that it cannot handle more than <a href="http://forums.iis.net/p/1105360/1689855.aspx" rel="noreferrer">260 characters</a>. Moreover if you look it up on web, you will find that IE 6 fails to work if it is not patched at above 100 charcters. </p> <p>I want to have the rewrite path module to be supported on maximum number of browsers, so I am looking for an acceptable limit to which I can create verbose URL's.</p>
[ { "answer_id": 179271, "author": "Mike Fielden", "author_id": 4144, "author_profile": "https://Stackoverflow.com/users/4144", "pm_score": 0, "selected": false, "text": "<p>More information is needed but for normal situations I would say try to keep it under 150 for sure. If for nothing else than pure ascetics, I hate when someone sends me a GI-NORMOUS link... </p>\n\n<p>Are you passing values through the query string? I assume that is why you asked, correct?</p>\n" }, { "answer_id": 179277, "author": "Mike Pone", "author_id": 16404, "author_profile": "https://Stackoverflow.com/users/16404", "pm_score": 2, "selected": false, "text": "<p>There is no length limit specified by the W3C, but look here for practical limits</p>\n\n<p><a href=\"http://www.boutell.com/newfaq/misc/urllength.html\" rel=\"nofollow noreferrer\">http://www.boutell.com/newfaq/misc/urllength.html</a></p>\n\n<p>pick your own limit from that.</p>\n" }, { "answer_id": 179279, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.boutell.com/newfaq/misc/urllength.html\" rel=\"nofollow noreferrer\">This article</a> gives the limits imposed by various browsers. It seems that IE limits the URL to 2083 chars, so you should probably stay under that if any of your users are on IE.</p>\n" }, { "answer_id": 179281, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 2, "selected": false, "text": "<p>The default limit in IIS is 16,384 characters</p>\n\n<p>But <a href=\"http://support.microsoft.com/kb/q208427/\" rel=\"nofollow noreferrer\">IE doesn't support more than 2083</a> </p>\n\n<p>More info at <a href=\"http://www.boutell.com/newfaq/misc/urllength.html\" rel=\"nofollow noreferrer\">link</a></p>\n" }, { "answer_id": 179282, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 1, "selected": false, "text": "<p>I think the RFC says 4096 chars but IE truncates down to 2083 characters. Stay well under that to be safe.</p>\n\n<p>Practically, shorter URLs are friendlier.</p>\n" }, { "answer_id": 179283, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 2, "selected": false, "text": "<p>Define \"optimum\" for your application.</p>\n\n<p>The HTTP standard has a limit (it depends on your application):</p>\n\n<blockquote>\n <p>The HTTP protocol does not place any\n a priori limit on the length of a URI.\n Servers MUST be able to handle the URI\n of any resource they serve, and SHOULD\n be able to handle URIs of unbounded\n length if they provide GET-based forms\n that could generate such URIs. A\n server SHOULD return 414 (Request-URI\n Too Long) status if a URI is longer\n than the server can handle (see\n section 10.4.15).</p>\n\n<pre><code> Note: Servers ought to be cautious about depending on URI\n lengths above 255 bytes, because some older client or proxy\n implementations might not properly support these lengths.\n</code></pre>\n</blockquote>\n\n<p>So the question is - what is the limit of your program, or what is the maximum resource identifier size your program needs to perform all its functionality?</p>\n\n<p>Your program should have a natural limit.</p>\n\n<p>If it doesn't you might as well stick it as 16k, as you don't have enough information to define the problem.</p>\n\n<p>-Adam</p>\n" }, { "answer_id": 179284, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 0, "selected": false, "text": "<p>What is \"optimum\" anyway?</p>\n\n<p>GET requests can be several kB in length, so this is entirely subjective.</p>\n\n<p>I'd say - stay within the address bar length of a maximized 1024x768 window to be user friendly.</p>\n" }, { "answer_id": 179292, "author": "Dan Goldstein", "author_id": 23427, "author_profile": "https://Stackoverflow.com/users/23427", "pm_score": 0, "selected": false, "text": "<p>If you're trying to get people to remember the URL, I wouldn't go more than 60. Use words if possible, because it's easier to remember \"www.example.com/this-is-the-url\" than \"www.example.com/179264\". If you're trying to get the page indexed, you could probably go more. The spiders look for words in the title too, and some people may be more likely to click on the link if the URL looks readable.</p>\n" }, { "answer_id": 179294, "author": "Mecki", "author_id": 15809, "author_profile": "https://Stackoverflow.com/users/15809", "pm_score": 2, "selected": false, "text": "<p>Short ;-)</p>\n\n<p>The problem is that every web server and every browser has own ideas how long the maximum is. The RFC for the HTTP protocol gives no maximum length. IE limits the get to 2083 characters, the path itself may be at most 2,048 characters. However, this limit is not universal. Firefox claims to support at least up to 65,536, however some people verified that on some platforms even 100,000 characters work. Safari is above 80,000 (tested). Apache server on the other hand has a limit of 4,000. Microsofts Internet Information Server has one being 16,384 (but it is configurable).</p>\n\n<p>My recommendation is to stay below 2'000 characters in any case. This is not guaranteed to work with every browser in the world (especially not older ones), but it will work with all modern browsers. Further I recommend to use POST wherever possible (e.g. avoid using GET for FORM submits - if some users want to simulate a FORM submit via GET, make sure your application supports the desired parameters either via POST or via GET, but when you submit the page yourself via a button or JS, prefer POST over GET).</p>\n" }, { "answer_id": 180183, "author": "Robert Paulson", "author_id": 14033, "author_profile": "https://Stackoverflow.com/users/14033", "pm_score": 4, "selected": true, "text": "<p>A Url is path + querystring, and the linked article only talks about limiting the path. Therefore, if you're using asp.net, don't exceed a path of 260 characters. Less than 260 will always work, and asp.net has no troubles with long querystrings.</p>\n\n<pre><code>http://somewhere.com/directory/filename.aspx?id=1234\n ^^^^^^^- querystring\n ^^^^^^^^^^^^^^^^^^^^^^^^ -------- path\n</code></pre>\n\n<p>Typically the issue is with the browser. Long ago I did tests and recall that many browsers support 4k url's, except for IE which limits it to 2083, so for all practical purposes, limit it to 2083. I don't know if IE7 and 8 have the limitation, but if you're going to broad compatibility, you need to go for the lowest common denominator.</p>\n" }, { "answer_id": 181267, "author": "Joe Morgan", "author_id": 13244, "author_profile": "https://Stackoverflow.com/users/13244", "pm_score": 0, "selected": false, "text": "<p>When you say \"Optimum\", I think \"Easily Accessible To Users\", in which case, I think the shorter the URL, the better. I would think 20-30 characters maximum, in that case.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9498/" ]
I have an ASP.Net 3.5 platform and windows 2003 server with all the updates. There is a limit with .Net that it cannot handle more than [260 characters](http://forums.iis.net/p/1105360/1689855.aspx). Moreover if you look it up on web, you will find that IE 6 fails to work if it is not patched at above 100 charcters. I want to have the rewrite path module to be supported on maximum number of browsers, so I am looking for an acceptable limit to which I can create verbose URL's.
A Url is path + querystring, and the linked article only talks about limiting the path. Therefore, if you're using asp.net, don't exceed a path of 260 characters. Less than 260 will always work, and asp.net has no troubles with long querystrings. ``` http://somewhere.com/directory/filename.aspx?id=1234 ^^^^^^^- querystring ^^^^^^^^^^^^^^^^^^^^^^^^ -------- path ``` Typically the issue is with the browser. Long ago I did tests and recall that many browsers support 4k url's, except for IE which limits it to 2083, so for all practical purposes, limit it to 2083. I don't know if IE7 and 8 have the limitation, but if you're going to broad compatibility, you need to go for the lowest common denominator.
179,287
<p>Let's say I have an existing trivial XML file named 'MyData.xml' that contains the following:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;myElement&gt;foo&lt;/myElement&gt; </code></pre> <p>I want to change the text value of 'foo' to 'bar' resulting in the following:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; &lt;myElement&gt;bar&lt;/myElement&gt; </code></pre> <p>Once I am done, I want to save the changes. </p> <p>What is the easiest and simplest way to accomplish all this?</p>
[ { "answer_id": 179305, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 2, "selected": false, "text": "<p>For quick, non-critical XML manipulations, i really like <a href=\"http://ponderer.org/p4x\" rel=\"nofollow noreferrer\">P4X</a>. It let's you write like this:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>import p4x\ndoc = p4x.P4X (open(file).read)\ndoc.myElement = 'bar'\n</code></pre>\n" }, { "answer_id": 179306, "author": "Ryan", "author_id": 17917, "author_profile": "https://Stackoverflow.com/users/17917", "pm_score": 3, "selected": true, "text": "<p>Use Python's <a href=\"http://docs.python.org/library/xml.dom.minidom.html\" rel=\"nofollow noreferrer\">minidom</a></p>\n\n<p>Basically you will take the following steps:</p>\n\n<ol>\n<li>Read XML data into DOM object</li>\n<li>Use DOM methods to modify the document</li>\n<li>Save new DOM object to new XML document</li>\n</ol>\n\n<p>The python spec should hold your hand rather nicely though this process. </p>\n" }, { "answer_id": 180433, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 2, "selected": false, "text": "<p>This is what I wrote based on <a href=\"https://stackoverflow.com/questions/179287/what-is-the-best-way-to-change-text-contained-in-an-xml-file-using-python#179306\">@Ryan's answer</a>:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>from xml.dom.minidom import parse\nimport os\n\n# create a backup of original file\nnew_file_name = 'MyData.xml'\nold_file_name = new_file_name + \"~\"\nos.rename(new_file_name, old_file_name)\n\n# change text value of element\ndoc = parse(old_file_name)\nnode = doc.getElementsByTagName('myElement')\nnode[0].firstChild.nodeValue = 'bar'\n\n# persist changes to new file\nxml_file = open(new_file_name, \"w\")\ndoc.writexml(xml_file, encoding=\"utf-8\")\nxml_file.close()\n</code></pre>\n\n<p>Not sure if this was the easiest and simplest approach but it does work. (<a href=\"https://stackoverflow.com/questions/179287/what-is-the-best-way-to-change-text-contained-in-an-xml-file-using-python#179305\">@Javier's answer</a> has less lines of code but requires non-standard library)</p>\n" }, { "answer_id": 180564, "author": "machineghost", "author_id": 5921, "author_profile": "https://Stackoverflow.com/users/5921", "pm_score": 1, "selected": false, "text": "<p>You also might want to check out Uche Ogbuji's excellent XML Data Binding Library, Amara:\n<a href=\"http://uche.ogbuji.net/tech/4suite/amara\" rel=\"nofollow noreferrer\">http://uche.ogbuji.net/tech/4suite/amara</a></p>\n\n<p>(Documentation here:\n<a href=\"http://platea.pntic.mec.es/~jmorilla/amara/manual/\" rel=\"nofollow noreferrer\">http://platea.pntic.mec.es/~jmorilla/amara/manual/</a>)</p>\n\n<p>The cool thing about Amara is that it turns an XML document in to a Python object, so you can just do stuff like:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>record = doc.xml_create_element(u'Record')\n\nnameElem = doc.xml_create_element(u'Name', content=unicode(name))\n\nrecord.xml_append(nameElem)\n\nvalueElem = doc.xml_create_element(u'Value', content=unicode(value))\n\nrecord.xml_append(valueElem\n</code></pre>\n\n<p>(which creates a Record element that contains Name and Value elements (which in turn contain the values of the name and value variables)).</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
Let's say I have an existing trivial XML file named 'MyData.xml' that contains the following: ``` <?xml version="1.0" encoding="utf-8" ?> <myElement>foo</myElement> ``` I want to change the text value of 'foo' to 'bar' resulting in the following: ``` <?xml version="1.0" encoding="utf-8" ?> <myElement>bar</myElement> ``` Once I am done, I want to save the changes. What is the easiest and simplest way to accomplish all this?
Use Python's [minidom](http://docs.python.org/library/xml.dom.minidom.html) Basically you will take the following steps: 1. Read XML data into DOM object 2. Use DOM methods to modify the document 3. Save new DOM object to new XML document The python spec should hold your hand rather nicely though this process.
179,288
<p>Say I have 3 frames in a frameset arranged in 3 rows. Frames 1 and 3 are from my site and frame 2 (the central one) is from an external website. Is there a cunning way to force the browser to centre align the data in frame 2?</p> <p>I've found a small work-around which uses a frameset within a frameset which has 2 blank columns either side of the data but that means the scrollbars from frames 2 and 3 are out of alignment.</p> <p>Any ideas?</p> <p>Edit : The code I have currently is : </p> <pre> &lt;html xmlns="http://www.w3.org/1999/xhtml" &gt; &lt;head id="Head1" runat="server" /&gt; &lt;frameset rows="10%,65%,25%" border=0 frameborder="no"&gt; &lt;frame name="nav" noresize scrolling="no" src='NavigationBar.aspx?NAVIGATION=&lt;%=sDisplayNavigation %&gt;'&gt; &lt;frameset cols="1*,1010px,1*"&gt; &lt;frame name="lspace" scrolling="no" src="border.htm"&gt; &lt;frame name= "main" scrolling="auto" src='&lt;%=sMainTextURL%&gt;#highlight'&gt; &lt;frame name="rspace" scrolling="no" src="border.htm"&gt; &lt;/frameset&gt; &lt;frame name="suggest" scrolling="yes" noresize src='&lt;%=sSuggestURL%&gt;'&gt; &lt;/frameset&gt; &lt;/html&gt; </pre>
[ { "answer_id": 179403, "author": "Mnebuerquo", "author_id": 5114, "author_profile": "https://Stackoverflow.com/users/5114", "pm_score": 3, "selected": true, "text": "<p>I think what you are looking for is a way to inject some CSS into the other frame, even though it comes from another site.</p>\n\n<p>I think this will not be possible without a server side script to request the page and modify it.</p>\n\n<p>Javascript has ways to modify other frames using window.frames[] and using DOM traversal just like for elements in the local frame. This will be problematic for you because of the \"same-origin policy\". This basically means that javascript in a frame loaded from example.com can not access the DOM in a frame loaded from foo.com. Even if you have similar domains, foo.example.com and bar.example.com, they are treated as separate domains in the browser so your javascript from one is not allowed to access the other.</p>\n\n<p>This affects ajax calls using XMLHttpRequest as well. There are ways of reducing the impact of this, but I think you need to be able to run javascript on both sides of the line.</p>\n\n<p>I recently tried something similar to what you are doing, where I wanted to embed one site in another, but the same-origin policy made it impractical. </p>\n\n<p>The other way to do this is server-side instead of client-side. Create a php script which requests content from the other server on behalf of the client, and then serves it as if it was on your server all along. Then your javascript, now on the same server, can do what it will with that frame. If the other site uses a lot of cookies or ajax, this could be tricky, but your php won't have a same-origin policy to deal with.</p>\n" }, { "answer_id": 73977121, "author": "Christopher M", "author_id": 20177451, "author_profile": "https://Stackoverflow.com/users/20177451", "pm_score": 1, "selected": false, "text": "<p>If you use an absolute value rather than a percentile to define the size of a frame in conjunction with other frames using percentiles the frame with an absolute value will not resize with the browser window and the other frames/divs will.</p>\n<pre><code>&lt;frameset rows=&quot;10%,65,25%&quot; border=0 frameborder=&quot;no&quot;&gt;\n</code></pre>\n<p>OR</p>\n<pre><code>&lt;frameset rows=&quot;10%,65px,25%&quot; border=0 frameborder=&quot;no&quot;&gt;\n</code></pre>\n<p>The first line will use the default unit of measurement and the second line will use units of &quot;pixels&quot;.</p>\n<p>I have a code bit which I have solved this problem with:</p>\n<pre><code>&lt;frameset rows=&quot;36px,80%,36px&quot; frameborder=1 border=3&gt; \n &lt;frame src=&quot;frame1.html&quot; target=&quot;frame2.html&quot; noresize&gt;\n\n &lt;frame name=frame2 src=&quot;index.html&quot;&gt; \n \n &lt;frame src=&quot;frame3.html&quot; target=&quot;frame2.html&quot; noresize&gt; \n&lt;/frameset&gt; \n</code></pre>\n<p>Frame 1 loads data from <code>&quot;frame1.html&quot;</code> and is used for a navigation menu at the top of the screen. Frame 1's unit of measurement is an absolute value of pixels and there for does not resize when the browser window or screen type does and the other frames will. (so far)</p>\n<p>Frame 2 is the center &quot;content&quot; part of the page and does not load any data itself. Frame 2 gets its data inherently using the <code>target=&quot;frame2.html&quot;</code> tags found on the link for the menus in frame 1 and 3.</p>\n<p>for example:</p>\n<pre><code>&lt;a title=&quot;To Homepage&quot; href=&quot;index.html&quot; target=&quot;frame2&quot; &gt;Homepage&lt;/a&gt;&amp;nbsp;\n</code></pre>\n<p>this line when loaded from Frame1.html will reload the home page into frame2.</p>\n<p>also this is a standard web site layout with the menu frame on the left side and applies the prelisted methods.</p>\n<pre><code>&lt;frameset cols=&quot;140px,100%&quot; frameborder=1 border=1&gt; \n &lt;frame src=&quot;frame1.html&quot; target=&quot;frame2.html&quot; noresize&gt;\n &lt;frame name=frame2 src=&quot;index.html&quot;&gt; \n&lt;/frameset&gt; \n</code></pre>\n<p>C-ya</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179288", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21299/" ]
Say I have 3 frames in a frameset arranged in 3 rows. Frames 1 and 3 are from my site and frame 2 (the central one) is from an external website. Is there a cunning way to force the browser to centre align the data in frame 2? I've found a small work-around which uses a frameset within a frameset which has 2 blank columns either side of the data but that means the scrollbars from frames 2 and 3 are out of alignment. Any ideas? Edit : The code I have currently is : ``` <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server" /> <frameset rows="10%,65%,25%" border=0 frameborder="no"> <frame name="nav" noresize scrolling="no" src='NavigationBar.aspx?NAVIGATION=<%=sDisplayNavigation %>'> <frameset cols="1*,1010px,1*"> <frame name="lspace" scrolling="no" src="border.htm"> <frame name= "main" scrolling="auto" src='<%=sMainTextURL%>#highlight'> <frame name="rspace" scrolling="no" src="border.htm"> </frameset> <frame name="suggest" scrolling="yes" noresize src='<%=sSuggestURL%>'> </frameset> </html> ```
I think what you are looking for is a way to inject some CSS into the other frame, even though it comes from another site. I think this will not be possible without a server side script to request the page and modify it. Javascript has ways to modify other frames using window.frames[] and using DOM traversal just like for elements in the local frame. This will be problematic for you because of the "same-origin policy". This basically means that javascript in a frame loaded from example.com can not access the DOM in a frame loaded from foo.com. Even if you have similar domains, foo.example.com and bar.example.com, they are treated as separate domains in the browser so your javascript from one is not allowed to access the other. This affects ajax calls using XMLHttpRequest as well. There are ways of reducing the impact of this, but I think you need to be able to run javascript on both sides of the line. I recently tried something similar to what you are doing, where I wanted to embed one site in another, but the same-origin policy made it impractical. The other way to do this is server-side instead of client-side. Create a php script which requests content from the other server on behalf of the client, and then serves it as if it was on your server all along. Then your javascript, now on the same server, can do what it will with that frame. If the other site uses a lot of cookies or ajax, this could be tricky, but your php won't have a same-origin policy to deal with.
179,291
<p>I'm looking to call a subprocess with a file descriptor opened to a given pipe such that the open() call does not hang waiting for the other side of the pipe to receive a connection.</p> <p>To demonstrate:</p> <pre><code>$ mkfifo /tmp/foobar.pipe $ some_program --command-fd=5 5&lt;/tmp/foobar.pipe </code></pre> <p>In this case, <code>some_program</code> is not run until some process has <code>/tmp/foobar.pipe</code> open for write; however, <code>some_program</code> has useful effects even when it isn't receiving commands, so desired behavior is for <code>some_program</code> to be immediately executed.</p> <p>Mechanisms to do this by exec'ing through an alternate scripting language (python, perl, etc) or a C wrapper which open <code>/tmp/foobar.pipe</code> with the <code>O_NONBLOCK</code> flag are obvious; I'm looking for a pure-bash solution, should one be possible.</p>
[ { "answer_id": 179345, "author": "Sec", "author_id": 20555, "author_profile": "https://Stackoverflow.com/users/20555", "pm_score": 2, "selected": false, "text": "<p>The only way I know getting this kind of result is a hack:</p>\n\n<pre><code>mkfifo /tmp/foobar.in\nmkfifo /tmp/foobar.out\n( cat &lt;/tmp/foobar.in ) &gt;/tmp/foobar.out &amp;\nsome_program --command-fd=5 5&lt;/tmp/foobar.out\n</code></pre>\n\n<p>perhaps this helps :-)</p>\n" }, { "answer_id": 179469, "author": "Charles Duffy", "author_id": 14122, "author_profile": "https://Stackoverflow.com/users/14122", "pm_score": 4, "selected": true, "text": "<p>Opening the FD read/write rather than read-only when setting up the pipeline prevents blocking.</p>\n\n<p>To be a bit more specific:</p>\n\n<pre><code>$ mkfifo /tmp/foobar.pipe\n$ some_program --command-fd=5 5&lt;&gt;/tmp/foobar.pipe\n</code></pre>\n\n<p>prevents the undesired blocking behavior, as <code>5&lt;&gt;/tmp/foobar.pipe</code> opens in RW mode (as opposed to opening in read-only mode as with <code>5&lt;/tmp/foobar.pipe</code>) although <code>O_NONBLOCK</code> is still set. Thanks to waldner on irc://irc.freenode.org/#bash for this pointer.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14122/" ]
I'm looking to call a subprocess with a file descriptor opened to a given pipe such that the open() call does not hang waiting for the other side of the pipe to receive a connection. To demonstrate: ``` $ mkfifo /tmp/foobar.pipe $ some_program --command-fd=5 5</tmp/foobar.pipe ``` In this case, `some_program` is not run until some process has `/tmp/foobar.pipe` open for write; however, `some_program` has useful effects even when it isn't receiving commands, so desired behavior is for `some_program` to be immediately executed. Mechanisms to do this by exec'ing through an alternate scripting language (python, perl, etc) or a C wrapper which open `/tmp/foobar.pipe` with the `O_NONBLOCK` flag are obvious; I'm looking for a pure-bash solution, should one be possible.
Opening the FD read/write rather than read-only when setting up the pipeline prevents blocking. To be a bit more specific: ``` $ mkfifo /tmp/foobar.pipe $ some_program --command-fd=5 5<>/tmp/foobar.pipe ``` prevents the undesired blocking behavior, as `5<>/tmp/foobar.pipe` opens in RW mode (as opposed to opening in read-only mode as with `5</tmp/foobar.pipe`) although `O_NONBLOCK` is still set. Thanks to waldner on irc://irc.freenode.org/#bash for this pointer.
179,299
<p>I'm fairly new at programming, but I've wondered how shell text editors such as vim, emacs, nano, etc are able to control the command-line window. I'm primarily a Windows programmer, so maybe it's different on *nix. As far as I know, it's only possible to print text to a console, and ask for input. How do text editors create a navigable, editable window in a command line environment?</p>
[ { "answer_id": 179301, "author": "EfForEffort", "author_id": 14113, "author_profile": "https://Stackoverflow.com/users/14113", "pm_score": 2, "selected": false, "text": "<p>Learning about <a href=\"http://www.gnu.org/software/ncurses/\" rel=\"nofollow noreferrer\">ncurses</a> might be a good starting point.</p>\n" }, { "answer_id": 179303, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 2, "selected": false, "text": "<p>There is an old protocol called vt100 based on a \"VT100\" terminal. It used codes starting with escape to control cursor position, color, clearing the screen, etc.</p>\n\n<p>It's also how you get colored prompts.</p>\n\n<p>Google VT100 or \"terminal escape codes\"</p>\n\n<p>edit: I Googled it for you: <a href=\"http://www.termsys.demon.co.uk/vtansi.htm\" rel=\"nofollow noreferrer\">http://www.termsys.demon.co.uk/vtansi.htm</a></p>\n" }, { "answer_id": 179307, "author": "Sec", "author_id": 20555, "author_profile": "https://Stackoverflow.com/users/20555", "pm_score": 3, "selected": false, "text": "<p>Short answer: there are libraries for it (like curses, slang).</p>\n\n<p>Longer answer: doing things like jumping around with the cursor or changing colors are done by printing special character sequences (called escape-secquences, because they start with the ESC character).</p>\n" }, { "answer_id": 179318, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": true, "text": "<p>By using libraries such as the following which, in turn, use escape character sequences</p>\n\n<pre>\nNAME\n ncurses - CRT screen handling and optimization package\n\nSYNOPSIS\n #include \n\nDESCRIPTION\n The ncurses library routines give the user a terminal-independent \nmethod of updating character screens with reasonable optimization. This \nimplementation is ‘‘new curses’’ (ncurses) and is the approved replacement \nfor 4.4BSD classic curses, which has been discontinued.\n\n[...snip....]\n\n The ncurses package supports: overall screen, window and pad \nmanipulation; output to windows and pads; reading terminal input; control \nover terminal and curses input and output options; environment query \nroutines; color manipulation; use of soft label keys; terminfo capabilities; \nand access to low-level terminal-manipulation routines.\n\n</pre>\n" }, { "answer_id": 179322, "author": "Chris Young", "author_id": 9417, "author_profile": "https://Stackoverflow.com/users/9417", "pm_score": 2, "selected": false, "text": "<p>You will also notice this if you type \"edit\" in a Windows command line console. This \"feature\" is not unique to unix-like systems, though the concepts for manipulating the windows console in that way are quite different to in unix.</p>\n" }, { "answer_id": 179339, "author": "Brian Knoblauch", "author_id": 15689, "author_profile": "https://Stackoverflow.com/users/15689", "pm_score": 0, "selected": false, "text": "<p>More Windows command line specific, the app typically calls DOS or BIOS functions that do the same. Sometimes ANSI command code support is available, sometimes it isn't (depending on exact MS OS version and whether or not it's configured to load it).</p>\n" }, { "answer_id": 179374, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 2, "selected": false, "text": "<p>On Unix systems, a console window emulates an ancient serial terminal (usually a <a href=\"http://en.wikipedia.org/wiki/Vt100\" rel=\"nofollow noreferrer\">VT100</a>). You can print special control characters and escape sequences to move the cursor around, change colors, and do other special effects. There are libraries to help handle the details; <a href=\"http://www.gnu.org/software/ncurses/\" rel=\"nofollow noreferrer\">ncurses</a> is the most popular.</p>\n\n<p>On Windows, the [Win32 Console API](<a href=\"http://msdn.microsoft.com/en-us/library/ms682073(VS.85%29.aspx)\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms682073(VS.85%29.aspx)</a> provides similar functionality, but in a rather different manner.</p>\n" }, { "answer_id": 179409, "author": "seanyboy", "author_id": 1726, "author_profile": "https://Stackoverflow.com/users/1726", "pm_score": 2, "selected": false, "text": "<p>Type \"c:\\winnt\\system32\\edit\" or \"c:\\windows\\system32\\edit\" at the command line, and you'll be shown a command line text editor. </p>\n\n<p>People are mostly right about the ESC character being used to control the command screen, but some older programs also write characters directly to the memory space used by the Windows Command Line screen. </p>\n\n<p>In order to control the command line window, you used to have to write your own windowing forms, entry box, menus, etc. You'd also have to wrap all that up in a big loop for handling events. </p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25870/" ]
I'm fairly new at programming, but I've wondered how shell text editors such as vim, emacs, nano, etc are able to control the command-line window. I'm primarily a Windows programmer, so maybe it's different on \*nix. As far as I know, it's only possible to print text to a console, and ask for input. How do text editors create a navigable, editable window in a command line environment?
By using libraries such as the following which, in turn, use escape character sequences ``` NAME ncurses - CRT screen handling and optimization package SYNOPSIS #include DESCRIPTION The ncurses library routines give the user a terminal-independent method of updating character screens with reasonable optimization. This implementation is ‘‘new curses’’ (ncurses) and is the approved replacement for 4.4BSD classic curses, which has been discontinued. [...snip....] The ncurses package supports: overall screen, window and pad manipulation; output to windows and pads; reading terminal input; control over terminal and curses input and output options; environment query routines; color manipulation; use of soft label keys; terminfo capabilities; and access to low-level terminal-manipulation routines. ```
179,337
<p>In c#</p> <pre><code>double tmp = 3.0 * 0.05; </code></pre> <p>tmp = 0.15000000000000002</p> <p>This has to do with money. The value is really $0.15, but the system wants to round it up to $0.16. 0.151 should probably be rounded up to 0.16, but not 0.15000000000000002</p> <p>What are some ways I can get the correct numbers (ie 0.15, or 0.16 if the decimal is high enough).</p>
[ { "answer_id": 179346, "author": "AaronSieb", "author_id": 16911, "author_profile": "https://Stackoverflow.com/users/16911", "pm_score": 5, "selected": true, "text": "<p>Use a fixed-point variable type, or a base ten floating point type like Decimal. Floating point numbers are always somewhat inaccurate, and binary floating point representations add another layer of inaccuracy when they convert to/from base two.</p>\n" }, { "answer_id": 179353, "author": "rslite", "author_id": 15682, "author_profile": "https://Stackoverflow.com/users/15682", "pm_score": 0, "selected": false, "text": "<p>'decimal' type was designed especially for this</p>\n" }, { "answer_id": 179364, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 2, "selected": false, "text": "<p>In Patterns of Enterprise Application Architecture, Martin Fowler recommends using a Money abstraction</p>\n\n<p><a href=\"http://martinfowler.com/eaaCatalog/money.html\" rel=\"nofollow noreferrer\">http://martinfowler.com/eaaCatalog/money.html</a></p>\n\n<p>Mostly he does it for dealing with Currency, but also precision.</p>\n\n<p>You can see a little of it in this Google Book search result:</p>\n\n<p><a href=\"http://books.google.com/books?id=FyWZt5DdvFkC&amp;pg=PT520&amp;lpg=PT520&amp;dq=money+martin+fowler&amp;source=web&amp;ots=eEys-C_vdA&amp;sig=jckdxgMLSRJtGDYZtcbYST1ak8M&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=6&amp;ct=result\" rel=\"nofollow noreferrer\">http://books.google.com/books?id=FyWZt5DdvFkC&amp;pg=PT520&amp;lpg=PT520&amp;dq=money+martin+fowler&amp;source=web&amp;ots=eEys-C_vdA&amp;sig=jckdxgMLSRJtGDYZtcbYST1ak8M&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=6&amp;ct=result</a></p>\n" }, { "answer_id": 179392, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "<p>Money should be stored as <code>decimal</code>, which is a <a href=\"http://pobox.com/~skeet/csharp/decimal.html\" rel=\"nofollow noreferrer\">floating decimal point type</a>. The same goes for other data which really is discrete rather than continuous, and which is logically decimal in nature.</p>\n\n<p>Humans have a bias to decimal for obvious reasons, so \"artificial\" quantities such as money tend to be more appropriate in decimal form. \"Natural\" quantities (mass, height) are on a more continuous scale, which means that <code>float</code>/<code>double</code> (which are <a href=\"http://pobox.com/~skeet/csharp/floatingpoint.html\" rel=\"nofollow noreferrer\">floating binary point types</a>) are often (but not always) more appropriate.</p>\n" }, { "answer_id": 179435, "author": "spoulson", "author_id": 3347, "author_profile": "https://Stackoverflow.com/users/3347", "pm_score": 0, "selected": false, "text": "<p>A <code>decimal</code> data type would work well and is probably your choice.</p>\n\n<p>However, in the past I've been able to do this in an optimized way using fixed point integers. It's ideal for high performance computations where <code>decimal</code> bogs down and you can't have the small precision errors of <code>float</code>.</p>\n\n<p>Start with, say an <code>Int32</code>, and split in half. First half is whole number portion, second half is fractional portion. You get 16-bits of signed integer plus 16 bits of fractional precision. e.g. 1.5 as an 16:16 fixed point would be represented as <code>0x00018000</code>. Or, alter the distribution of bits to suit your needs.</p>\n\n<p>Fixed point numbers can generally be added/sub/mul/div like any other integer, with a little bit of work around mul/div to avoid overflows.</p>\n" }, { "answer_id": 181246, "author": "faulty", "author_id": 20007, "author_profile": "https://Stackoverflow.com/users/20007", "pm_score": 0, "selected": false, "text": "<p>What you faced is a rounding problem, which I had mentioned earlier in another post</p>\n\n<p><a href=\"https://stackoverflow.com/questions/151291/can-i-use-systemcurrency-in-net#153410\">Can I use “System.Currency” in .NET? </a></p>\n\n<p>And refer to this as well <a href=\"http://en.wikipedia.org/wiki/Rounding\" rel=\"nofollow noreferrer\">Rounding</a></p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179337", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3800/" ]
In c# ``` double tmp = 3.0 * 0.05; ``` tmp = 0.15000000000000002 This has to do with money. The value is really $0.15, but the system wants to round it up to $0.16. 0.151 should probably be rounded up to 0.16, but not 0.15000000000000002 What are some ways I can get the correct numbers (ie 0.15, or 0.16 if the decimal is high enough).
Use a fixed-point variable type, or a base ten floating point type like Decimal. Floating point numbers are always somewhat inaccurate, and binary floating point representations add another layer of inaccuracy when they convert to/from base two.
179,355
<p>How do you delete all the cookies for the current domain using JavaScript?</p>
[ { "answer_id": 179386, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 4, "selected": false, "text": "<p>As far as I know there's no way to do a blanket delete of any cookie set on the domain. You can clear a cookie if you know the name and if the script is on the same domain as the cookie. </p>\n\n<p>You can set the value to empty and the expiration date to somewhere in the past:</p>\n\n<pre><code>var mydate = new Date();\nmydate.setTime(mydate.getTime() - 1);\ndocument.cookie = \"username=; expires=\" + mydate.toGMTString(); \n</code></pre>\n\n<p>There's an <a href=\"http://www.elated.com/articles/javascript-and-cookies/\" rel=\"noreferrer\">excellent article here</a> on manipulating cookies using javascript.</p>\n" }, { "answer_id": 179408, "author": "Sec", "author_id": 20555, "author_profile": "https://Stackoverflow.com/users/20555", "pm_score": 1, "selected": false, "text": "<p>You can get a list by looking into the document.cookie variable. Clearing them all is just a matter of looping over all of them and clearing them one by one.</p>\n" }, { "answer_id": 179514, "author": "Robert J. Walker", "author_id": 4287, "author_profile": "https://Stackoverflow.com/users/4287", "pm_score": 10, "selected": true, "text": "<pre><code>function deleteAllCookies() {\n var cookies = document.cookie.split(\";\");\n\n for (var i = 0; i &lt; cookies.length; i++) {\n var cookie = cookies[i];\n var eqPos = cookie.indexOf(\"=\");\n var name = eqPos &gt; -1 ? cookie.substr(0, eqPos) : cookie;\n document.cookie = name + \"=;expires=Thu, 01 Jan 1970 00:00:00 GMT\";\n }\n}\n</code></pre>\n\n<p>Note that this code has two limitations:</p>\n\n<ul>\n<li>It will not delete cookies with <code>HttpOnly</code> flag set, as the <code>HttpOnly</code> flag disables Javascript's access to the cookie.</li>\n<li>It will not delete cookies that have been set with a <code>Path</code> value. (This is despite the fact that those cookies will appear in <code>document.cookie</code>, but you can't delete it without specifying the same <code>Path</code> value with which it was set.)</li>\n</ul>\n" }, { "answer_id": 5886746, "author": "AnthonyVO", "author_id": 438458, "author_profile": "https://Stackoverflow.com/users/438458", "pm_score": 6, "selected": false, "text": "<p>After a bit of frustration with this myself I knocked together this function which will attempt to delete a named cookie from all paths. Just call this for each of your cookies and you should be closer to deleting every cookie then you were before.</p>\n\n<pre><code>function eraseCookieFromAllPaths(name) {\n // This function will attempt to remove a cookie from all paths.\n var pathBits = location.pathname.split('/');\n var pathCurrent = ' path=';\n\n // do a simple pathless delete first.\n document.cookie = name + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;';\n\n for (var i = 0; i &lt; pathBits.length; i++) {\n pathCurrent += ((pathCurrent.substr(-1) != '/') ? '/' : '') + pathBits[i];\n document.cookie = name + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT;' + pathCurrent + ';';\n }\n}\n</code></pre>\n\n<p>As always different browsers have different behaviour but this worked for me.\nEnjoy.</p>\n" }, { "answer_id": 17819341, "author": "Zach Shallbetter", "author_id": 520520, "author_profile": "https://Stackoverflow.com/users/520520", "pm_score": 2, "selected": false, "text": "<p>Figured I'd share this method for clearing cookies. Perhaps it may be helpful for someone else at some point.</p>\n\n<pre><code>var cookie = document.cookie.split(';');\n\nfor (var i = 0; i &lt; cookie.length; i++) {\n\n var chip = cookie[i],\n entry = chip.split(\"=\"),\n name = entry[0];\n\n document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;';\n}\n</code></pre>\n" }, { "answer_id": 20115529, "author": "Dinesh", "author_id": 1921517, "author_profile": "https://Stackoverflow.com/users/1921517", "pm_score": 3, "selected": false, "text": "<p>Simpler. Faster.</p>\n\n<pre><code>function deleteAllCookies() {\n var c = document.cookie.split(\"; \");\n for (i in c) \n document.cookie =/^[^=]+/.exec(c[i])[0]+\"=;expires=Thu, 01 Jan 1970 00:00:00 GMT\"; \n}\n</code></pre>\n" }, { "answer_id": 20946944, "author": "jichi", "author_id": 970086, "author_profile": "https://Stackoverflow.com/users/970086", "pm_score": 4, "selected": false, "text": "<p>If you have access to the <a href=\"http://plugins.jquery.com/cookie/\">jquery.cookie</a> plugin, you can erase all cookies this way:</p>\n\n<pre><code>for (var it in $.cookie()) $.removeCookie(it);\n</code></pre>\n" }, { "answer_id": 27374365, "author": "Craig Smedley", "author_id": 2818475, "author_profile": "https://Stackoverflow.com/users/2818475", "pm_score": 8, "selected": false, "text": "<h3>One liner</h3>\n\n<p>In case you want to paste it in quickly...</p>\n\n<pre><code>document.cookie.split(\";\").forEach(function(c) { document.cookie = c.replace(/^ +/, \"\").replace(/=.*/, \"=;expires=\" + new Date().toUTCString() + \";path=/\"); });\n</code></pre>\n\n<p>And the code for a bookmarklet :</p>\n\n<pre><code>javascript:(function(){document.cookie.split(\";\").forEach(function(c) { document.cookie = c.replace(/^ +/, \"\").replace(/=.*/, \"=;expires=\" + new Date().toUTCString() + \";path=/\"); }); })();\n</code></pre>\n" }, { "answer_id": 31985035, "author": "Roman", "author_id": 4791116, "author_profile": "https://Stackoverflow.com/users/4791116", "pm_score": 1, "selected": false, "text": "<pre><code>//Delete all cookies\nfunction deleteAllCookies() {\n var cookies = document.cookie.split(\";\");\n for (var i = 0; i &lt; cookies.length; i++) {\n var cookie = cookies[i];\n var eqPos = cookie.indexOf(\"=\");\n var name = eqPos &gt; -1 ? cookie.substr(0, eqPos) : cookie;\n document.cookie = name + '=;' +\n 'expires=Thu, 01-Jan-1970 00:00:01 GMT;' +\n 'path=' + '/;' +\n 'domain=' + window.location.host + ';' +\n 'secure=;';\n }\n}\n</code></pre>\n" }, { "answer_id": 33366171, "author": "Jan", "author_id": 78639, "author_profile": "https://Stackoverflow.com/users/78639", "pm_score": 7, "selected": false, "text": "<p>And here's one to clear all cookies in all paths and all variants of the domain (<code>www.mydomain.example</code>, <code>mydomain.example</code> etc):</p>\n<pre><code>(function () {\n var cookies = document.cookie.split(&quot;; &quot;);\n for (var c = 0; c &lt; cookies.length; c++) {\n var d = window.location.hostname.split(&quot;.&quot;);\n while (d.length &gt; 0) {\n var cookieBase = encodeURIComponent(cookies[c].split(&quot;;&quot;)[0].split(&quot;=&quot;)[0]) + '=; expires=Thu, 01-Jan-1970 00:00:01 GMT; domain=' + d.join('.') + ' ;path=';\n var p = location.pathname.split('/');\n document.cookie = cookieBase + '/';\n while (p.length &gt; 0) {\n document.cookie = cookieBase + p.join('/');\n p.pop();\n };\n d.shift();\n }\n }\n})();\n</code></pre>\n" }, { "answer_id": 35680201, "author": "Derek Wade", "author_id": 2668852, "author_profile": "https://Stackoverflow.com/users/2668852", "pm_score": -1, "selected": false, "text": "<p>I found a problem in IE and Edge. Webkit browsers (Chrome, safari) seem to be more forgiving. When setting cookies, always set the \"path\" to something, because the default will be the page that set the cookie. So if you try to expire it on a different page without specifying the \"path\", the path won't match and it won't expire. The <code>document.cookie</code> value doesn't show the path or expiration for a cookie, so you can't derive where the cookie was set by looking at the value.</p>\n\n<p>If you need to expire cookies from different pages, save the path of the setting page in the cookie value so you can pull it out later or always append <code>\"; path=/;\"</code> to the cookie value. Then it will expire from any page.</p>\n" }, { "answer_id": 38184148, "author": "Shubham Kumar", "author_id": 4722288, "author_profile": "https://Stackoverflow.com/users/4722288", "pm_score": 2, "selected": false, "text": "<p>Here's a simple code to <a href=\"http://mycodingtricks.com/snippets/javascript/javascript-cookies/#Delete_All_Cookies\" rel=\"nofollow\">delete all cookies in JavaScript</a>.</p>\n\n<pre><code>function deleteAllCookies(){\n var cookies = document.cookie.split(\";\");\n for (var i = 0; i &lt; cookies.length; i++)\n deleteCookie(cookies[i].split(\"=\")[0]);\n}\n\nfunction setCookie(name, value, expirydays) {\n var d = new Date();\n d.setTime(d.getTime() + (expirydays*24*60*60*1000));\n var expires = \"expires=\"+ d.toUTCString();\n document.cookie = name + \"=\" + value + \"; \" + expires;\n}\n\nfunction deleteCookie(name){\n setCookie(name,\"\",-1);\n}\n</code></pre>\n\n<p>Run the function <code>deleteAllCookies()</code> to clear all cookies.</p>\n" }, { "answer_id": 38244351, "author": "Stefano Saitta", "author_id": 4420152, "author_profile": "https://Stackoverflow.com/users/4420152", "pm_score": 1, "selected": false, "text": "<h3>Functional Approach + ES6</h3>\n\n<pre><code>const cookieCleaner = () =&gt; {\n return document.cookie.split(\";\").reduce(function (acc, cookie) {\n const eqPos = cookie.indexOf(\"=\");\n const cleanCookie = `${cookie.substr(0, eqPos)}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;`;\n return `${acc}${cleanCookie}`;\n }, \"\");\n}\n</code></pre>\n\n<blockquote>\n <p>Note: Doesn't handle paths</p>\n</blockquote>\n" }, { "answer_id": 41641134, "author": "SpYk3HH", "author_id": 900807, "author_profile": "https://Stackoverflow.com/users/900807", "pm_score": 0, "selected": false, "text": "<p>After testing almost ever method listed in multiple style of browsers on multiple styles of cookies, I found almost nothing here works even 50%.</p>\n\n<p>Please help correct as needed, but I'm going to throw my 2 cents in here. The following method breaks everything down and basically builds the cookie value string based on both the settings pieces as well as including a step by step build of the path string, starting with <code>/</code> of course.</p>\n\n<p>Hope this helps others and I hope any criticism may come in the form of perfecting this method. At first I wanted a simple 1-liner as some others sought, but JS cookies are one of those things not so easily dealt with.</p>\n\n<pre><code>;(function() {\n if (!window['deleteAllCookies'] &amp;&amp; document['cookie']) {\n window.deleteAllCookies = function(showLog) {\n var arrCookies = document.cookie.split(';'),\n arrPaths = location.pathname.replace(/^\\//, '').split('/'), // remove leading '/' and split any existing paths\n arrTemplate = [ 'expires=Thu, 01-Jan-1970 00:00:01 GMT', 'path={path}', 'domain=' + window.location.host, 'secure=' ]; // array of cookie settings in order tested and found most useful in establishing a \"delete\"\n for (var i in arrCookies) {\n var strCookie = arrCookies[i];\n if (typeof strCookie == 'string' &amp;&amp; strCookie.indexOf('=') &gt;= 0) {\n var strName = strCookie.split('=')[0]; // the cookie name\n for (var j=1;j&lt;=arrTemplate.length;j++) {\n if (document.cookie.indexOf(strName) &lt; 0) break; // if this is true, then the cookie no longer exist\n else {\n var strValue = strName + '=; ' + arrTemplate.slice(0, j).join('; ') + ';'; // made using the temp array of settings, putting it together piece by piece as loop rolls on\n if (j == 1) document.cookie = strValue;\n else {\n for (var k=0;k&lt;=arrPaths.length;k++) {\n if (document.cookie.indexOf(strName) &lt; 0) break; // if this is true, then the cookie no longer exist\n else {\n var strPath = arrPaths.slice(0, k).join('/') + '/'; // builds path line \n strValue = strValue.replace('{path}', strPath);\n document.cookie = strValue;\n }\n }\n }\n }\n }\n }\n }\n showLog &amp;&amp; window['console'] &amp;&amp; console.info &amp;&amp; console.info(\"\\n\\tCookies Have Been Deleted!\\n\\tdocument.cookie = \\\"\" + document.cookie + \"\\\"\\n\");\n return document.cookie;\n }\n }\n})();\n</code></pre>\n" }, { "answer_id": 44164390, "author": "Jacob David C. Cunningham", "author_id": 2710227, "author_profile": "https://Stackoverflow.com/users/2710227", "pm_score": 4, "selected": false, "text": "<p>An answer influenced by both second answer here and W3Schools</p>\n\n<pre><code>document.cookie.split(';').forEach(function(c) {\n document.cookie = c.trim().split('=')[0] + '=;' + 'expires=Thu, 01 Jan 1970 00:00:00 UTC;';\n});\n</code></pre>\n\n<p>Seems to be working</p>\n\n<p>edit: wow almost exactly the same as Zach's interesting how Stack Overflow put them next to each other.</p>\n\n<p>edit: nvm that was temporary apparently</p>\n" }, { "answer_id": 44945595, "author": "sureshvignesh", "author_id": 6856761, "author_profile": "https://Stackoverflow.com/users/6856761", "pm_score": 0, "selected": false, "text": "<p><strong>Jquery:</strong></p>\n\n<pre><code>var cookies = $.cookie();\nfor(var cookie in cookies) {\n$.removeCookie(cookie);\n}\n</code></pre>\n\n<p><strong>vanilla JS</strong></p>\n\n<pre><code>function clearListCookies()\n{ \n var cookies = document.cookie.split(\";\");\n for (var i = 0; i &lt; cookies.length; i++)\n { \n var spcook = cookies[i].split(\"=\");\n deleteCookie(spcook[0]);\n }\n function deleteCookie(cookiename)\n {\n var d = new Date();\n d.setDate(d.getDate() - 1);\n var expires = \";expires=\"+d;\n var name=cookiename;\n //alert(name);\n var value=\"\";\n document.cookie = name + \"=\" + value + expires + \"; path=/acc/html\"; \n}\nwindow.location = \"\"; // TO REFRESH THE PAGE\n}\n</code></pre>\n" }, { "answer_id": 50291342, "author": "Mashiro", "author_id": 8083009, "author_profile": "https://Stackoverflow.com/users/8083009", "pm_score": 3, "selected": false, "text": "<p>I don't know why the first voted answer doesn't work for me.</p>\n\n<p>As <a href=\"https://stackoverflow.com/questions/595228/how-can-i-delete-all-cookies-with-javascript\">this answer</a> said: </p>\n\n<blockquote>\n <p>There is no 100% solution to delete browser cookies.</p>\n \n <p>The problem is that cookies are uniquely identified by not just by their key \"name\" but also their \"domain\" and \"path\".</p>\n \n <p>Without knowing the \"domain\" and \"path\" of a cookie, you cannot reliably delete it. This information is not available through JavaScript's document.cookie. It's not available through the HTTP Cookie header either!</p>\n</blockquote>\n\n<p>So my idea is to add a Cookie version control with the full set of setting, getting, removing of cookies:</p>\n\n<pre><code>var cookie_version_control = '---2018/5/11';\n\nfunction setCookie(name,value,days) {\n var expires = \"\";\n if (days) {\n var date = new Date();\n date.setTime(date.getTime() + (days*24*60*60*1000));\n expires = \"; expires=\" + date.toUTCString();\n }\n document.cookie = name+cookie_version_control + \"=\" + (value || \"\") + expires + \"; path=/\";\n}\n\nfunction getCookie(name) {\n var nameEQ = name+cookie_version_control + \"=\";\n var ca = document.cookie.split(';');\n for(var i=0;i &lt; ca.length;i++) {\n var c = ca[i];\n while (c.charAt(0)==' ') c = c.substring(1,c.length);\n if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);\n }\n return null;\n}\n\nfunction removeCookie(name) { \n document.cookie = name+cookie_version_control+'=; Max-Age=-99999999;'; \n}\n</code></pre>\n" }, { "answer_id": 54947499, "author": "B. Bohdan", "author_id": 8097218, "author_profile": "https://Stackoverflow.com/users/8097218", "pm_score": 2, "selected": false, "text": "<p>I have some more sophisticated and OOP-oriented cookie control module. It also contains <code>deleteAll</code> method to clear all existing cookie. Make notice that this version of <code>deleteAll</code> method has setting <code>path=/</code> that causes deleting of all cookies within current domain. If you need to delete cookies only from some scope you will have to upgrade this method my adding dynamic <code>path</code> parameter to this method.</p>\n\n<p>There is main <code>Cookie</code> class:</p>\n\n<pre><code>import {Setter} from './Setter';\n\nexport class Cookie {\n /**\n * @param {string} key\n * @return {string|undefined}\n */\n static get(key) {\n key = key.replace(/([\\.$?*|{}\\(\\)\\[\\]\\\\\\/\\+^])/g, '\\\\$1');\n\n const regExp = new RegExp('(?:^|; )' + key + '=([^;]*)');\n const matches = document.cookie.match(regExp);\n\n return matches\n ? decodeURIComponent(matches[1])\n : undefined;\n }\n\n /**\n * @param {string} name\n */\n static delete(name) {\n this.set(name, '', { expires: -1 });\n }\n\n static deleteAll() {\n const cookies = document.cookie.split('; ');\n\n for (let cookie of cookies) {\n const index = cookie.indexOf('=');\n\n const name = ~index\n ? cookie.substr(0, index)\n : cookie;\n\n document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/';\n }\n }\n\n /**\n * @param {string} name\n * @param {string|boolean} value\n * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts\n */\n static set(name, value, opts = {}) {\n Setter.set(name, value, opts);\n }\n}\n</code></pre>\n\n<p>Cookie setter method (<code>Cookie.set</code>) is rather complex so I decomposed it into other class. There is code of this one:</p>\n\n<pre><code>export class Setter {\n /**\n * @param {string} name\n * @param {string|boolean} value\n * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts\n */\n static set(name, value, opts = {}) {\n value = Setter.prepareValue(value);\n opts = Setter.prepareOpts(opts);\n\n let updatedCookie = name + '=' + value;\n\n for (let i in opts) {\n if (!opts.hasOwnProperty(i)) continue;\n\n updatedCookie += '; ' + i;\n\n const value = opts[i];\n\n if (value !== true)\n updatedCookie += '=' + value;\n }\n\n document.cookie = updatedCookie;\n }\n\n /**\n * @param {string} value\n * @return {string}\n * @private\n */\n static prepareValue(value) {\n return encodeURIComponent(value);\n }\n\n /**\n * @param {{expires?:Date|string|number,path?:string,domain?:string,secure?:boolean}} opts\n * @private\n */\n static prepareOpts(opts = {}) {\n opts = Object.assign({}, opts);\n\n let {expires} = opts;\n\n if (typeof expires == 'number' &amp;&amp; expires) {\n const date = new Date();\n\n date.setTime(date.getTime() + expires * 1000);\n\n expires = opts.expires = date;\n }\n\n if (expires &amp;&amp; expires.toUTCString)\n opts.expires = expires.toUTCString();\n\n return opts;\n }\n}\n</code></pre>\n" }, { "answer_id": 66412149, "author": "Luis Lobo", "author_id": 11212275, "author_profile": "https://Stackoverflow.com/users/11212275", "pm_score": 1, "selected": false, "text": "<p>Several answers here do not resolve the path question. I believe that: if you control the site, or part of it, you should know all the paths used. So you just have to have it delete all cookies from all paths used.\nBecause my site already has jquery (and out of laziness) I decided to use the jquery cookie, but you can easily adapt it to pure javascript based on the other answers.</p>\n<p>In this example I remove three specific paths that were being used by the ecommerce platform.</p>\n<pre><code>let mainURL = getMainURL().toLowerCase().replace('www.', '').replace('.com.br', '.com'); // i am a brazilian guy\nlet cookies = $.cookie();\nfor(key in cookies){\n // default remove\n $.removeCookie(key, {\n path:'/'\n });\n // remove without www\n $.removeCookie(key, {\n domain: mainURL,\n path: '/'\n });\n // remove with www\n $.removeCookie(key, {\n domain: 'www.' + mainURL,\n path: '/'\n });\n};\n\n// get-main-url.js v1\nfunction getMainURL(url = window.location.href){\n url = url.replace(/.+?\\/\\//, ''); // remove protocol\n url = url.replace(/(\\#|\\?|\\/)(.+)?/, ''); // remove parameters and paths\n // remove subdomain\n if( url.split('.').length === 3 ){\n url = url.split('.');\n url.shift();\n url = url.join('.');\n };\n return url;\n};\n</code></pre>\n<p>I changed the .com site to .com.br because my site is multi domain and multi lingual</p>\n" }, { "answer_id": 66422055, "author": "sampath", "author_id": 10229940, "author_profile": "https://Stackoverflow.com/users/10229940", "pm_score": 3, "selected": false, "text": "<pre><code>document.cookie.split(&quot;;&quot;).forEach(function(c) { \n document.cookie = c.replace(/^ +/, &quot;&quot;).replace(/=.*/, &quot;=;expires=&quot; + new Date().toUTCString() + &quot;;path=/&quot;); \n});\n//clearing local storage\nlocalStorage.clear();\n</code></pre>\n" }, { "answer_id": 66612049, "author": "Tesla", "author_id": 13158114, "author_profile": "https://Stackoverflow.com/users/13158114", "pm_score": 4, "selected": false, "text": "<p>If you are concerned about clearing cookies only on a secured origin you can use the <a href=\"https://wicg.github.io/cookie-store/\" rel=\"noreferrer\">Cookie Store API</a> and it's <a href=\"https://wicg.github.io/cookie-store/#CookieStore-delete\" rel=\"noreferrer\">.delete()</a> method.</p>\n<pre class=\"lang-js prettyprint-override\"><code>cookieStore.getAll().then(cookies =&gt; cookies.forEach(cookie =&gt; {\n console.log('Cookie deleted:', cookie);\n cookieStore.delete(cookie.name);\n}));\n</code></pre>\n<p>Visit the <a href=\"https://caniuse.com/?search=cookiestore\" rel=\"noreferrer\">caniuse.com</a> table for the <a href=\"https://wicg.github.io/cookie-store/\" rel=\"noreferrer\">Cookie Store API</a> to check for <strong>browser support</strong>.</p>\n" }, { "answer_id": 66698063, "author": "Slavik Meltser", "author_id": 1291121, "author_profile": "https://Stackoverflow.com/users/1291121", "pm_score": 4, "selected": false, "text": "<p>The following code will remove all cookies within the current domain and all trailing subdomains (<code>www.some.sub.domain.example</code>, <code>.some.sub.domain.example</code>, <code>.sub.domain.example</code> and so on.).</p>\n<p>A single line vanilla JS version (I think the only one here without the use of <code>cookie.split()</code>):</p>\n<pre class=\"lang-js prettyprint-override\"><code>document.cookie.replace(/(?&lt;=^|;).+?(?=\\=|;|$)/g, name =&gt; location.hostname.split('.').reverse().reduce(domain =&gt; (domain=domain.replace(/^\\.?[^.]+/, ''),document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`,domain), location.hostname));\n</code></pre>\n<p>This is a readable version of this single line:</p>\n<pre class=\"lang-js prettyprint-override\"><code>document.cookie.replace(\n /(?&lt;=^|;).+?(?=\\=|;|$)/g,\n name =&gt; location.hostname\n .split(/\\.(?=[^\\.]+\\.)/)\n .reduceRight((acc, val, i, arr) =&gt; i ? arr[i]='.'+val+acc : (arr[i]='', arr), '')\n .map(domain =&gt; document.cookie=`${name}=;max-age=0;path=/;domain=${domain}`)\n);\n</code></pre>\n" }, { "answer_id": 68085116, "author": "Nemesarial", "author_id": 2186159, "author_profile": "https://Stackoverflow.com/users/2186159", "pm_score": 1, "selected": false, "text": "<p>I'm contributing here because this function will allow you to delete all cookies (matching the path, by default no-path or <code>\\</code>) <strong>also cookies that were set to be included on subdomains</strong></p>\n<pre><code>function clearCookies( wildcardDomain=false, primaryDomain=true, path=null ){\n pathSegment = path ? '; path=' + path : ''\n expSegment = &quot;=;expires=Thu, 01 Jan 1970 00:00:00 GMT&quot;\n document.cookie.split(';').forEach(\n function(c) { \n primaryDomain &amp;&amp; (document.cookie = c.replace(/^ +/, &quot;&quot;).replace(/=.*/, expSegment + pathSegment))\n wildcardDomain &amp;&amp; (document.cookie = c.replace(/^ +/, &quot;&quot;).replace(/=.*/, expSegment + pathSegment + '; domain=' + document.domain))\n }\n )\n} \n</code></pre>\n" }, { "answer_id": 70360538, "author": "Anton Starcev", "author_id": 4579414, "author_profile": "https://Stackoverflow.com/users/4579414", "pm_score": 0, "selected": false, "text": "<p>If you'd like to use <code>js-cookie</code> npm package and remove cookies by name:</p>\n<pre><code>import cookie from 'js-cookie'\n\nexport const removeAllCookiesByName = (cookieName: string) =&gt; {\n const hostParts = location.host.split('.')\n const domains = hostParts.reduce(\n (acc: string[], current, index) =&gt; [\n ...acc,\n hostParts.slice(index).join('.'),\n ],\n []\n )\n domains.forEach((domain) =&gt; cookie.remove(cookieName, { domain }))\n}\n\n</code></pre>\n" }, { "answer_id": 73315500, "author": "PYK", "author_id": 3233722, "author_profile": "https://Stackoverflow.com/users/3233722", "pm_score": 0, "selected": false, "text": "<p>We can do it like so:</p>\n<pre><code>deleteAllCookies=()=&gt;\n {\n let c=document.cookie.split(';')\n for(const k of c)\n {\n let s=k.split('=')\n document.cookie=s[0].trim()+'=;expires=Fri, 20 Aug 2021 00:00:00 UTC'\n }\n }\n</code></pre>\n<p>Usage:</p>\n<pre><code>deleteAllCookies()\n</code></pre>\n<ul>\n<li>the expiration date was a random day prior to this answer; it can be any date before the current day</li>\n<li>In JS you cannot read through cookies based on path</li>\n<li>In JS you can only set or get cookies</li>\n</ul>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3636/" ]
How do you delete all the cookies for the current domain using JavaScript?
``` function deleteAllCookies() { var cookies = document.cookie.split(";"); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i]; var eqPos = cookie.indexOf("="); var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie; document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT"; } } ``` Note that this code has two limitations: * It will not delete cookies with `HttpOnly` flag set, as the `HttpOnly` flag disables Javascript's access to the cookie. * It will not delete cookies that have been set with a `Path` value. (This is despite the fact that those cookies will appear in `document.cookie`, but you can't delete it without specifying the same `Path` value with which it was set.)
179,365
<p>I am trying this:</p> <pre><code>Provider=MSDASQL.1;Persist Security Info=False;User ID=sys;Password=pwd;Initial Catalog=DATABASE;Data Source=OdbcDataSource;DBA Privilege=SYSDBA </code></pre> <p>But I get the error:</p> <pre><code>[Microsoft][ODBC Driver Manager] Driver's SQLSetConnectAttr failed </code></pre> <p>I'm using Delphi, but answers in any language are welcome.</p> <p><strong><em>Clarification: I am able to connect as a normal user. I run into trouble when I try to connect AS SYSDBA.</em></strong></p>
[ { "answer_id": 179383, "author": "Matt R", "author_id": 4298, "author_profile": "https://Stackoverflow.com/users/4298", "pm_score": 1, "selected": false, "text": "<p>I'm not sure what you mean by connecting as a SYS, but there here is a link to sweet repository of <a href=\"http://www.connectionstrings.com\" rel=\"nofollow noreferrer\">connection strings</a>. I hope you can find your answer there.</p>\n" }, { "answer_id": 179416, "author": "David Basarab", "author_id": 2469, "author_profile": "https://Stackoverflow.com/users/2469", "pm_score": 0, "selected": false, "text": "<p>Oracle Connection string sample</p>\n\n<p>You must have your Oracle SID defined in your TNSNames file. Which is the data source.</p>\n\n<pre><code>Data Source=oracl;User Id=userID;Password=password;Integrated Security=no\n</code></pre>\n\n<p>If you are using Visual Studios you can add a data source in the Sever Explore and it will give you the connection string.</p>\n" }, { "answer_id": 190035, "author": "Salamander2007", "author_id": 10629, "author_profile": "https://Stackoverflow.com/users/10629", "pm_score": 3, "selected": true, "text": "<p>You can't connect as SYSDBA using standard System.Data.OracleClient, as stated by this post : <a href=\"http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2245591&amp;SiteID=1\" rel=\"nofollow noreferrer\">http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2245591&amp;SiteID=1</a>.</p>\n\n<p>You can do that using ODP .NET (Oracle Data Provider for .NET), or other third parties library. If you're planning to build serious Oracle Application on .NET, I suggest you at least look at ODP.NET</p>\n" }, { "answer_id": 61949624, "author": "ListenToBob", "author_id": 13575047, "author_profile": "https://Stackoverflow.com/users/13575047", "pm_score": 1, "selected": false, "text": "<p>Posting the answer here as this is the top result when looking for an answer for DBA PRIVILEGE connection string</p>\n\n<pre><code>Data Source=(DESCRIPTION =(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = ORCL))); User ID=sys; Password=syspassword; DBA PRIVILEGE=SYSDBA\n</code></pre>\n" }, { "answer_id": 71669169, "author": "M.Hassan", "author_id": 3142139, "author_profile": "https://Stackoverflow.com/users/3142139", "pm_score": 1, "selected": false, "text": "<p>using <a href=\"https://www.nuget.org/packages/oracle.manageddataaccess/\" rel=\"nofollow noreferrer\">Oracle.ManagedDataAccess</a>,\nthe connection string for sys as sysdba is:</p>\n<pre><code>Data Source=myOracleDB;User Id=SYS;Password=SYS;DBA Privilege=SYSDBA;\n</code></pre>\n<p><a href=\"https://www.connectionstrings.com/net-framework-data-provider-for-oracle/privileged-connection-sysdba/\" rel=\"nofollow noreferrer\">ref</a></p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
I am trying this: ``` Provider=MSDASQL.1;Persist Security Info=False;User ID=sys;Password=pwd;Initial Catalog=DATABASE;Data Source=OdbcDataSource;DBA Privilege=SYSDBA ``` But I get the error: ``` [Microsoft][ODBC Driver Manager] Driver's SQLSetConnectAttr failed ``` I'm using Delphi, but answers in any language are welcome. ***Clarification: I am able to connect as a normal user. I run into trouble when I try to connect AS SYSDBA.***
You can't connect as SYSDBA using standard System.Data.OracleClient, as stated by this post : <http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2245591&SiteID=1>. You can do that using ODP .NET (Oracle Data Provider for .NET), or other third parties library. If you're planning to build serious Oracle Application on .NET, I suggest you at least look at ODP.NET
179,369
<p>I have a simple Python script that I want to stop executing if a condition is met.</p> <p>For example:</p> <pre><code>done = True if done: # quit/stop/exit else: # do other stuff </code></pre> <p>Essentially, I am looking for something that behaves equivalently to the 'return' keyword in the body of a function which allows the flow of the code to exit the function and not execute the remaining code.</p>
[ { "answer_id": 179375, "author": "Sec", "author_id": 20555, "author_profile": "https://Stackoverflow.com/users/20555", "pm_score": 2, "selected": false, "text": "<p>exit() should do the trick</p>\n" }, { "answer_id": 179376, "author": "Dana", "author_id": 7856, "author_profile": "https://Stackoverflow.com/users/7856", "pm_score": 2, "selected": false, "text": "<p>exit() should do it.</p>\n" }, { "answer_id": 179385, "author": "André", "author_id": 9683, "author_profile": "https://Stackoverflow.com/users/9683", "pm_score": 2, "selected": false, "text": "<p>If the entire program should stop use sys.exit() otherwise just use an empty return.</p>\n" }, { "answer_id": 179387, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 4, "selected": false, "text": "<pre><code>import sys\nsys.exit()\n</code></pre>\n" }, { "answer_id": 179516, "author": "David Locke", "author_id": 1447, "author_profile": "https://Stackoverflow.com/users/1447", "pm_score": 4, "selected": false, "text": "<p>You could put the body of your script into a function and then you could return from that function.</p>\n\n<pre><code>def main():\n done = True\n if done:\n return\n # quit/stop/exit\n else:\n # do other stuff\n\nif __name__ == \"__main__\":\n #Run as main program\n main()\n</code></pre>\n" }, { "answer_id": 179608, "author": "ryan_s", "author_id": 13728, "author_profile": "https://Stackoverflow.com/users/13728", "pm_score": 9, "selected": true, "text": "<p>To exit a script you can use,</p>\n\n<pre><code>import sys\nsys.exit()\n</code></pre>\n\n<p>You can also provide an exit status value, usually an integer.</p>\n\n<pre><code>import sys\nsys.exit(0)\n</code></pre>\n\n<p>Exits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero.</p>\n\n<pre><code>import sys\nsys.exit(\"aa! errors!\")\n</code></pre>\n\n<p>Prints \"aa! errors!\" and exits with a status code of 1.</p>\n\n<p>There is also an _exit() function in the os module. The <a href=\"http://docs.python.org/2/library/sys.html#sys.exit\" rel=\"noreferrer\">sys.exit()</a> function raises a SystemExit exception to exit the program, so try statements and cleanup code can execute. The os._exit() version doesn't do this. It just ends the program without doing any cleanup or flushing output buffers, so it shouldn't normally be used. </p>\n\n<p>The <a href=\"http://docs.python.org/2/library/os.html#os._exit\" rel=\"noreferrer\">Python docs</a> indicate that os._exit() is the normal way to end a child process created with a call to os.fork(), so it does have a use in certain circumstances.</p>\n" }, { "answer_id": 179689, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 4, "selected": false, "text": "<p>You can either use:</p>\n\n<pre><code>import sys\nsys.exit(...)\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>raise SystemExit(...)\n</code></pre>\n\n<p>The optional parameter can be an exit code or an error message. Both methods are identical. I used to prefer sys.exit, but I've lately switched to raising SystemExit, because it seems to stand out better among the rest of the code (due to the <strong>raise</strong> keyword).</p>\n" }, { "answer_id": 2139017, "author": "GabrieleV", "author_id": 188694, "author_profile": "https://Stackoverflow.com/users/188694", "pm_score": 3, "selected": false, "text": "<p>Try</p>\n\n<pre><code>sys.exit(\"message\")\n</code></pre>\n\n<p>It is like the perl</p>\n\n<pre><code>die(\"message\")\n</code></pre>\n\n<p>if this is what you are looking for. It terminates the execution of the script even it is called from an imported module / def /function</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
I have a simple Python script that I want to stop executing if a condition is met. For example: ``` done = True if done: # quit/stop/exit else: # do other stuff ``` Essentially, I am looking for something that behaves equivalently to the 'return' keyword in the body of a function which allows the flow of the code to exit the function and not execute the remaining code.
To exit a script you can use, ``` import sys sys.exit() ``` You can also provide an exit status value, usually an integer. ``` import sys sys.exit(0) ``` Exits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero. ``` import sys sys.exit("aa! errors!") ``` Prints "aa! errors!" and exits with a status code of 1. There is also an \_exit() function in the os module. The [sys.exit()](http://docs.python.org/2/library/sys.html#sys.exit) function raises a SystemExit exception to exit the program, so try statements and cleanup code can execute. The os.\_exit() version doesn't do this. It just ends the program without doing any cleanup or flushing output buffers, so it shouldn't normally be used. The [Python docs](http://docs.python.org/2/library/os.html#os._exit) indicate that os.\_exit() is the normal way to end a child process created with a call to os.fork(), so it does have a use in certain circumstances.
179,405
<p>Can anyone explain what this mod_rewrite rule is doing?</p> <p>I'm trying to comment the file, but the code seems to state the opposite of what I think it's doing</p> <pre><code># Enable rewriting of URLs RewriteEngine on # Allow specified file types to be accessed # Thing to test = URL # Condition = not starting with RewriteCond $1 !^(index\.php|images|css|js|robots\.txt) # RewriteRule will only be performed if the preceeding RewriteCond is fulfilled # Remove index.php from all URLs # Pattern = anything (0 or more of any character) # Substitution = index.php + the rest of the URL RewriteRule ^(.*)$ /index.php/$1 [L] </code></pre>
[ { "answer_id": 179413, "author": "Sec", "author_id": 20555, "author_profile": "https://Stackoverflow.com/users/20555", "pm_score": 2, "selected": false, "text": "<p>If the URL does not start with index.php or images or css or js or robots.txt, the string \"/index.php/\" is prefixed.</p>\n\n<p>As index.php is probably an executable php app, the index.php then can read the rest of the URL from its cgi environment. (it is stored in ${PATH_INFO})</p>\n" }, { "answer_id": 179419, "author": "Roel", "author_id": 11449, "author_profile": "https://Stackoverflow.com/users/11449", "pm_score": 3, "selected": true, "text": "<pre><code>^ = begin of line\n( = begin group\n.* = any character, any number of times\n) = end group\n</code></pre>\n\n<p>The $1 in the second part is replaced by the group in the first part.</p>\n\n<p>Is this a Symfony rule? The idea is to pass the whole query string to the index.php (the front controller) as a parameter, so that the front controller can parse and route it.</p>\n" }, { "answer_id": 179493, "author": "Roel", "author_id": 11449, "author_profile": "https://Stackoverflow.com/users/11449", "pm_score": 3, "selected": false, "text": "<p>The browser sends a request to the server (Apache, since you're using mod_rewrite):</p>\n\n<p>GET profile/edit</p>\n\n<p>Apache accepts this request and sees in its configuration files that you've configured it to pass all requests through mod_rewrite. So, it sends the string 'profile/edit' to mod_rewrite. Mod_rewrite then applies the rules you specified to it, which then transforms the request (in the way I explained in my previous post) to 'index.php/profile/edit'. After mod_rewrite is done, Apache continues processing the request, and sees 'oh, this guy is requesting the file index.php'. So it calls the php interpreter which then parses and executes index.php - and gets '/profile/edit' as arguments. The php code (CI in your case) parses these arguments and knows how to call the right module in your application.</p>\n\n<p>So basically, it's a way to always call index.php, even when the url doesn't specify index.php. In that way, index.php works as the front controller: it routes all requests to the right location in your application.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4196/" ]
Can anyone explain what this mod\_rewrite rule is doing? I'm trying to comment the file, but the code seems to state the opposite of what I think it's doing ``` # Enable rewriting of URLs RewriteEngine on # Allow specified file types to be accessed # Thing to test = URL # Condition = not starting with RewriteCond $1 !^(index\.php|images|css|js|robots\.txt) # RewriteRule will only be performed if the preceeding RewriteCond is fulfilled # Remove index.php from all URLs # Pattern = anything (0 or more of any character) # Substitution = index.php + the rest of the URL RewriteRule ^(.*)$ /index.php/$1 [L] ```
``` ^ = begin of line ( = begin group .* = any character, any number of times ) = end group ``` The $1 in the second part is replaced by the group in the first part. Is this a Symfony rule? The idea is to pass the whole query string to the index.php (the front controller) as a parameter, so that the front controller can parse and route it.
179,427
<p>Seems like the subtraction is triggering some kind of issue and the resulting value is wrong.</p> <pre><code>double tempCommission = targetPremium.doubleValue()*rate.doubleValue()/100d; </code></pre> <p>78.75 = 787.5 * 10.0/100d</p> <pre><code>double netToCompany = targetPremium.doubleValue() - tempCommission; </code></pre> <p>708.75 = 787.5 - 78.75</p> <pre><code>double dCommission = request.getPremium().doubleValue() - netToCompany; </code></pre> <p>877.8499999999999 = 1586.6 - 708.75</p> <p>The resulting expected value would be 877.85.</p> <p>What should be done to ensure the correct calculation?</p>
[ { "answer_id": 179437, "author": "Adam Bellaire", "author_id": 21632, "author_profile": "https://Stackoverflow.com/users/21632", "pm_score": 2, "selected": false, "text": "<p>See responses to <a href=\"https://stackoverflow.com/questions/178952/adding-floats-with-gmp-gives-correct-results-sort-of\">this question</a>. Essentially what you are seeing is a natural consequence of using floating point arithmetic.</p>\n\n<p>You could pick some arbitrary precision (significant digits of your inputs?) and round your result to it, if you feel comfortable doing that. </p>\n" }, { "answer_id": 179442, "author": "Steve Klabnik", "author_id": 24817, "author_profile": "https://Stackoverflow.com/users/24817", "pm_score": 3, "selected": false, "text": "<p>Any time you do calculations with doubles, this can happen. This code would give you 877.85:</p>\n\n<p>double answer = Math.round(dCommission * 100000) / 100000.0;</p>\n" }, { "answer_id": 179453, "author": "Eric Weilnau", "author_id": 13342, "author_profile": "https://Stackoverflow.com/users/13342", "pm_score": 8, "selected": true, "text": "<p>To control the precision of floating point arithmetic, you should use <a href=\"http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html\" rel=\"noreferrer\">java.math.BigDecimal</a>. Read <a href=\"https://blogs.oracle.com/CoreJavaTechTips/entry/the_need_for_bigdecimal\" rel=\"noreferrer\">The need for BigDecimal</a> by John Zukowski for more information.</p>\n\n<p>Given your example, the last line would be as following using BigDecimal.</p>\n\n<pre><code>import java.math.BigDecimal;\n\nBigDecimal premium = BigDecimal.valueOf(\"1586.6\");\nBigDecimal netToCompany = BigDecimal.valueOf(\"708.75\");\nBigDecimal commission = premium.subtract(netToCompany);\nSystem.out.println(commission + \" = \" + premium + \" - \" + netToCompany);\n</code></pre>\n\n<p>This results in the following output.</p>\n\n<pre><code>877.85 = 1586.6 - 708.75\n</code></pre>\n" }, { "answer_id": 179455, "author": "tloach", "author_id": 14092, "author_profile": "https://Stackoverflow.com/users/14092", "pm_score": 2, "selected": false, "text": "<p>Save the number of cents rather than dollars, and just do the format to dollars when you output it. That way you can use an integer which doesn't suffer from the precision issues.</p>\n" }, { "answer_id": 179474, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 3, "selected": false, "text": "<p>Another example:</p>\n\n<pre><code>double d = 0;\nfor (int i = 1; i &lt;= 10; i++) {\n d += 0.1;\n}\nSystem.out.println(d); // prints 0.9999999999999999 not 1.0\n</code></pre>\n\n<p>Use BigDecimal instead.</p>\n\n<p>EDIT:</p>\n\n<p>Also, just to point out this isn't a 'Java' rounding issue. Other languages exhibit \nsimilar (though not necessarily consistent) behaviour. Java at least guarantees consistent behaviour in this regard.</p>\n" }, { "answer_id": 179487, "author": "Johann Zacharee", "author_id": 24290, "author_profile": "https://Stackoverflow.com/users/24290", "pm_score": 6, "selected": false, "text": "<p>As the previous answers stated, this is a consequence of doing floating point arithmetic.</p>\n\n<p>As a previous poster suggested, When you are doing numeric calculations, use <code>java.math.BigDecimal</code>.</p>\n\n<p>However, there is a gotcha to using <code>BigDecimal</code>. When you are converting from the double value to a <code>BigDecimal</code>, you have a choice of using a new <code>BigDecimal(double)</code> constructor or the <code>BigDecimal.valueOf(double)</code> static factory method. Use the static factory method.</p>\n\n<p>The double constructor converts the entire precision of the <code>double</code> to a <code>BigDecimal</code> while the static factory effectively converts it to a <code>String</code>, then converts that to a <code>BigDecimal</code>.</p>\n\n<p>This becomes relevant when you are running into those subtle rounding errors. A number might display as .585, but internally its value is '0.58499999999999996447286321199499070644378662109375'. If you used the <code>BigDecimal</code> constructor, you would get the number that is NOT equal to 0.585, while the static method would give you a value equal to 0.585.</p>\n\n<pre>\ndouble value = 0.585;\nSystem.out.println(new BigDecimal(value));\nSystem.out.println(BigDecimal.valueOf(value));\n</pre>\n\n<p>on my system gives</p>\n\n<pre>\n0.58499999999999996447286321199499070644378662109375\n0.585\n</pre>\n" }, { "answer_id": 808959, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I would modify the example above as follows:</p>\n\n<pre><code>import java.math.BigDecimal;\n\nBigDecimal premium = new BigDecimal(\"1586.6\");\nBigDecimal netToCompany = new BigDecimal(\"708.75\");\nBigDecimal commission = premium.subtract(netToCompany);\nSystem.out.println(commission + \" = \" + premium + \" - \" + netToCompany);\n</code></pre>\n\n<p>This way you avoid the pitfalls of using string to begin with.\nAnother alternative:</p>\n\n<pre><code>import java.math.BigDecimal;\n\nBigDecimal premium = BigDecimal.valueOf(158660, 2);\nBigDecimal netToCompany = BigDecimal.valueOf(70875, 2);\nBigDecimal commission = premium.subtract(netToCompany);\nSystem.out.println(commission + \" = \" + premium + \" - \" + netToCompany);\n</code></pre>\n\n<p>I think these options are better than using doubles. In webapps numbers start out as strings anyways.</p>\n" }, { "answer_id": 1018367, "author": "Roman Kagan", "author_id": 117802, "author_profile": "https://Stackoverflow.com/users/117802", "pm_score": 2, "selected": false, "text": "<p>So far the most elegant and most efficient way to do that in Java: </p>\n\n<pre><code>double newNum = Math.floor(num * 100 + 0.5) / 100;\n</code></pre>\n" }, { "answer_id": 1629282, "author": "Denis", "author_id": 197133, "author_profile": "https://Stackoverflow.com/users/197133", "pm_score": 1, "selected": false, "text": "<pre><code>double rounded = Math.rint(toround * 100) / 100;\n</code></pre>\n" }, { "answer_id": 8326785, "author": "Timon", "author_id": 1073447, "author_profile": "https://Stackoverflow.com/users/1073447", "pm_score": -1, "selected": false, "text": "<p>Although you should not use doubles for precise calculations the following trick helped me if you are rounding the results anyway. </p>\n\n<pre><code>public static int round(Double i) {\n return (int) Math.round(i + ((i &gt; 0.0) ? 0.00000001 : -0.00000001));\n}\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code> Double foo = 0.0;\n for (int i = 1; i &lt;= 150; i++) {\n foo += 0.00010;\n }\n System.out.println(foo);\n System.out.println(Math.round(foo * 100.0) / 100.0);\n System.out.println(round(foo*100.0) / 100.0);\n</code></pre>\n\n<p>Which prints:</p>\n\n<pre><code>0.014999999999999965\n0.01\n0.02\n</code></pre>\n\n<p>More info: <a href=\"http://en.wikipedia.org/wiki/Double_precision\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Double_precision</a></p>\n" }, { "answer_id": 9656080, "author": "Mike Stratton", "author_id": 1262427, "author_profile": "https://Stackoverflow.com/users/1262427", "pm_score": -1, "selected": false, "text": "<p>It's quite simple.</p>\n\n<p>Use the %.2f operator for output. Problem solved!</p>\n\n<p>For example:</p>\n\n<pre><code>int a = 877.8499999999999;\nSystem.out.printf(\"Formatted Output is: %.2f\", a);\n</code></pre>\n\n<p>The above code results in a print output of:\n877.85</p>\n\n<p>The %.2f operator defines that only TWO decimal places should be used.</p>\n" }, { "answer_id": 10028960, "author": "Doug", "author_id": 381448, "author_profile": "https://Stackoverflow.com/users/381448", "pm_score": 2, "selected": false, "text": "<p>This is a fun issue.</p>\n\n<p>The idea behind Timons reply is you specify an epsilon which represents the smallest precision a legal double can be. If you know in your application that you will never need precision below 0.00000001 then what he suggests is sufficient to get a more precise result very close to the truth. Useful in applications where they know up front their maximum precision (for in instance finance for currency precisions, etc)</p>\n\n<p>However the fundamental problem with trying to round it off is that when you divide by a factor to rescale it you actually introduce another possibility for precision problems. Any manipulation of doubles can introduce imprecision problems with varying frequency. Especially if you're trying to round at a very significant digit (so your operands are &lt; 0) for instance if you run the following with Timons code:</p>\n\n<pre><code>System.out.println(round((1515476.0) * 0.00001) / 0.00001);\n</code></pre>\n\n<p>Will result in <code>1499999.9999999998</code> where the goal here is to round at the units of 500000 (i.e we want 1500000)</p>\n\n<p>In fact the only way to be completely sure you've eliminated the imprecision is to go through a BigDecimal to scale off. e.g.</p>\n\n<pre><code>System.out.println(BigDecimal.valueOf(1515476.0).setScale(-5, RoundingMode.HALF_UP).doubleValue());\n</code></pre>\n\n<p>Using a mix of the epsilon strategy and the BigDecimal strategy will give you fine control over your precision. The idea being the epsilon gets you very close and then the BigDecimal will eliminate any imprecision caused by rescaling afterwards. Though using BigDecimal will reduce the expected performance of your application.</p>\n\n<p>It has been pointed out to me that the final step of using BigDecimal to rescale it isn't always necessary for some uses cases when you can determine that there's no input value that the final division can reintroduce an error. Currently I don't know how to properly determine this so if anyone knows how then I'd be delighted to hear about it.</p>\n" }, { "answer_id": 16248507, "author": "Tomasz", "author_id": 10523, "author_profile": "https://Stackoverflow.com/users/10523", "pm_score": 2, "selected": false, "text": "<p>Better yet use <a href=\"http://jscience.org/api/overview-summary.html#TUTORIAL\" rel=\"nofollow\">JScience</a> as BigDecimal is fairly limited (e.g., no sqrt function)</p>\n\n<pre><code>double dCommission = 1586.6 - 708.75;\nSystem.out.println(dCommission);\n&gt; 877.8499999999999\n\nReal dCommissionR = Real.valueOf(1586.6 - 708.75);\nSystem.out.println(dCommissionR);\n&gt; 877.850000000000\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25881/" ]
Seems like the subtraction is triggering some kind of issue and the resulting value is wrong. ``` double tempCommission = targetPremium.doubleValue()*rate.doubleValue()/100d; ``` 78.75 = 787.5 \* 10.0/100d ``` double netToCompany = targetPremium.doubleValue() - tempCommission; ``` 708.75 = 787.5 - 78.75 ``` double dCommission = request.getPremium().doubleValue() - netToCompany; ``` 877.8499999999999 = 1586.6 - 708.75 The resulting expected value would be 877.85. What should be done to ensure the correct calculation?
To control the precision of floating point arithmetic, you should use [java.math.BigDecimal](http://java.sun.com/javase/6/docs/api/java/math/BigDecimal.html). Read [The need for BigDecimal](https://blogs.oracle.com/CoreJavaTechTips/entry/the_need_for_bigdecimal) by John Zukowski for more information. Given your example, the last line would be as following using BigDecimal. ``` import java.math.BigDecimal; BigDecimal premium = BigDecimal.valueOf("1586.6"); BigDecimal netToCompany = BigDecimal.valueOf("708.75"); BigDecimal commission = premium.subtract(netToCompany); System.out.println(commission + " = " + premium + " - " + netToCompany); ``` This results in the following output. ``` 877.85 = 1586.6 - 708.75 ```
179,439
<p>I checked out a project from SVN and did not specify the project type, so it checked out as a "default" project. What is the easiest way to quickly convert this into a "Java" project?</p> <p>I'm using Eclipse version 3.3.2.</p>
[ { "answer_id": 179450, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 8, "selected": true, "text": "<p>Open the .project file and add java nature and builders.</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;projectDescription&gt;\n &lt;buildSpec&gt;\n &lt;buildCommand&gt;\n &lt;name&gt;org.eclipse.jdt.core.javabuilder&lt;/name&gt;\n &lt;arguments&gt;\n &lt;/arguments&gt;\n &lt;/buildCommand&gt;\n &lt;/buildSpec&gt;\n &lt;natures&gt;\n &lt;nature&gt;org.eclipse.jdt.core.javanature&lt;/nature&gt;\n &lt;/natures&gt;\n&lt;/projectDescription&gt;\n</code></pre>\n\n<p>And in .classpath, reference the Java libs:</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code>&lt;classpath&gt;\n &lt;classpathentry kind=\"con\" path=\"org.eclipse.jdt.launching.JRE_CONTAINER\"/&gt;\n&lt;/classpath&gt;\n</code></pre>\n" }, { "answer_id": 179497, "author": "Joe Dean", "author_id": 5917, "author_profile": "https://Stackoverflow.com/users/5917", "pm_score": 5, "selected": false, "text": "<p>I deleted the project without removing content. I then created a new Java project from an existing resource. Pointing at my SVN checkout root folder. This worked for me. Although, Chris' way would have been much quicker. That's good to note for future. Thanks! </p>\n" }, { "answer_id": 1738009, "author": "Chris J", "author_id": 165119, "author_profile": "https://Stackoverflow.com/users/165119", "pm_score": 4, "selected": false, "text": "<p>Joe's approach is actually the most effective means that I have found for doing this conversation. To elaborate a little bit more on it, you should right click on the project in the package explorer in eclipse and then select to delete it without removing directory or its contents. Next, you select to create a Java project (File -> New -> Java Project) and in the Contents part of the New Java Project dialog box, select 'Create project from existing source'.</p>\n\n<p>The advantage this approach is that source folders will be properly identified. I found that mucking around with the .project file can lead to the entire directory being considered a source folder which is not what you want.</p>\n" }, { "answer_id": 3354109, "author": "Lorenzo", "author_id": 339509, "author_profile": "https://Stackoverflow.com/users/339509", "pm_score": 7, "selected": false, "text": "<p>Manually changing XML and/or settings is very dangerous in eclipse unless you know exactly what you're doing. In the other case you might end up finding your complete project is screwed. Taking a backup is very recommended!</p>\n\n<p>How to do it just using Eclipse?</p>\n\n<ol>\n<li>Select project.</li>\n<li>Open the project properties through Project -> Properties.</li>\n<li>Go to \"Targetted Runtimes\" and add the proper runtime. Click APPLY.</li>\n<li>Go to \"Project Facets\" and select the JAVA facet which has appeared due to step 4. Click APPLY</li>\n<li>Set your build path.</li>\n<li>If it's a Maven project, you might want to select the project, click Maven -> Update Project configuration...</li>\n</ol>\n\n<p>That did it for me. And Eclipse is configured correctly. Hope it'll work for you too.</p>\n" }, { "answer_id": 13629747, "author": "Victor Grazi", "author_id": 522729, "author_profile": "https://Stackoverflow.com/users/522729", "pm_score": 6, "selected": false, "text": "<p>In recent versions of eclipse the fix is slightly different...</p>\n\n<ol>\n<li>Right click and select Project Properties</li>\n<li>Select Project Facets</li>\n<li>If necessary, click \"Convert to faceted form\"</li>\n<li>Select \"Java\" facet</li>\n<li>Click OK</li>\n</ol>\n" }, { "answer_id": 13750958, "author": "drumherum", "author_id": 33343, "author_profile": "https://Stackoverflow.com/users/33343", "pm_score": 3, "selected": false, "text": "<p>You can do it directly from eclipse using the Navigator view (Window -> Show View -> Navigator). In the Navigator view select the project and open it so that you can see the file <code>.project</code>. Right click -> Open. You will get a XML editor view. Edit the content of the node <code>natures</code> and insert a new child <code>nature</code> with <code>org.eclipse.jdt.core.javanature</code> as content. Save.</p>\n\n<p>Now create a file <code>.classpath</code>, it will open in the XML editor. Add a node named <code>classpath</code>, add a child named <code>classpathentry</code> with the attributes <code>kind</code> with content <code>con</code> and another one named <code>path</code> and content <code>org.eclipse.jdt.launching.JRE_CONTAINER</code>. Save-</p>\n\n<p>Much easier: <strong>copy</strong> the files <code>.project</code> and <code>.classpath</code> from an existing Java project and <strong>edit</strong> the node <code>result name</code> to the name of this project. Maybe you have to refresh the project (F5).</p>\n\n<p>You'll get the same result as with the solution of Chris Marasti-Georg. </p>\n\n<h2>Edit</h2>\n\n<p><img src=\"https://i.stack.imgur.com/ycbnM.png\" alt=\"enter image description here\"></p>\n" }, { "answer_id": 30620066, "author": "Kumar", "author_id": 2182344, "author_profile": "https://Stackoverflow.com/users/2182344", "pm_score": 1, "selected": false, "text": "<ol>\n<li>Right click on project</li>\n<li>Configure -> 'Convert to Faceted Form'</li>\n<li>You will get a popup, Select 'Java' in 'Project Facet' column.</li>\n<li>Press Apply and Ok.</li>\n</ol>\n" }, { "answer_id": 31248884, "author": "Brian de Alwis", "author_id": 600339, "author_profile": "https://Stackoverflow.com/users/600339", "pm_score": 2, "selected": false, "text": "<p>Another possible way is to delete the project from Eclipse (but don't delete the project contents from disk!) and then use the <em>New Java Project</em> wizard to create a project in-place. That wizard will detect the Java code and set up build paths automatically.</p>\n" }, { "answer_id": 31965240, "author": "Premraj", "author_id": 1697099, "author_profile": "https://Stackoverflow.com/users/1697099", "pm_score": 4, "selected": false, "text": "<blockquote>\n <p>Using project <strong>Project facets</strong> we can configure characteristics and requirements for projects. </p>\n</blockquote>\n\n<p>To find Project facets on eclipse: </p>\n\n<ul>\n<li>Step 1: Right click on the project and choose <code>properties</code> from the menu.</li>\n<li><p>Step 2:Select <code>project facets</code> option. Click on <code>Convert to faceted form...</code>\n<a href=\"https://i.stack.imgur.com/q9bsH.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/q9bsH.png\" alt=\"enter image description here\"></a></p></li>\n<li><p>Step 3: We can find all available facets you can select and change their settings.\n<a href=\"https://i.stack.imgur.com/gBlxO.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/gBlxO.png\" alt=\"enter image description here\"></a></p></li>\n</ul>\n" }, { "answer_id": 39590714, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Depending on the Eclipse in question the required WTP packages may be found with different names. For example in Eclipse Luna I found it easiest to search with \"Tools\" and choose one that mentioned Tools for Java EE development. That added the project facet functionality. Searching with \"WTP\" wasn't of much help.</p>\n" }, { "answer_id": 53286006, "author": "Salix alba", "author_id": 865481, "author_profile": "https://Stackoverflow.com/users/865481", "pm_score": 4, "selected": false, "text": "<p>In newer versions of eclipse (I'm using 4.9.0) there is another, possibly easier, methods. As well as Project Facets, there are now Project Natures. Here the process is simple get the Project Natures property page up, and then click the Add... button. This will come up with possible natures included Java Nature and Eclipse Faceted Project Properties. Just add the Java Nature and ignore the various warning messages and your done. </p>\n\n<p><a href=\"https://i.stack.imgur.com/ovpGZ.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ovpGZ.png\" alt=\"Project Nature\"></a></p>\n\n<p>This method might be better as you don't have to convert to Faceted form first. Furthermore Java was not offered in the add Facet menu.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5917/" ]
I checked out a project from SVN and did not specify the project type, so it checked out as a "default" project. What is the easiest way to quickly convert this into a "Java" project? I'm using Eclipse version 3.3.2.
Open the .project file and add java nature and builders. ```xml <projectDescription> <buildSpec> <buildCommand> <name>org.eclipse.jdt.core.javabuilder</name> <arguments> </arguments> </buildCommand> </buildSpec> <natures> <nature>org.eclipse.jdt.core.javanature</nature> </natures> </projectDescription> ``` And in .classpath, reference the Java libs: ```xml <classpath> <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> </classpath> ```
179,448
<p>on KDE, there's a possibility to execute a command when some event happen. for example one can execute a script when kmail receives a mail or when a akregator fetches a new feed.</p> <p>I want to execute the script on a way I can retrieve the mail/feed subject in my script. is there a possibility to specify the program to execute:</p> <pre><code>myprogram &lt;SUBJECT&gt; ? </code></pre> <p>possibly specify it as an argument or an environment variable.</p>
[ { "answer_id": 179456, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 5, "selected": true, "text": "<p>With my <a href=\"http://pd.acm.org/\" rel=\"noreferrer\">ACM membership</a>, I get access to both Safari and Books24x7 (this includes Apress).</p>\n\n<p>The selection is reduced from the total offering of those sites (600 in Safari only available to professional members and 500 in Books24x7 available to both student and professional members), but I find it's well worth the ACM annual membership, especially when you factor in the other benefits.</p>\n\n<p>There is a discount for first year members: <a href=\"http://learnmore.acm.org/joinacm5.html\" rel=\"noreferrer\">http://learnmore.acm.org/joinacm5.html</a></p>\n\n<p>Our local library (<a href=\"http://nutrias.org\" rel=\"noreferrer\">nutrias.org</a>) does have ebooks for free also, but I haven't looked to see if they have technical books. In addition, they are term-limited with DRM (yuk).</p>\n" }, { "answer_id": 179457, "author": "MvdD", "author_id": 18044, "author_profile": "https://Stackoverflow.com/users/18044", "pm_score": 2, "selected": false, "text": "<p>I use paper books and use <a href=\"http://www.amazon.com\" rel=\"nofollow noreferrer\">Amazon</a> as a reference</p>\n" }, { "answer_id": 179558, "author": "Flory", "author_id": 5551, "author_profile": "https://Stackoverflow.com/users/5551", "pm_score": 2, "selected": false, "text": "<p>Cade,</p>\n\n<p>Not the answer you are looking for but if you are paying for Safari check around your local library systems and make sure you cannot get it for free. </p>\n" }, { "answer_id": 181040, "author": "bog", "author_id": 20909, "author_profile": "https://Stackoverflow.com/users/20909", "pm_score": 1, "selected": false, "text": "<p>Here in Santa Clara county, California, we can access the library e-resources, including Safari, from the library's website.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/65724/" ]
on KDE, there's a possibility to execute a command when some event happen. for example one can execute a script when kmail receives a mail or when a akregator fetches a new feed. I want to execute the script on a way I can retrieve the mail/feed subject in my script. is there a possibility to specify the program to execute: ``` myprogram <SUBJECT> ? ``` possibly specify it as an argument or an environment variable.
With my [ACM membership](http://pd.acm.org/), I get access to both Safari and Books24x7 (this includes Apress). The selection is reduced from the total offering of those sites (600 in Safari only available to professional members and 500 in Books24x7 available to both student and professional members), but I find it's well worth the ACM annual membership, especially when you factor in the other benefits. There is a discount for first year members: <http://learnmore.acm.org/joinacm5.html> Our local library ([nutrias.org](http://nutrias.org)) does have ebooks for free also, but I haven't looked to see if they have technical books. In addition, they are term-limited with DRM (yuk).
179,466
<p>I'm creating a self updating app where I have the majority of the code in a seperate DLL. It's command line and will eventually be run on Mono. I'm just trying to get this code to work in C# on windows at the command line.</p> <p>How can I create a c# application that I can delete a supporting dll while its running?</p> <pre><code>AppDomain domain = AppDomain.CreateDomain("MyDomain"); ObjectHandle instance = domain.CreateInstance( "VersionUpdater.Core", "VersionUpdater.Core.VersionInfo"); object unwrap = instance.Unwrap(); Console.WriteLine(((ICommand)unwrap).Run()); AppDomain.Unload(domain); Console.ReadLine(); </code></pre> <p>at the ReadLine the VersionUpdater.Core.dll is still locked from deletion</p> <p>The ICommand interface is in VersionUpdater.Common.dll which is referenced by both the Commandline app and VersionUpdater.Core.dll</p>
[ { "answer_id": 179477, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 3, "selected": false, "text": "<p>The only way I've ever managed something similar is to have the DLL in a separate AppDomain to the assembly that is trying to delete it. I unload the other AppDomain and then delete the DLL from disk.</p>\n\n<p>If you're looking for a way to perform the update, off the top of my head I would go for a stub exe that spawns the real AppDomain. Then, when that stub exe detects an update is to be applied, it quits the other AppDomain and then does the update magic.</p>\n\n<p>EDIT: The updater cannot share DLLs with the thing it is updating, otherwise it will lock those DLLs and therefore prevent them from being deleted. I suspect this is why you still get an exception. The updater has to be standalone and not reliant on anything that the other AppDomain uses, and vice versa.</p>\n" }, { "answer_id": 179518, "author": "Philip Rieck", "author_id": 12643, "author_profile": "https://Stackoverflow.com/users/12643", "pm_score": 1, "selected": false, "text": "<p>Unwrap will load the assembly of the object's type into the appdomain that calls it. One way around this is to create a type in your \"base\" assembly that calls command.run, then load that into your new appdomain. This way you never have to call unwrap on an object from a type in a different assembly, and you can delete the assembly on disk.</p>\n" }, { "answer_id": 622990, "author": "Cheeso", "author_id": 48082, "author_profile": "https://Stackoverflow.com/users/48082", "pm_score": 1, "selected": false, "text": "<p>When I built a self-updating app, I used the stub idea, but the stub was the app itself.</p>\n\n<p>The app would start, look for updates. If it found an update, it would download a copy of the new app to temp storage, and then start it up (System.Diagnostics.Process.Start()) using a command-line option that said \"you are being updated\". Then the original exe exits. </p>\n\n<p>The spawned exe starts up, sees that it is an update, and copies itself to the original app directory. It then starts the app from that new location. Then the spawned exe ends. </p>\n\n<p>The newly started exe from the original app install location starts up - sees the temp file and deletes it. Then resumes normal execution. </p>\n" }, { "answer_id": 924702, "author": "RandomNickName42", "author_id": 67819, "author_profile": "https://Stackoverflow.com/users/67819", "pm_score": 1, "selected": false, "text": "<p>You can always use <code>MOVEFILE_DELAY_UNTIL_REBOOT</code> to delete on reboot. This is most likely the least hackey way todo this sort of thing, by hackey I ususally see things like; loading up new DLL's or injecting to explorer.exe even patching a system dll to get loaded into another process, etc... </p>\n\n<p><strong>MoveFileEx</strong> <a href=\"http://msdn.microsoft.com/en-us/library/aa365240(VS.85).aspx\" rel=\"nofollow noreferrer\">From MSDN</a>;</p>\n\n<blockquote>\n <p>lpNewFileName [in, <strong>optional</strong>] The new\n name of the file or directory on the\n local computer.</p>\n \n <p>When <em>moving</em> a file, the destination\n can be on a different file system or\n volume. If the destination is on\n another drive, you must set the\n <code>MOVEFILE_COPY_ALLOWED</code> flag in dwFlags.</p>\n \n <p>When moving a directory, the\n destination must be on the same drive.</p>\n \n <p>If dwFlags specifies\n <code>MOVEFILE_DELAY_UNTIL_REBOOT</code> and\n lpNewFileName is <strong>NULL</strong>, <em>MoveFileEx</em>\n registers the lpExistingFileName file\n to be <strong>deleted</strong> when the system\n restarts. If lpExistingFileName refers\n to a directory, the system removes the\n directory at restart only if the\n directory is empty.</p>\n</blockquote>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179466", "https://Stackoverflow.com", "https://Stackoverflow.com/users/253/" ]
I'm creating a self updating app where I have the majority of the code in a seperate DLL. It's command line and will eventually be run on Mono. I'm just trying to get this code to work in C# on windows at the command line. How can I create a c# application that I can delete a supporting dll while its running? ``` AppDomain domain = AppDomain.CreateDomain("MyDomain"); ObjectHandle instance = domain.CreateInstance( "VersionUpdater.Core", "VersionUpdater.Core.VersionInfo"); object unwrap = instance.Unwrap(); Console.WriteLine(((ICommand)unwrap).Run()); AppDomain.Unload(domain); Console.ReadLine(); ``` at the ReadLine the VersionUpdater.Core.dll is still locked from deletion The ICommand interface is in VersionUpdater.Common.dll which is referenced by both the Commandline app and VersionUpdater.Core.dll
The only way I've ever managed something similar is to have the DLL in a separate AppDomain to the assembly that is trying to delete it. I unload the other AppDomain and then delete the DLL from disk. If you're looking for a way to perform the update, off the top of my head I would go for a stub exe that spawns the real AppDomain. Then, when that stub exe detects an update is to be applied, it quits the other AppDomain and then does the update magic. EDIT: The updater cannot share DLLs with the thing it is updating, otherwise it will lock those DLLs and therefore prevent them from being deleted. I suspect this is why you still get an exception. The updater has to be standalone and not reliant on anything that the other AppDomain uses, and vice versa.
179,468
<p>What I want to do is set the focus to a specific control (specifically a <code>TextBox</code>) on a tab page when that tab page is selected.</p> <p>I've tried to call <code>Focus</code> during the Selected event of the containing tab control, but that isn't working. After that I tried to call focus during the <code>VisibleChanged</code> event of the control itself (with a check so that I'm not focusing on an invisible control), but that isn't working either.</p> <p>Searching this site, I've come across this <a href="https://stackoverflow.com/questions/48680/winforms-c-set-focus-to-first-child-control-of-tab-page">question</a> but that isn't working either. Although after that, I did notice that calling the <code>Focus</code> of the control does make it the <code>ActiveControl</code>.</p>
[ { "answer_id": 179499, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 4, "selected": true, "text": "<p>I did this and it seems to work:</p>\n\n<p>Handle the <code>SelectedIndexChanged</code> for the <code>tabControl</code>.\nCheck if <code>tabControl1.SelectedIndex</code> == the one I want and \ncall <code>textBox.Focus();</code></p>\n\n<p>I'm using VS 2008, BTW.</p>\n\n<hr>\n\n<p>Something like this worked:</p>\n\n<pre><code>private void tabControl1_selectedIndexChanged(object sender, EventArgs e)\n{\n if (tabControl1.SelectedIndex == 1)\n {\n textBox1.Focus();\n }\n}\n</code></pre>\n" }, { "answer_id": 179606, "author": "CheGueVerra", "author_id": 17787, "author_profile": "https://Stackoverflow.com/users/17787", "pm_score": 1, "selected": false, "text": "<p>Try the TabPage.Enter something like</p>\n\n<pre>\n private void tabPage1_Enter(object sender, EventArgs e)\n {\n TabPage page = (TabPage)sender;\n switch (page.TabIndex)\n {\n case 0:\n textBox1.Text = \"Page 1\";\n if (!textBox1.Focus())\n textBox1.Focus();\n\n break;\n case 1:\n textBox2.Text = \"Page 2\";\n\n if (!textBox2.Focus())\n textBox2.Focus();\n\n break;\n default:\n throw new InvalidOperationException();\n }\n }\n</pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1440933/" ]
What I want to do is set the focus to a specific control (specifically a `TextBox`) on a tab page when that tab page is selected. I've tried to call `Focus` during the Selected event of the containing tab control, but that isn't working. After that I tried to call focus during the `VisibleChanged` event of the control itself (with a check so that I'm not focusing on an invisible control), but that isn't working either. Searching this site, I've come across this [question](https://stackoverflow.com/questions/48680/winforms-c-set-focus-to-first-child-control-of-tab-page) but that isn't working either. Although after that, I did notice that calling the `Focus` of the control does make it the `ActiveControl`.
I did this and it seems to work: Handle the `SelectedIndexChanged` for the `tabControl`. Check if `tabControl1.SelectedIndex` == the one I want and call `textBox.Focus();` I'm using VS 2008, BTW. --- Something like this worked: ``` private void tabControl1_selectedIndexChanged(object sender, EventArgs e) { if (tabControl1.SelectedIndex == 1) { textBox1.Focus(); } } ```
179,472
<p>I need to export a SL DataGrid to HTML so my users can then print it. Can someone put me in the right direction?</p> <p>Upate: After reading Rob's answer I am changing my question. Instead of Silverlight Grid to HTML, I now just want to export it to PDF. Has anyone used any 3rd party PDF generators with Silverlight?</p>
[ { "answer_id": 179499, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 4, "selected": true, "text": "<p>I did this and it seems to work:</p>\n\n<p>Handle the <code>SelectedIndexChanged</code> for the <code>tabControl</code>.\nCheck if <code>tabControl1.SelectedIndex</code> == the one I want and \ncall <code>textBox.Focus();</code></p>\n\n<p>I'm using VS 2008, BTW.</p>\n\n<hr>\n\n<p>Something like this worked:</p>\n\n<pre><code>private void tabControl1_selectedIndexChanged(object sender, EventArgs e)\n{\n if (tabControl1.SelectedIndex == 1)\n {\n textBox1.Focus();\n }\n}\n</code></pre>\n" }, { "answer_id": 179606, "author": "CheGueVerra", "author_id": 17787, "author_profile": "https://Stackoverflow.com/users/17787", "pm_score": 1, "selected": false, "text": "<p>Try the TabPage.Enter something like</p>\n\n<pre>\n private void tabPage1_Enter(object sender, EventArgs e)\n {\n TabPage page = (TabPage)sender;\n switch (page.TabIndex)\n {\n case 0:\n textBox1.Text = \"Page 1\";\n if (!textBox1.Focus())\n textBox1.Focus();\n\n break;\n case 1:\n textBox2.Text = \"Page 2\";\n\n if (!textBox2.Focus())\n textBox2.Focus();\n\n break;\n default:\n throw new InvalidOperationException();\n }\n }\n</pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23663/" ]
I need to export a SL DataGrid to HTML so my users can then print it. Can someone put me in the right direction? Upate: After reading Rob's answer I am changing my question. Instead of Silverlight Grid to HTML, I now just want to export it to PDF. Has anyone used any 3rd party PDF generators with Silverlight?
I did this and it seems to work: Handle the `SelectedIndexChanged` for the `tabControl`. Check if `tabControl1.SelectedIndex` == the one I want and call `textBox.Focus();` I'm using VS 2008, BTW. --- Something like this worked: ``` private void tabControl1_selectedIndexChanged(object sender, EventArgs e) { if (tabControl1.SelectedIndex == 1) { textBox1.Focus(); } } ```
179,480
<p>Provided I have admin access, I need a way to manage (Create, modify, remove) local accounts in a remote machine from an ASP.NET client.</p> <p>I'm clueless in how to approach this. Is WMI a possibility (System.Management namespace)? Any pointers?</p>
[ { "answer_id": 179561, "author": "sebagomez", "author_id": 23893, "author_profile": "https://Stackoverflow.com/users/23893", "pm_score": 0, "selected": false, "text": "<p>I used System.DirectoryServices to get data from users in a n ActiveDirectory (LDAP).\nI don't know if that's the kind of thing you're looking for.<br>\nHope it helps.</p>\n" }, { "answer_id": 179570, "author": "Robert Rouse", "author_id": 25129, "author_profile": "https://Stackoverflow.com/users/25129", "pm_score": 0, "selected": false, "text": "<p>You should be able to do this via DirectoryEntry.</p>\n" }, { "answer_id": 180678, "author": "Matt Hanson", "author_id": 5473, "author_profile": "https://Stackoverflow.com/users/5473", "pm_score": 3, "selected": true, "text": "<p>Give this a try:</p>\n\n<pre><code>DirectoryEntry directoryEntry = new DirectoryEntry(\"WinNT://ComputerName\" &amp; \",computer\", \"AdminUN\", \"AdminPW\");\nDirectoryEntry user = directoryEntry.Children.Add(\"username\", \"user\");\nuser.Invoke(\"SetPassword\", new object[] { \"password\"});\nser.CommitChanges();\n</code></pre>\n\n<p>If you do need to go the Active Directory route, you can change the directoryEntry path string to something like this: LDAP://CN=ComputerName,DC=MySample,DC=com</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25885/" ]
Provided I have admin access, I need a way to manage (Create, modify, remove) local accounts in a remote machine from an ASP.NET client. I'm clueless in how to approach this. Is WMI a possibility (System.Management namespace)? Any pointers?
Give this a try: ``` DirectoryEntry directoryEntry = new DirectoryEntry("WinNT://ComputerName" & ",computer", "AdminUN", "AdminPW"); DirectoryEntry user = directoryEntry.Children.Add("username", "user"); user.Invoke("SetPassword", new object[] { "password"}); ser.CommitChanges(); ``` If you do need to go the Active Directory route, you can change the directoryEntry path string to something like this: LDAP://CN=ComputerName,DC=MySample,DC=com
179,488
<p>Is there a list somewhere on common Attributes which are used in objects like <code>Serializable</code>?</p> <p>Thanks</p> <p>Edit ~ The reason I asked is that I came across an StoredProcedure attribute in ntiers ORMS.</p>
[ { "answer_id": 179496, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 5, "selected": true, "text": "<p>Yes, look msdn has you covered please look <a href=\"http://msdn.microsoft.com/en-us/library/system.attribute.aspx#inheritanceContinued\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>EDIT: This link only answer sucked. Here is a working extractor for all loadable types (gac) that have Attribute in the name. </p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Reflection;\n\nnamespace ConsoleApp1\n{\n class Program\n {\n static void Main(string[] args)\n {\n var process = new Process();\n //your path may vary\n process.StartInfo.FileName = @\"C:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v10.0A\\bin\\NETFX 4.6.1 Tools\\gacutil.exe\";\n process.StartInfo.RedirectStandardOutput = true;\n process.StartInfo.UseShellExecute = false;\n process.StartInfo.Arguments = \"/l\";\n process.Start();\n\n var consoleOutput = process.StandardOutput;\n\n\n var assemblyList = new List&lt;string&gt;();\n var startAdding = false;\n while (consoleOutput.EndOfStream == false)\n {\n var line = consoleOutput.ReadLine();\n if (line.IndexOf(\"The Global Assembly Cache contains the following assemblies\", StringComparison.OrdinalIgnoreCase) &gt;= 0)\n {\n startAdding = true;\n continue;\n }\n\n if (startAdding == false)\n {\n continue;\n }\n\n //add any other filter conditions (framework version, etc)\n if (line.IndexOf(\"System.\", StringComparison.OrdinalIgnoreCase) &lt; 0)\n {\n continue;\n }\n\n assemblyList.Add(line.Trim());\n }\n\n var collectedRecords = new List&lt;string&gt;();\n var failedToLoad = new List&lt;string&gt;();\n\n Console.WriteLine($\"Found {assemblyList.Count} assemblies\");\n var currentItem = 1;\n\n\n foreach (var gacAssemblyInfo in assemblyList)\n {\n Console.SetCursorPosition(0, 2);\n Console.WriteLine($\"On {currentItem} of {assemblyList.Count} \");\n Console.SetCursorPosition(0, 3);\n Console.WriteLine($\"Loading {gacAssemblyInfo}\");\n currentItem++;\n\n try\n {\n var asm = Assembly.Load(gacAssemblyInfo);\n\n foreach (Type t in asm.GetTypes())\n {\n if (t.Name.EndsWith(\"Attribute\", StringComparison.OrdinalIgnoreCase))\n {\n collectedRecords.Add($\"{t.FullName} - {t.Assembly.FullName}\");\n }\n }\n\n }\n catch (Exception ex)\n {\n failedToLoad.Add($\"FAILED to load {gacAssemblyInfo} - {ex}\");\n Console.SetCursorPosition(1, 9);\n Console.WriteLine($\"Failure to load count: {failedToLoad.Count}\");\n Console.SetCursorPosition(4, 10);\n Console.WriteLine($\"Last Fail: {gacAssemblyInfo}\");\n }\n }\n\n var fileBase = System.IO.Path.GetRandomFileName();\n var goodFile = $\"{fileBase}_good.txt\";\n var failFile = $\"{fileBase}_failedToLoad.txt\";\n System.IO.File.WriteAllLines(goodFile, collectedRecords);\n System.IO.File.WriteAllLines(failFile, failedToLoad);\n Console.SetCursorPosition(0, 15);\n Console.WriteLine($\"Matching types: {goodFile}\");\n Console.WriteLine($\"Failures: {failFile}\");\n Console.WriteLine(\"Press ENTER to exit\");\n Console.ReadLine();\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 179502, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 2, "selected": false, "text": "<p>I'm not aware of a complete list of Attributes, but a search for Attribute in MSDN can yield interesting results. I have tended to browse namespaces for interesting attribute types and then go look them up to see what I might use them for. Not the most efficient approach, I know.</p>\n\n<p>The MSDN entry for <a href=\"http://msdn.microsoft.com/en-us/library/system.attribute.aspx\" rel=\"nofollow noreferrer\" title=\"System.Attribute\">System.Attribute</a> has a list at the bottom.</p>\n" }, { "answer_id": 179560, "author": "ilitirit", "author_id": 9825, "author_profile": "https://Stackoverflow.com/users/9825", "pm_score": 1, "selected": false, "text": "<p>You may not find what you're looking for because it's possible that you're looking at a custom attribute.</p>\n\n<p><a href=\"http://www.code-magazine.com/Article.aspx?quickid=0307041\" rel=\"nofollow noreferrer\">http://www.code-magazine.com/Article.aspx?quickid=0307041</a></p>\n" }, { "answer_id": 179568, "author": "Inisheer", "author_id": 2982, "author_profile": "https://Stackoverflow.com/users/2982", "pm_score": 2, "selected": false, "text": "<p>Additionally, you can create your own attributes. If you are searching through someone else's code, it's easy to get confused when they create their own.</p>\n" }, { "answer_id": 179615, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "<p>You can use Reflector to browse the <code>mscorlib</code> assembly, and under <strong><code>System.Attribute</code></strong>, expand the <em>Derived Types</em> node. It will show all attributes for all the assemblies currently loaded in Reflector.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23667/" ]
Is there a list somewhere on common Attributes which are used in objects like `Serializable`? Thanks Edit ~ The reason I asked is that I came across an StoredProcedure attribute in ntiers ORMS.
Yes, look msdn has you covered please look [here](http://msdn.microsoft.com/en-us/library/system.attribute.aspx#inheritanceContinued). EDIT: This link only answer sucked. Here is a working extractor for all loadable types (gac) that have Attribute in the name. ``` using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; namespace ConsoleApp1 { class Program { static void Main(string[] args) { var process = new Process(); //your path may vary process.StartInfo.FileName = @"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\gacutil.exe"; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.UseShellExecute = false; process.StartInfo.Arguments = "/l"; process.Start(); var consoleOutput = process.StandardOutput; var assemblyList = new List<string>(); var startAdding = false; while (consoleOutput.EndOfStream == false) { var line = consoleOutput.ReadLine(); if (line.IndexOf("The Global Assembly Cache contains the following assemblies", StringComparison.OrdinalIgnoreCase) >= 0) { startAdding = true; continue; } if (startAdding == false) { continue; } //add any other filter conditions (framework version, etc) if (line.IndexOf("System.", StringComparison.OrdinalIgnoreCase) < 0) { continue; } assemblyList.Add(line.Trim()); } var collectedRecords = new List<string>(); var failedToLoad = new List<string>(); Console.WriteLine($"Found {assemblyList.Count} assemblies"); var currentItem = 1; foreach (var gacAssemblyInfo in assemblyList) { Console.SetCursorPosition(0, 2); Console.WriteLine($"On {currentItem} of {assemblyList.Count} "); Console.SetCursorPosition(0, 3); Console.WriteLine($"Loading {gacAssemblyInfo}"); currentItem++; try { var asm = Assembly.Load(gacAssemblyInfo); foreach (Type t in asm.GetTypes()) { if (t.Name.EndsWith("Attribute", StringComparison.OrdinalIgnoreCase)) { collectedRecords.Add($"{t.FullName} - {t.Assembly.FullName}"); } } } catch (Exception ex) { failedToLoad.Add($"FAILED to load {gacAssemblyInfo} - {ex}"); Console.SetCursorPosition(1, 9); Console.WriteLine($"Failure to load count: {failedToLoad.Count}"); Console.SetCursorPosition(4, 10); Console.WriteLine($"Last Fail: {gacAssemblyInfo}"); } } var fileBase = System.IO.Path.GetRandomFileName(); var goodFile = $"{fileBase}_good.txt"; var failFile = $"{fileBase}_failedToLoad.txt"; System.IO.File.WriteAllLines(goodFile, collectedRecords); System.IO.File.WriteAllLines(failFile, failedToLoad); Console.SetCursorPosition(0, 15); Console.WriteLine($"Matching types: {goodFile}"); Console.WriteLine($"Failures: {failFile}"); Console.WriteLine("Press ENTER to exit"); Console.ReadLine(); } } } ```
179,510
<p>Is there a way to get rid of the selection rectangle when clicking a link which does not refresh the current page entirely?</p>
[ { "answer_id": 179525, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 3, "selected": false, "text": "<p>Try adding this:</p>\n\n<pre><code>onclick=\"this.blur()\"\n</code></pre>\n\n<p>Discussed here as well</p>\n\n<p><a href=\"https://stackoverflow.com/questions/176695/css-eliminating-browsers-selected-lines-around-a-hyperlinked-image\">(CSS?) Eliminating browser&#39;s &#39;selected&#39; lines around a hyperlinked image?</a></p>\n" }, { "answer_id": 179532, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 7, "selected": true, "text": "<p>Do you mean the dotted outline of a target?</p>\n\n<p>Try:</p>\n\n<pre><code>:focus {\n outline: 0;\n}\n</code></pre>\n\n<p>This would remove all focus outlines. IT's essentially the same as onclick in JavaScript terms. You might prefer to apply this to <code>a:focus</code>.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16440/" ]
Is there a way to get rid of the selection rectangle when clicking a link which does not refresh the current page entirely?
Do you mean the dotted outline of a target? Try: ``` :focus { outline: 0; } ``` This would remove all focus outlines. IT's essentially the same as onclick in JavaScript terms. You might prefer to apply this to `a:focus`.
179,539
<p>If I have $var defined in Page1.php and in Page2.php I have</p> <pre> //Page2.php include('Page1.php'); echo $var; </pre> <p>For what reasons will it not print the value of $var to the screen? The files are in the same directory so paths shouldn't be the issue. I've checked the php.ini file and nothing really jumps out at me. Any ideas?</p>
[ { "answer_id": 179552, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 2, "selected": false, "text": "<p>Possible causes:</p>\n\n<ul>\n<li>The current working path isn't always the same as the file's. For example, if Page2.php is being included at a higher level, that higher level will be the path. Either make sure you've loaded Page2.php directly or move Page1.php accordingly.</li>\n<li>Make sure <code>$var</code> is really what you expect it to be. Echo it in Page1.php to confirm. (this also checks the right file is being included)</li>\n<li>If the source isn't really this simple, make sure you're not undefining/clearing <code>$var</code> anywhere.</li>\n</ul>\n" }, { "answer_id": 179572, "author": "andyuk", "author_id": 2108, "author_profile": "https://Stackoverflow.com/users/2108", "pm_score": 0, "selected": false, "text": "<p>I've just tested:</p>\n\n<p>page1.php:</p>\n\n<pre><code>&lt;?php\n$foo = \"bar\"\n?&gt;\n</code></pre>\n\n<p>page2.php:</p>\n\n<pre><code>&lt;?php\ninclude('page1.php');\necho $foo;\n?&gt;\n</code></pre>\n\n<p>This works.</p>\n\n<p>You might want to check your file paths. Also var_dump() is handy to check the variable output.</p>\n" }, { "answer_id": 179578, "author": "Mnebuerquo", "author_id": 5114, "author_profile": "https://Stackoverflow.com/users/5114", "pm_score": 1, "selected": true, "text": "<p>If it were a path problem you would see a warning in your error log. You could also change to require instead of include and it would become obvious.</p>\n\n<pre><code>echo getcwd();\n</code></pre>\n\n<p>You can also print your working directory to figure out what's wrong.</p>\n\n<p>Is $var created in a function? If so, make sure you have </p>\n\n<pre><code>global $var;\n</code></pre>\n\n<p>before the first assignment in that function.</p>\n" }, { "answer_id": 179587, "author": "Markus", "author_id": 18597, "author_profile": "https://Stackoverflow.com/users/18597", "pm_score": 0, "selected": false, "text": "<p>Check that you not turned off the whole <a href=\"http://php.net/error_reporting\" rel=\"nofollow noreferrer\">error_reporting</a>. Maybe the include goes wrong and so the variable never is included.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24059/" ]
If I have $var defined in Page1.php and in Page2.php I have ``` //Page2.php include('Page1.php'); echo $var; ``` For what reasons will it not print the value of $var to the screen? The files are in the same directory so paths shouldn't be the issue. I've checked the php.ini file and nothing really jumps out at me. Any ideas?
If it were a path problem you would see a warning in your error log. You could also change to require instead of include and it would become obvious. ``` echo getcwd(); ``` You can also print your working directory to figure out what's wrong. Is $var created in a function? If so, make sure you have ``` global $var; ``` before the first assignment in that function.
179,556
<p>Like the title says, If I place an <code>app_offline.htm</code> in the application root, will it cut off currently running requests, or just new ones?</p>
[ { "answer_id": 179609, "author": "Brian Kim", "author_id": 5704, "author_profile": "https://Stackoverflow.com/users/5704", "pm_score": 3, "selected": false, "text": "<p>From ScottGu's blog:</p>\n\n<blockquote>\n <p>Basically, if you place a file with\n this name in the root of a web\n application directory, <strong>ASP.NET 2.0\n will shut-down the application, unload\n the application domain from the\n server, and stop processing any new\n incoming requests for that\n application</strong>. ASP.NET will also then\n respond to all requests for dynamic\n pages in the application by sending\n back the content of the\n app_offline.htm file (for example: you\n might want to have a “site under\n construction” or “down for\n maintenance” message).</p>\n</blockquote>\n\n<p><a href=\"http://weblogs.asp.net/scottgu/archive/2005/10/06/426755.aspx\" rel=\"nofollow noreferrer\">App_Offline.htm - ScottGu's Blog</a></p>\n\n<p>So, it seems like it will continue processing current request, but stop new incoming requests.</p>\n" }, { "answer_id": 179686, "author": "Gabe Sumner", "author_id": 12689, "author_profile": "https://Stackoverflow.com/users/12689", "pm_score": 6, "selected": true, "text": "<p>Here is my lame experiment; I created an ASPX page with the following code:\n</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>protected void Page_Load(object sender, EventArgs e)\n{\n Response.BufferOutput = false;\n Response.Write(\"Step 1&lt;br /&gt;\");\n System.Threading.Thread.Sleep(10000);\n Response.Write(\"Step 2&lt;br /&gt;\");\n System.Threading.Thread.Sleep(10000);\n Response.Write(\"Step 3&lt;br /&gt;\");\n}\n</code></pre>\n\n<p>This code simply introduces some loooong page loads. I accessed the page and while it was loading, I created an \"app_offline.htm\" file. I then loaded another web browser and confirmed the application was offline. I then re-visited my \"loading\" request...it completed all the way to step 3.</p>\n\n<p>This confirms that current requests finish loading and new requests are turned away.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16172/" ]
Like the title says, If I place an `app_offline.htm` in the application root, will it cut off currently running requests, or just new ones?
Here is my lame experiment; I created an ASPX page with the following code: ```cs protected void Page_Load(object sender, EventArgs e) { Response.BufferOutput = false; Response.Write("Step 1<br />"); System.Threading.Thread.Sleep(10000); Response.Write("Step 2<br />"); System.Threading.Thread.Sleep(10000); Response.Write("Step 3<br />"); } ``` This code simply introduces some loooong page loads. I accessed the page and while it was loading, I created an "app\_offline.htm" file. I then loaded another web browser and confirmed the application was offline. I then re-visited my "loading" request...it completed all the way to step 3. This confirms that current requests finish loading and new requests are turned away.
179,565
<p>If yes, on which operating system, shell or whatever?</p> <p>Consider the following java program (I'm using java just as an example, any language would be good for this question, which is more about operation systems):</p> <pre><code>public class ExitCode { public static void main(String args[]) { System.exit(Integer.parseInt(args[0])); } } </code></pre> <p>Running it on Linux and bash, it returns always values less equal 255, e.g. (<code>echo $?</code> prints the exit code of the previous executed command)</p> <pre><code>&gt; java ExitCode 2; echo $? 2 &gt; java ExitCode 128; echo $? 128 &gt; java ExitCode 255; echo $? 255 &gt; java ExitCode 256; echo $? 0 &gt; java ExitCode 65536; echo $? 0 </code></pre> <hr> <p>EDITED: the (only, so far) answer below fully explain what happens on UNIXes. I'm still wondering about other OSes.</p>
[ { "answer_id": 179652, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 6, "selected": true, "text": "<h3>Using <code>wait()</code> or <code>waitpid()</code></h3>\n\n<p>It is not possible on Unix and derivatives using POSIX functions like <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html\" rel=\"nofollow noreferrer\"><code>wait()</code></a> and <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/functions/waitpid.html\" rel=\"nofollow noreferrer\"><code>waitpid()</code></a>. The exit status information returned consists of two 8-bit fields, one containing the exit status, and the other containing information about the cause of death (0 implying orderly exit under program control, other values indicating that a signal killed it, and indicating whether a core was dumped).</p>\n\n<h3>Using <code>sigaction()</code> with <code>SA_SIGINFO</code></h3>\n\n<p>If you work hard, and read the POSIX specification of <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigaction.html\" rel=\"nofollow noreferrer\"><code>sigaction()</code></a> and <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html\" rel=\"nofollow noreferrer\"><code>&lt;signal.h&gt;</code></a> and <a href=\"https://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04_03\" rel=\"nofollow noreferrer\">Signal Actions</a>, you will find that you can get hold of the 32-bit value passed to <code>exit()</code> by a child process. However, it is not completely straight-forward.</p>\n\n<pre><code>#include &lt;errno.h&gt;\n#include &lt;signal.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;sys/wait.h&gt;\n#include &lt;time.h&gt;\n#include &lt;unistd.h&gt;\n\nstatic siginfo_t sig_info = { 0 };\nstatic volatile sig_atomic_t sig_num = 0;\nstatic void *sig_ctxt = 0;\n\nstatic void catcher(int signum, siginfo_t *info, void *vp)\n{\n sig_num = signum;\n sig_info = *info;\n sig_ctxt = vp;\n}\n\nstatic void set_handler(int signum)\n{\n struct sigaction sa;\n sa.sa_flags = SA_SIGINFO;\n sa.sa_sigaction = catcher;\n sigemptyset(&amp;sa.sa_mask);\n\n if (sigaction(signum, &amp;sa, 0) != 0)\n {\n int errnum = errno;\n fprintf(stderr, \"Failed to set signal handler (%d: %s)\\n\", errnum, strerror(errnum));\n exit(1);\n }\n}\n\nstatic void prt_interrupt(FILE *fp)\n{\n if (sig_num != 0)\n {\n fprintf(fp, \"Signal %d from PID %d (status 0x%.8X; UID %d)\\n\",\n sig_info.si_signo, (int)sig_info.si_pid, sig_info.si_status,\n (int)sig_info.si_uid);\n sig_num = 0;\n }\n}\n\nstatic void five_kids(void)\n{\n const int base = 0xCC00FF40;\n for (int i = 0; i &lt; 5; i++)\n {\n pid_t pid = fork();\n if (pid &lt; 0)\n break;\n else if (pid == 0)\n {\n printf(\"PID %d - exiting with status %d (0x%.8X)\\n\",\n (int)getpid(), base + i, base + i);\n exit(base + i);\n }\n else\n {\n int status = 0;\n pid_t corpse = wait(&amp;status);\n if (corpse != -1)\n printf(\"Child: %d; Corpse: %d; Status = 0x%.4X - waited\\n\", pid, corpse, (status &amp; 0xFFFF));\n struct timespec nap = { .tv_sec = 0, .tv_nsec = 1000000 }; // 1 millisecond\n nanosleep(&amp;nap, 0);\n prt_interrupt(stdout);\n fflush(0);\n }\n }\n}\n\nint main(void)\n{\n set_handler(SIGCHLD);\n five_kids();\n}\n</code></pre>\n\n<p>When run (program <code>sigexit73</code> compiled from <code>sigexit73.c</code>), this produces output like:</p>\n\n<pre><code>$ sigexit73\nPID 26599 - exiting with status -872349888 (0xCC00FF40)\nSignal 20 from PID 26599 (status 0xCC00FF40; UID 501)\nChild: 26600; Corpse: 26599; Status = 0x4000 - waited\nPID 26600 - exiting with status -872349887 (0xCC00FF41)\nSignal 20 from PID 26600 (status 0xCC00FF41; UID 501)\nChild: 26601; Corpse: 26600; Status = 0x4100 - waited\nPID 26601 - exiting with status -872349886 (0xCC00FF42)\nSignal 20 from PID 26601 (status 0xCC00FF42; UID 501)\nChild: 26602; Corpse: 26601; Status = 0x4200 - waited\nPID 26602 - exiting with status -872349885 (0xCC00FF43)\nSignal 20 from PID 26602 (status 0xCC00FF43; UID 501)\nChild: 26603; Corpse: 26602; Status = 0x4300 - waited\nPID 26603 - exiting with status -872349884 (0xCC00FF44)\nSignal 20 from PID 26603 (status 0xCC00FF44; UID 501)\n$\n</code></pre>\n\n<p>With the one millisecond call to <code>nanosleep()</code> removed, the output is apt to look like:</p>\n\n<pre><code>$ sigexit73\nsigexit23\nPID 26621 - exiting with status -872349888 (0xCC00FF40)\nSignal 20 from PID 26621 (status 0xCC00FF40; UID 501)\nChild: 26622; Corpse: 26621; Status = 0x4000 - waited\nPID 26622 - exiting with status -872349887 (0xCC00FF41)\nPID 26623 - exiting with status -872349886 (0xCC00FF42)\nSignal 20 from PID 26622 (status 0xCC00FF41; UID 501)\nChild: 26624; Corpse: 26623; Status = 0x4200 - waited\nSignal 20 from PID 26623 (status 0xCC00FF42; UID 501)\nChild: 26625; Corpse: 26622; Status = 0x4100 - waited\nPID 26624 - exiting with status -872349885 (0xCC00FF43)\nPID 26625 - exiting with status -872349884 (0xCC00FF44)\n$\n</code></pre>\n\n<p>Note that there are only three lines starting <code>Signal</code> here, and also only three lines ending <code>waited</code>; some of the signals and exit statuses are lost. This is likely to be because of timing issues between the <code>SIGCHLD</code> signals being set to the parent process.</p>\n\n<p>However, the key point is that 4 bytes of data can be transmitted in the <code>exit()</code> status when the code uses <code>sigaction()</code>, <code>SIGCHLD</code>, <code>SA_SIGINFO</code> to track the status.</p>\n\n<p>Just for the record, the testing was performed on a MacBook Pro running macOS Mojave 10.14.6, using GCC 9.2.0 and XCode 11.3.1. The code is also available in my <a href=\"https://github.com/jleffler/soq\" rel=\"nofollow noreferrer\">SOQ</a> (Stack Overflow Questions) repository on GitHub as file <code>sigexit73.c</code> in the <a href=\"https://github.com/jleffler/soq/tree/master/src/so-1843-7779\" rel=\"nofollow noreferrer\">src/so-1843-7779</a> sub-directory.</p>\n" }, { "answer_id": 205303, "author": "Veynom", "author_id": 11670, "author_profile": "https://Stackoverflow.com/users/11670", "pm_score": 2, "selected": false, "text": "<p>Windows has many more exit codes, over 14,000. (I'm sure you often saw some of them on your own screen).</p>\n\n<p>Here comes:</p>\n\n<ul>\n<li><a href=\"http://www.hiteksoftware.com/knowledge/articles/049.htm\" rel=\"nofollow noreferrer\">A list of Windows exit codes</a>.</li>\n<li><a href=\"http://blogs.msdn.com/powershell/archive/2006/10/14/Windows-PowerShell-Exit-Codes.aspx\" rel=\"nofollow noreferrer\">PowerShell script to test them</a>.</li>\n</ul>\n" }, { "answer_id": 328423, "author": "Michael Ratanapintha", "author_id": 1879, "author_profile": "https://Stackoverflow.com/users/1879", "pm_score": 4, "selected": false, "text": "<p>On modern Windows, the OS itself, and the default console shell (<code>CMD.EXE</code>), accept and show exit codes throughout at least the whole range of 32-bit signed integers. Running your example above in <code>CMD.EXE</code> gives the exit codes you asked for :</p>\n\n<pre><code>&gt; java ExitCode 2\n&gt; echo %errorlevel%\n2\n\n&gt; java ExitCode 128\n&gt; echo %errorlevel%\n128\n\n&gt; java ExitCode 255\n&gt; echo %errorlevel%\n255\n\n&gt; java ExitCode 256\n&gt; echo %errorlevel%\n256\n\n&gt; java ExitCode 65536\n&gt; echo %errorlevel%\n65536\n</code></pre>\n\n<p>Windows doesn't really have the concept of Unix signals, nor does it try to hijack the exit code to add extra information, so as long as your shell (or whatever program ends up reading the exit code) doesn't do that either, you should get back the exit codes you returned. Fortunately, programs that use Microsoft's C runtime (including all programs compiled with MS Visual C++) preserve the exit code as is from exiting processes.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25891/" ]
If yes, on which operating system, shell or whatever? Consider the following java program (I'm using java just as an example, any language would be good for this question, which is more about operation systems): ``` public class ExitCode { public static void main(String args[]) { System.exit(Integer.parseInt(args[0])); } } ``` Running it on Linux and bash, it returns always values less equal 255, e.g. (`echo $?` prints the exit code of the previous executed command) ``` > java ExitCode 2; echo $? 2 > java ExitCode 128; echo $? 128 > java ExitCode 255; echo $? 255 > java ExitCode 256; echo $? 0 > java ExitCode 65536; echo $? 0 ``` --- EDITED: the (only, so far) answer below fully explain what happens on UNIXes. I'm still wondering about other OSes.
### Using `wait()` or `waitpid()` It is not possible on Unix and derivatives using POSIX functions like [`wait()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/wait.html) and [`waitpid()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/waitpid.html). The exit status information returned consists of two 8-bit fields, one containing the exit status, and the other containing information about the cause of death (0 implying orderly exit under program control, other values indicating that a signal killed it, and indicating whether a core was dumped). ### Using `sigaction()` with `SA_SIGINFO` If you work hard, and read the POSIX specification of [`sigaction()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/sigaction.html) and [`<signal.h>`](http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/signal.h.html) and [Signal Actions](https://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04_03), you will find that you can get hold of the 32-bit value passed to `exit()` by a child process. However, it is not completely straight-forward. ``` #include <errno.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> static siginfo_t sig_info = { 0 }; static volatile sig_atomic_t sig_num = 0; static void *sig_ctxt = 0; static void catcher(int signum, siginfo_t *info, void *vp) { sig_num = signum; sig_info = *info; sig_ctxt = vp; } static void set_handler(int signum) { struct sigaction sa; sa.sa_flags = SA_SIGINFO; sa.sa_sigaction = catcher; sigemptyset(&sa.sa_mask); if (sigaction(signum, &sa, 0) != 0) { int errnum = errno; fprintf(stderr, "Failed to set signal handler (%d: %s)\n", errnum, strerror(errnum)); exit(1); } } static void prt_interrupt(FILE *fp) { if (sig_num != 0) { fprintf(fp, "Signal %d from PID %d (status 0x%.8X; UID %d)\n", sig_info.si_signo, (int)sig_info.si_pid, sig_info.si_status, (int)sig_info.si_uid); sig_num = 0; } } static void five_kids(void) { const int base = 0xCC00FF40; for (int i = 0; i < 5; i++) { pid_t pid = fork(); if (pid < 0) break; else if (pid == 0) { printf("PID %d - exiting with status %d (0x%.8X)\n", (int)getpid(), base + i, base + i); exit(base + i); } else { int status = 0; pid_t corpse = wait(&status); if (corpse != -1) printf("Child: %d; Corpse: %d; Status = 0x%.4X - waited\n", pid, corpse, (status & 0xFFFF)); struct timespec nap = { .tv_sec = 0, .tv_nsec = 1000000 }; // 1 millisecond nanosleep(&nap, 0); prt_interrupt(stdout); fflush(0); } } } int main(void) { set_handler(SIGCHLD); five_kids(); } ``` When run (program `sigexit73` compiled from `sigexit73.c`), this produces output like: ``` $ sigexit73 PID 26599 - exiting with status -872349888 (0xCC00FF40) Signal 20 from PID 26599 (status 0xCC00FF40; UID 501) Child: 26600; Corpse: 26599; Status = 0x4000 - waited PID 26600 - exiting with status -872349887 (0xCC00FF41) Signal 20 from PID 26600 (status 0xCC00FF41; UID 501) Child: 26601; Corpse: 26600; Status = 0x4100 - waited PID 26601 - exiting with status -872349886 (0xCC00FF42) Signal 20 from PID 26601 (status 0xCC00FF42; UID 501) Child: 26602; Corpse: 26601; Status = 0x4200 - waited PID 26602 - exiting with status -872349885 (0xCC00FF43) Signal 20 from PID 26602 (status 0xCC00FF43; UID 501) Child: 26603; Corpse: 26602; Status = 0x4300 - waited PID 26603 - exiting with status -872349884 (0xCC00FF44) Signal 20 from PID 26603 (status 0xCC00FF44; UID 501) $ ``` With the one millisecond call to `nanosleep()` removed, the output is apt to look like: ``` $ sigexit73 sigexit23 PID 26621 - exiting with status -872349888 (0xCC00FF40) Signal 20 from PID 26621 (status 0xCC00FF40; UID 501) Child: 26622; Corpse: 26621; Status = 0x4000 - waited PID 26622 - exiting with status -872349887 (0xCC00FF41) PID 26623 - exiting with status -872349886 (0xCC00FF42) Signal 20 from PID 26622 (status 0xCC00FF41; UID 501) Child: 26624; Corpse: 26623; Status = 0x4200 - waited Signal 20 from PID 26623 (status 0xCC00FF42; UID 501) Child: 26625; Corpse: 26622; Status = 0x4100 - waited PID 26624 - exiting with status -872349885 (0xCC00FF43) PID 26625 - exiting with status -872349884 (0xCC00FF44) $ ``` Note that there are only three lines starting `Signal` here, and also only three lines ending `waited`; some of the signals and exit statuses are lost. This is likely to be because of timing issues between the `SIGCHLD` signals being set to the parent process. However, the key point is that 4 bytes of data can be transmitted in the `exit()` status when the code uses `sigaction()`, `SIGCHLD`, `SA_SIGINFO` to track the status. Just for the record, the testing was performed on a MacBook Pro running macOS Mojave 10.14.6, using GCC 9.2.0 and XCode 11.3.1. The code is also available in my [SOQ](https://github.com/jleffler/soq) (Stack Overflow Questions) repository on GitHub as file `sigexit73.c` in the [src/so-1843-7779](https://github.com/jleffler/soq/tree/master/src/so-1843-7779) sub-directory.
179,582
<p>I'm primarily interested in pgsql for this, but I was wondering if there is a way in any RDBMS to do an insert operation, <em>without</em> disabling and re-enabling any FOREIGN KEY or NOT NULL constraints, on two tables that refer to each other. (You might think of this as a chicken that was somehow born from its own egg.)</p> <p>For a practical example, if you had a multiple-choice quiz system, with tables "question" and "answer", where question.correct_answer refers to answer.id, and answer.question refers to question.id, is it possible to add a question and its answers simultaneously?</p> <p>(For the record, I'm aware that you can do the disabling and re-enabling in a transaction block, and that another solution is to not have a correct_answer column but instead have answer.correct as a boolean and have a check constraint making sure there's exactly one correct answer per question. But I'm not curious about alternative solutions here.)</p>
[ { "answer_id": 179651, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 3, "selected": true, "text": "<p>I think that you answered your own question - you have to make a transaction block. In PostgreSQL this should work:</p>\n\n<pre><code>BEGIN;\n SET CONSTRAINTS ALL DEFERRED;\nINSERT INTO questions (questionid, answerid, question)\n VALUES (1, 100, 'How long are Abraham Lincoln\\'s legs?');\nINSERT INTO answers (answerid, questionid, answer)\n VALUES (100, 1, 'Long enough to reach the ground.');\nCOMMIT;\n</code></pre>\n\n<p>It has to be in a transaction block because if either INSERT statement failed the database would be in an invalid state (table constraints not met).</p>\n" }, { "answer_id": 179663, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 0, "selected": false, "text": "<p>I'd do it in the following way:</p>\n\n<ol>\n<li>Define Questions.correct_answer as a\nnullable column.</li>\n<li>Insert row into Questions, with correct_answer set to NULL.</li>\n<li>Insert row(s) into Answers, referencing the row in Questions.</li>\n<li>UPDATE Questions SET correct_answer\n= ?</li>\n</ol>\n" }, { "answer_id": 246743, "author": "David Schmitt", "author_id": 4918, "author_profile": "https://Stackoverflow.com/users/4918", "pm_score": 0, "selected": false, "text": "<p>In the simple case of one question and one answer it is advisable to just put all attributes into one table.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16777/" ]
I'm primarily interested in pgsql for this, but I was wondering if there is a way in any RDBMS to do an insert operation, *without* disabling and re-enabling any FOREIGN KEY or NOT NULL constraints, on two tables that refer to each other. (You might think of this as a chicken that was somehow born from its own egg.) For a practical example, if you had a multiple-choice quiz system, with tables "question" and "answer", where question.correct\_answer refers to answer.id, and answer.question refers to question.id, is it possible to add a question and its answers simultaneously? (For the record, I'm aware that you can do the disabling and re-enabling in a transaction block, and that another solution is to not have a correct\_answer column but instead have answer.correct as a boolean and have a check constraint making sure there's exactly one correct answer per question. But I'm not curious about alternative solutions here.)
I think that you answered your own question - you have to make a transaction block. In PostgreSQL this should work: ``` BEGIN; SET CONSTRAINTS ALL DEFERRED; INSERT INTO questions (questionid, answerid, question) VALUES (1, 100, 'How long are Abraham Lincoln\'s legs?'); INSERT INTO answers (answerid, questionid, answer) VALUES (100, 1, 'Long enough to reach the ground.'); COMMIT; ``` It has to be in a transaction block because if either INSERT statement failed the database would be in an invalid state (table constraints not met).
179,619
<p>Why is it that there are two kinds of references in xaml.</p> <p>One looks like this:</p> <pre><code>xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" </code></pre> <p>But mine look like this:</p> <pre><code>xmlns:WPFToolKit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit" </code></pre> <p>Why can't I do this:</p> <pre><code>xmlns:local="http://myschema.mydomain.com/MyControlNamespace </code></pre> <p>Thanks to <a href="https://stackoverflow.com/users/7116/sixlettervariables">ixlettervariables</a> for the answer. Here's a detailed explanation <a href="http://codingcontext.wordpress.com/2008/10/09/consolidating-xaml-namespaces/" rel="nofollow noreferrer">here</a></p>
[ { "answer_id": 179632, "author": "user7116", "author_id": 7116, "author_profile": "https://Stackoverflow.com/users/7116", "pm_score": 4, "selected": true, "text": "<p>The second instance is basically an unmapped, but explicit reference to a namespace in an assembly. The first instance is a mapped reference to a namespace in some assembly referenced by your project. <a href=\"http://msdn.microsoft.com/en-us/library/ms747086.aspx\" rel=\"noreferrer\">XAML Namespaces and Namespace Mapping</a>, over at MSDN explains this in more detail:</p>\n\n<blockquote>\n <p>WPF defines a CLR attribute that is consumed by XAML processors in order to map multiple CLR namespaces to a single XML namespace. This attribute, <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.markup.xmlnsdefinitionattribute.aspx\" rel=\"noreferrer\">XmlnsDefinitionAttribute</a>, is placed at the assembly level in the source code that produces the assembly. The WPF assembly source code uses this attribute to map the various common namespaces, such as System.Windows and System.Windows.Controls, to the <a href=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" rel=\"noreferrer\">http://schemas.microsoft.com/winfx/2006/xaml/presentation</a> namespace.</p>\n</blockquote>\n\n<p>Therefore, by adding the following to your assembly you could do just that:</p>\n\n<pre><code>[assembly:XmlnsDefinition(\"http://myschema.mydomain.com/MyControlNamespace\", \"My.Control.Namespace\")]\n</code></pre>\n" }, { "answer_id": 179641, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 0, "selected": false, "text": "<p>The schema reference is used for the standard XAML elements, which the compiler knows how to map directly to built-in WPF classes.</p>\n\n<p>The CLR namespace reference is a hint for the compiler which assmebly and namespace to look for when mapping the XML elements in your namespace namespace to your CLR/WPF classes.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17744/" ]
Why is it that there are two kinds of references in xaml. One looks like this: ``` xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" ``` But mine look like this: ``` xmlns:WPFToolKit="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit" ``` Why can't I do this: ``` xmlns:local="http://myschema.mydomain.com/MyControlNamespace ``` Thanks to [ixlettervariables](https://stackoverflow.com/users/7116/sixlettervariables) for the answer. Here's a detailed explanation [here](http://codingcontext.wordpress.com/2008/10/09/consolidating-xaml-namespaces/)
The second instance is basically an unmapped, but explicit reference to a namespace in an assembly. The first instance is a mapped reference to a namespace in some assembly referenced by your project. [XAML Namespaces and Namespace Mapping](http://msdn.microsoft.com/en-us/library/ms747086.aspx), over at MSDN explains this in more detail: > > WPF defines a CLR attribute that is consumed by XAML processors in order to map multiple CLR namespaces to a single XML namespace. This attribute, [XmlnsDefinitionAttribute](http://msdn.microsoft.com/en-us/library/system.windows.markup.xmlnsdefinitionattribute.aspx), is placed at the assembly level in the source code that produces the assembly. The WPF assembly source code uses this attribute to map the various common namespaces, such as System.Windows and System.Windows.Controls, to the <http://schemas.microsoft.com/winfx/2006/xaml/presentation> namespace. > > > Therefore, by adding the following to your assembly you could do just that: ``` [assembly:XmlnsDefinition("http://myschema.mydomain.com/MyControlNamespace", "My.Control.Namespace")] ```
179,625
<p>In SQL Server 2017, you can use this syntax, but not in earlier versions:</p> <pre><code>SELECT Name = TRIM(Name) FROM dbo.Customer; </code></pre>
[ { "answer_id": 179630, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 9, "selected": true, "text": "<pre><code>SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer\n</code></pre>\n" }, { "answer_id": 179637, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 6, "selected": false, "text": "<p>To Trim on the right, use:</p>\n\n<pre><code>SELECT RTRIM(Names) FROM Customer\n</code></pre>\n\n<p>To Trim on the left, use:</p>\n\n<pre><code>SELECT LTRIM(Names) FROM Customer\n</code></pre>\n\n<p>To Trim on the both sides, use:</p>\n\n<pre><code>SELECT LTRIM(RTRIM(Names)) FROM Customer\n</code></pre>\n" }, { "answer_id": 182047, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 3, "selected": false, "text": "<p>I assume this is a one-off data scrubbing exercise. Once done, ensure you add database constraints to prevent bad data in the future e.g. </p>\n\n<pre><code>ALTER TABLE Customer ADD\n CONSTRAINT customer_names__whitespace\n CHECK (\n Names NOT LIKE ' %'\n AND Names NOT LIKE '% '\n AND Names NOT LIKE '% %'\n );\n</code></pre>\n\n<p>Also consider disallowing other characters (tab, carriage return, line feed, etc) that may cause problems. </p>\n\n<p>It may also be a good time to split those Names into <code>family_name</code>, <code>first_name</code>, etc :)</p>\n" }, { "answer_id": 6420947, "author": "rahularyansharma", "author_id": 779158, "author_profile": "https://Stackoverflow.com/users/779158", "pm_score": 1, "selected": false, "text": "<p>in sql server 2008 r2 with ssis expression we have the trim function .</p>\n\n<p>SQL Server Integration Services (SSIS) is a component of the Microsoft SQL Server database software that can be used to perform a broad range of data migration tasks.</p>\n\n<p>you can find the complete description on this link</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms139947.aspx\" rel=\"nofollow\">http://msdn.microsoft.com/en-us/library/ms139947.aspx</a></p>\n\n<p>but this function have some limitation in itself which are also mentioned by msdn on that page.\nbut this is in <strong>sql server 2008 r2</strong> </p>\n\n<pre><code>TRIM(\" New York \") .The return result is \"New York\".\n</code></pre>\n" }, { "answer_id": 24605674, "author": "razon", "author_id": 908936, "author_profile": "https://Stackoverflow.com/users/908936", "pm_score": 3, "selected": false, "text": "<pre><code>SELECT LTRIM(RTRIM(Replace(Replace(Replace(name,' ',' '),CHAR(13), ' '),char(10), ' ')))\nfrom author\n</code></pre>\n" }, { "answer_id": 54250546, "author": "Kai-Ove Böhnisch", "author_id": 10932439, "author_profile": "https://Stackoverflow.com/users/10932439", "pm_score": 2, "selected": false, "text": "<p>Extended version of \"REPLACE\":</p>\n\n<pre><code>REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(RTRIM(LTRIM(REPLACE(\"Put in your Field name\", ' ',' '))),'''',''), CHAR(9), ''), CHAR(10), ''), CHAR(13), ''), CHAR(160), '') [CorrValue]\n</code></pre>\n" }, { "answer_id": 63855110, "author": "Reejuta Sharmin", "author_id": 7911722, "author_profile": "https://Stackoverflow.com/users/7911722", "pm_score": 0, "selected": false, "text": "<p>To trim any set of characters from the beginning and end of a string, you can do the following code where @TrimPattern defines the characters to be trimmed. In this example, Space, tab, LF and CR characters are being trimmed:</p>\n<p>Declare @Test nvarchar(50) = Concat (' ', char(9), char(13), char(10), ' ', 'TEST', ' ', char(9), char(10), char(13),' ', 'Test', ' ', char(9), ' ', char(9), char(13), ' ')</p>\n<p>DECLARE @TrimPattern nvarchar(max) = '%[^ ' + char(9) + char(13) + char(10) +']%'</p>\n<p>SELECT SUBSTRING(@Test, PATINDEX(@TrimPattern, @Test), LEN(@Test) - PATINDEX(@TrimPattern, @Test) - PATINDEX(@TrimPattern, LTRIM(REVERSE(@Test))) + 2)</p>\n" }, { "answer_id": 73069982, "author": "Poke82", "author_id": 19386078, "author_profile": "https://Stackoverflow.com/users/19386078", "pm_score": 0, "selected": false, "text": "<p>SELECT REPLACE(name, ' ', '') FROM Customer</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179625", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6522/" ]
In SQL Server 2017, you can use this syntax, but not in earlier versions: ``` SELECT Name = TRIM(Name) FROM dbo.Customer; ```
``` SELECT LTRIM(RTRIM(Names)) AS Names FROM Customer ```
179,653
<p>I want to take the value stored in a 32 bit unsigned int, put it into four chars and then store the integer value of each of these chars in a string.</p> <p>I think the first part goes like this:</p> <pre><code>char a = orig &lt;&lt; 8; char b = orig &lt;&lt; 8; char c = orig &lt;&lt; 8; char d = orig &lt;&lt; 8; </code></pre>
[ { "answer_id": 179666, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 1, "selected": false, "text": "<p>Not quite:</p>\n\n<pre><code>char a = orig &amp; 0xff;\norig &gt;&gt;= 8;\nchar b = orig &amp; 0xff;\norig &gt;&gt;= 8;\nchar c = orig &amp; 0xff;\norig &gt;&gt;= 8;\nchar d = orig &amp; 0xff;\n</code></pre>\n\n<p>Not exactly sure what you mean by \"store the integer values of each of these values into a string. Do you want turn <code>0x10111213</code> into <code>\"16 17 18 19\"</code>, or what?</p>\n" }, { "answer_id": 179669, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 0, "selected": false, "text": "<p>For hexadecimal:</p>\n\n<pre><code>sprintf(buffer, \"%lX\", orig);\n</code></pre>\n\n<p>For decimal:</p>\n\n<pre><code>sprintf(buffer, \"%ld\", orig);\n</code></pre>\n\n<p>Use <code>snprintf</code> to avoid a buffer overflow.</p>\n" }, { "answer_id": 179675, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 2, "selected": false, "text": "<p>Use a <code>union</code>. (As requested here is the sample program.)</p>\n\n<pre><code> #include &lt;&lt;iostream&gt;&gt;\n #include &lt;&lt;stdio.h&gt;&gt;\n using namespace std;\n\n union myunion\n {\n struct chars \n { \n unsigned char d, c, b, a;\n } mychars;\n\n unsigned int myint; \n };\n\n int main(void) \n {\n myunion u;\n\n u.myint = 0x41424344;\n\n cout &lt;&lt; \"a = \" &lt;&lt; u.mychars.a &lt;&lt; endl;\n cout &lt;&lt; \"b = \" &lt;&lt; u.mychars.b &lt;&lt; endl;\n cout &lt;&lt; \"c = \" &lt;&lt; u.mychars.c &lt;&lt; endl;\n cout &lt;&lt; \"d = \" &lt;&lt; u.mychars.d &lt;&lt; endl;\n }\n</code></pre>\n\n<p>As James mentioned this is platform specific.</p>\n" }, { "answer_id": 179682, "author": "friol", "author_id": 23034, "author_profile": "https://Stackoverflow.com/users/23034", "pm_score": 3, "selected": false, "text": "<p>Let's say \"orig\" is a 32bit variable containing your value.</p>\n\n<p>I imagine you want to do something like this:</p>\n\n<pre><code>unsigned char byte1=orig&amp;0xff;\nunsigned char byte2=(orig&gt;&gt;8)&amp;0xff;\nunsigned char byte3=(orig&gt;&gt;16)&amp;0xff;\nunsigned char byte4=(orig&gt;&gt;24)&amp;0xff;\n\nchar myString[256];\nsprintf(myString,\"%x %x %x %x\",byte1,byte2,byte3,byte4);\n</code></pre>\n\n<p>I'm not sure this is always endian correct, by the way. (<em>Edit</em>: indeed, it is endian correct, since bitshift operations shouldn't be affected by endianness)</p>\n\n<p>Hope this helps.</p>\n" }, { "answer_id": 179694, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 4, "selected": true, "text": "<p>If you really want to extract the individual bytes first:</p>\n\n<pre><code>unsigned char a = orig &amp; 0xff;\nunsigned char b = (orig &gt;&gt; 8) &amp; 0xff;\nunsigned char c = (orig &gt;&gt; 16) &amp; 0xff;\nunsigned char d = (orig &gt;&gt; 24) &amp; 0xff;\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>unsigned char *chars = (unsigned char *)(&amp;orig);\nunsigned char a = chars[0];\nunsigned char b = chars[1];\nunsigned char c = chars[2];\nunsigned char d = chars[3];\n</code></pre>\n\n<p>Or use a union of an unsigned long and four chars:</p>\n\n<pre><code>union charSplitter {\n struct {\n unsigned char a, b, c, d;\n } charValues;\n\n unsigned int intValue;\n};\n\ncharSplitter splitter;\nsplitter.intValue = orig;\n// splitter.charValues.a will give you first byte etc.\n</code></pre>\n\n<p>Update: as friol pointed out, solutions 2 and 3 are not endianness-agnostic; which bytes <code>a</code>, <code>b</code>, <code>c</code> and <code>d</code> represent depend on the CPU architecture.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1449/" ]
I want to take the value stored in a 32 bit unsigned int, put it into four chars and then store the integer value of each of these chars in a string. I think the first part goes like this: ``` char a = orig << 8; char b = orig << 8; char c = orig << 8; char d = orig << 8; ```
If you really want to extract the individual bytes first: ``` unsigned char a = orig & 0xff; unsigned char b = (orig >> 8) & 0xff; unsigned char c = (orig >> 16) & 0xff; unsigned char d = (orig >> 24) & 0xff; ``` Or: ``` unsigned char *chars = (unsigned char *)(&orig); unsigned char a = chars[0]; unsigned char b = chars[1]; unsigned char c = chars[2]; unsigned char d = chars[3]; ``` Or use a union of an unsigned long and four chars: ``` union charSplitter { struct { unsigned char a, b, c, d; } charValues; unsigned int intValue; }; charSplitter splitter; splitter.intValue = orig; // splitter.charValues.a will give you first byte etc. ``` Update: as friol pointed out, solutions 2 and 3 are not endianness-agnostic; which bytes `a`, `b`, `c` and `d` represent depend on the CPU architecture.
179,665
<p>I have an array <code>NSMutableArray</code> with happy objects. These objects viciously turn on (leak) me whenever I try to clear the array of all the objects and repopulate it.</p> <p>It's allocated in the init function like so</p> <pre><code>self.list = [NSMutableArray array]; </code></pre> <p>The different methods I have used to clear it out include:</p> <pre><code>self.list = nil; self.list = [NSMutableArray array]; </code></pre> <p>and</p> <pre><code>[self.eventList removeAllObjects]; </code></pre> <p>Explicitly allocating and releasing the array doesn't work either. The leak ONLY occurs when I try to reset the list.</p> <p>Am I missing a step when resetting or is this a different problem?</p>
[ { "answer_id": 179695, "author": "Elfred", "author_id": 12636, "author_profile": "https://Stackoverflow.com/users/12636", "pm_score": 2, "selected": false, "text": "<p>what does your <code>@property</code> declaration look like? are you synthesizing the accessors? If so, you need <code>@property(retain)</code>. I'm assuming that when you say the objects are turning on you, you're referring to a core dump <code>(EXC\\_BAD\\_ACCESS)</code>. </p>\n" }, { "answer_id": 179892, "author": "Nathan Kinsinger", "author_id": 20045, "author_profile": "https://Stackoverflow.com/users/20045", "pm_score": 3, "selected": false, "text": "<p>Are you referring to the objects in the array leaking? </p>\n\n<p>How are you adding objects to the array? The array will retain them, so you need to autorelease or release them after you've added them to the array. Otherwise after the array is released the objects will still be retained (leaked).</p>\n\n<pre><code>MyEvent *event = [[MyEvent alloc] initWithEventInfo:info];\n[self.eventList addObject:event];\n[event release];\n\nMyEvent *otherEvent = [[[MyEvent alloc] initWithEventInfo:otherInfo] autorelease];\n[self.eventList addObject:otherEvent];\n</code></pre>\n" }, { "answer_id": 180024, "author": "Colin Wheeler", "author_id": 2750, "author_profile": "https://Stackoverflow.com/users/2750", "pm_score": 0, "selected": false, "text": "<p>I'd say I don't really have enough Information here to give you a great answer. Are you saying that the <code>NSMutableArray</code> is still allocated, but empty and doesn't have any objects in it but that the objects once previously in the array are still allocated even though they should be dealloc'd at that point in the app?</p>\n\n<p>If that's the case the array could possibly be empty, but your objects aren't handling the dealloc message sent to them, in which case the objects are still around in memory but not referenced by anything. </p>\n\n<p>I'd say to help you I'd like to know exactly what MallocDebug exactly says is being leaked. Also @Elfred is giving out some good advice in checking your <code>@property</code> method for the array, really it should be retain or copy.</p>\n" }, { "answer_id": 189382, "author": "Chris Schreiner", "author_id": 24093, "author_profile": "https://Stackoverflow.com/users/24093", "pm_score": 0, "selected": false, "text": "<p>If the leak only occurs when you try to reset the list, you have someone/something else using those other objects that you just tried to release.</p>\n" }, { "answer_id": 190099, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 4, "selected": true, "text": "<p>How did you create the objects that are leaking?\nIf you did something like this:</p>\n\n<pre><code>- (void)addObjectsToArray {\n\n [list addObject:[[MyClass alloc] init];\n\n OtherClass *anotherObject = [[OtherClass alloc] init];\n [list addObject:anotherObject];\n}\n</code></pre>\n\n<p>then you will leak two objects when list is deallocated.</p>\n\n<p>You should replace any such code with:</p>\n\n<pre><code>- (void)addObjectsToArray {\n\n MyClass *myObject = [[MyClass alloc] init];\n [list addObject:myObject];\n [myObject release];\n\n OtherClass *anotherObject = [[OtherClass alloc] init];\n [list addObject:anotherObject];\n [anotherObject release];\n}\n</code></pre>\n\n<p>In more detail:</p>\n\n<p>If you follow the first pattern, you've created two objects which, according to the <a href=\"http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Tasks/MemoryManagementRules.html\" rel=\"nofollow noreferrer\">Cocoa memory management rules</a> you own. It's your responsibility to relinquish ownership. If you don't, the object will never be deallocated and you'll see a leak.</p>\n\n<p>You don't see a leak immediately, though, because you pass the objects to the array, which also takes ownership of them. The leak will only be recognised when you remove the objects from the array or when the array itself is deallocated. When either of those events occurs, the array relinquishes ownership of the objects and they'll be left \"live\" in your application, but you won't have any references to them.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25004/" ]
I have an array `NSMutableArray` with happy objects. These objects viciously turn on (leak) me whenever I try to clear the array of all the objects and repopulate it. It's allocated in the init function like so ``` self.list = [NSMutableArray array]; ``` The different methods I have used to clear it out include: ``` self.list = nil; self.list = [NSMutableArray array]; ``` and ``` [self.eventList removeAllObjects]; ``` Explicitly allocating and releasing the array doesn't work either. The leak ONLY occurs when I try to reset the list. Am I missing a step when resetting or is this a different problem?
How did you create the objects that are leaking? If you did something like this: ``` - (void)addObjectsToArray { [list addObject:[[MyClass alloc] init]; OtherClass *anotherObject = [[OtherClass alloc] init]; [list addObject:anotherObject]; } ``` then you will leak two objects when list is deallocated. You should replace any such code with: ``` - (void)addObjectsToArray { MyClass *myObject = [[MyClass alloc] init]; [list addObject:myObject]; [myObject release]; OtherClass *anotherObject = [[OtherClass alloc] init]; [list addObject:anotherObject]; [anotherObject release]; } ``` In more detail: If you follow the first pattern, you've created two objects which, according to the [Cocoa memory management rules](http://developer.apple.com/documentation/Cocoa/Conceptual/MemoryMgmt/Tasks/MemoryManagementRules.html) you own. It's your responsibility to relinquish ownership. If you don't, the object will never be deallocated and you'll see a leak. You don't see a leak immediately, though, because you pass the objects to the array, which also takes ownership of them. The leak will only be recognised when you remove the objects from the array or when the array itself is deallocated. When either of those events occurs, the array relinquishes ownership of the objects and they'll be left "live" in your application, but you won't have any references to them.
179,668
<p>I tried doing this:</p> <pre><code>root.addEventListener("click", function () { navigateToURL(ClickURLRequest,"_self"); }); </code></pre> <p>And it does add the event listener. I like using closures because they work well in this situation,</p> <p>however, removing the event listener requires a reference to the original function, and since I used an anonymous closure, it does not work, I tried:</p> <pre><code> root.removeEventListener("click", function () { navigateToURL(ClickURLRequest,"_self"); }); </code></pre> <p>as well as:</p> <pre><code> root.removeEventListener("click", function () {} ); </code></pre> <p>The only way I found it would work was to ditch the anonymous closure and point the event listeners at a pre-existing function:</p> <pre><code> function OnClick (e:Event) { navigateToURL(ClickURLRequest,"_self"); } root.addEventListener("click", OnClick); root.removeEventListener("click", OnClick); </code></pre> <p>Does anyone know a way to use anonymous closures for event handlers while still retaining the ability to remove them?</p>
[ { "answer_id": 179750, "author": "Javier", "author_id": 11649, "author_profile": "https://Stackoverflow.com/users/11649", "pm_score": 2, "selected": false, "text": "<p>You can think of the function() keyword as a constructor, creating a new object (a closure) each time. Therefore, if you create the closure just for as a parameter and don't retain a reference anywhere, there's no way to get a hold of \"the same\" closure somewhere else.</p>\n\n<p>The obvious solution is what you don't like, defining the function before using it. Of course, it can still be a full closure and not just a 'static-like' function. simply define it in the context you want, and assign it to a local variable.</p>\n" }, { "answer_id": 179842, "author": "JustLogic", "author_id": 21664, "author_profile": "https://Stackoverflow.com/users/21664", "pm_score": 0, "selected": false, "text": "<p>I'm not sure if this will work but its worth a shot: </p>\n\n<pre><code>root.removeEventListener(\"click\", arguments.callee );\n</code></pre>\n\n<p>More information about it can be found <a href=\"http://livedocs.adobe.com/flex/2/langref/arguments.html#callee\" rel=\"nofollow noreferrer\">Flex lang ref</a></p>\n" }, { "answer_id": 179905, "author": "BefittingTheorem", "author_id": 16744, "author_profile": "https://Stackoverflow.com/users/16744", "pm_score": 5, "selected": false, "text": "<p>Here's a generic way of removing event listeners that i have used on production projects</p>\n\n<pre><code>\naddEventListener\n(\n Event.ACTIVATE, \n function(event:Event):void\n {\n (event.target as EventDispatcher).removeEventListener(event.type, arguments.callee) \n }\n)\n</code></pre>\n" }, { "answer_id": 184072, "author": "user23405", "author_id": 23405, "author_profile": "https://Stackoverflow.com/users/23405", "pm_score": 0, "selected": false, "text": "<p>It's not too much different than using a defined function, but maybe this will satisfy your needs. Remember that Functions are first-class objects in ActionScript and you can store and pass them around as variables.</p>\n\n<pre>\nprotected function addListener()\n{\n m_handler = function(in_event:Event) { removeEventListener(MouseEvent.CLICK, m_handler); m_handler=null}\n addEventListener(MouseEvent.CLICK, m_handler)\n}\nprotected var m_handler:Function\n</pre>\n" }, { "answer_id": 191231, "author": "Jonathan", "author_id": 7099, "author_profile": "https://Stackoverflow.com/users/7099", "pm_score": 0, "selected": false, "text": "<p>Just a side note on your code that I came across in the Flex In A Week set of tutorials on the Adobe web site. There, they said you should always use the constants for the event types rather than the string. That way you get typo protection. If you make a typo in the event type string (like say \"clse\"), your event handler will get registered but of course never invoked. Instead, use Event.CLOSE so the compiler will catch the typo.</p>\n" }, { "answer_id": 213890, "author": "Simon", "author_id": 24727, "author_profile": "https://Stackoverflow.com/users/24727", "pm_score": -1, "selected": false, "text": "<p>I dont know what you're actually doing but in this particular example perhaps you could have a _clickEnabled global variable.</p>\n\n<p>Then inside the event handler you just check _clickEnabled, and if its false you just <code>return</code> immediately.</p>\n\n<p>Then you can enable and disable the overall event without detaching and reattaching it.</p>\n" }, { "answer_id": 948547, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<blockquote>\n <p>I found myself doing this a lot so I tried this. Seems to work fine.</p>\n</blockquote>\n\n<pre><code>addSelfDestructiveEventListener('roomRenderer', 'complete', trackAction, 'floorChanged');\n\nprivate function addSelfDestructiveEventListener(listenee:*, event:String, functionToCall:Function, StringArgs:String):void\n{\n this[listenee].addEventListener(event, function(event:Event):void\n {\n (event.target as EventDispatcher).removeEventListener(event.type, arguments.callee);\n functionToCall(StringArgs);\n })\n}\n</code></pre>\n" }, { "answer_id": 3195329, "author": "Emerson Cardoso", "author_id": 385590, "author_profile": "https://Stackoverflow.com/users/385590", "pm_score": 2, "selected": false, "text": "<p>I use this sometimes:</p>\n\n<pre><code>var closure:Function = null;\nroot.addEventListener(\"click\", \n closure = function () \n { \n navigateToURL(ClickURLRequest,\"_self\"); \n });\n\nroot.removeEventListener(\"click\", closure);\n</code></pre>\n" }, { "answer_id": 3894712, "author": "Marcus Stade", "author_id": 68909, "author_profile": "https://Stackoverflow.com/users/68909", "pm_score": 3, "selected": false, "text": "<p>As has already been suggested, you may remove the closure from the chain of listeners from within the closure itself. This is done through the use of arguments.callee:</p>\n\n<pre><code>myDispatcher.addEventListener(\"click\", function(event:Event):void\n{\n IEventDispatcher(event.target).removeEventListener(event.type, arguments.callee);\n\n // Whatever else needs doing goes here\n});\n</code></pre>\n\n<p>This will effectively turn the closure into a one-time listener of the event, simply detaching itself once the event has fired. While syntactically verbose, it's an incredibly useful technique for those many events that really only fire once (or that you only care about once) like \"creationComplete\" in Flex, for instance. I use this all the time when downloading data, since I think having the callback code inline makes it easier to understand. It is like hiding away the asynchronous-ness:</p>\n\n<pre><code>myLoader.addEventListener(\"complete\", function(event:Event):void\n{\n /* Even though the load is asynchronous, having the callback code inline\n * like this instead of scattered around makes it easier to understand,\n * in my opinion. */\n});\n</code></pre>\n\n<p>However, if you want to listen to the event multiple times, this will not be very effective for obvious reasons. In that case, you need to store a reference to the closure somewhere. Methods are objects like anything else in ActionScript and can be passed around. Thus, we can alter our code to look like this:</p>\n\n<pre><code>var closure:Function;\n\nmyDispatcher.addEventListener(\"click\", function(event:Event):void\n{\n closure = arguments.callee;\n\n // Whatever else needs doing goes here\n});\n</code></pre>\n\n<p>When you need to remove the event listener, use the 'closure' reference, like so:</p>\n\n<pre><code>myDispatcher.removeEventListener(\"click\", closure);\n</code></pre>\n\n<p>Obviously, this is an abstract example but using closures like this can be pretty useful. They do have drawbacks though, such as being less efficient than named methods. Another drawback is the fact that you actually have to store away a reference to the closure if you ever need it. Care must then be taken to preserve the integrity of that reference, just like with any other variable.</p>\n\n<p>Thus, while the different syntax may have its uses, it's not always the best solution. It's an apples and oranges kind of thing.</p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
I tried doing this: ``` root.addEventListener("click", function () { navigateToURL(ClickURLRequest,"_self"); }); ``` And it does add the event listener. I like using closures because they work well in this situation, however, removing the event listener requires a reference to the original function, and since I used an anonymous closure, it does not work, I tried: ``` root.removeEventListener("click", function () { navigateToURL(ClickURLRequest,"_self"); }); ``` as well as: ``` root.removeEventListener("click", function () {} ); ``` The only way I found it would work was to ditch the anonymous closure and point the event listeners at a pre-existing function: ``` function OnClick (e:Event) { navigateToURL(ClickURLRequest,"_self"); } root.addEventListener("click", OnClick); root.removeEventListener("click", OnClick); ``` Does anyone know a way to use anonymous closures for event handlers while still retaining the ability to remove them?
Here's a generic way of removing event listeners that i have used on production projects ``` addEventListener ( Event.ACTIVATE, function(event:Event):void { (event.target as EventDispatcher).removeEventListener(event.type, arguments.callee) } ) ```
179,676
<p>What is the best way to get a file (in this case, a .PDF, but any file will do) from a WebResponse and put it into a MemoryStream? Using .GetResponseStream() from WebResponse gets a Stream object, but if you want to convert that Stream to a specific type of stream, what do you do?</p>
[ { "answer_id": 179990, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Copied this from the web a year or so ago.</p>\n\n<pre><code>//---------- Start HttpResponse\nif(objHttpWebResponse.StatusCode == HttpStatusCode.OK)\n {\n //Get response stream\n objResponseStream = objHttpWebResponse.GetResponseStream();\n\n //Load response stream into XMLReader\n objXMLReader = new XmlTextReader(objResponseStream);\n\n //Declare XMLDocument\n XmlDocument xmldoc = new XmlDocument();\n xmldoc.Load(objXMLReader);\n\n //Set XMLResponse object returned from XMLReader\n XMLResponse = xmldoc;\n\n //Close XMLReader\n objXMLReader.Close();\n }\n\n //Close HttpWebResponse\n objHttpWebResponse.Close();\n}\n</code></pre>\n" }, { "answer_id": 180505, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<p>I found the following at <a href=\"http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/eeeefd81-8800-41b2-be63-71acdaddce0e/\" rel=\"nofollow noreferrer\">http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/eeeefd81-8800-41b2-be63-71acdaddce0e/</a></p>\n\n<pre><code> Dim request As WebRequest\n Dim response As WebResponse = Nothing\n Dim s As Stream = Nothing\n Dim fs As FileStream = Nothing\n Dim file As MemoryStream = Nothing\n\n Dim uri As New Uri(String.Format(\"http://forums.microsoft.com/forums/ShowPost.aspx?PostID=2992978&amp;SiteID=1\"))\n request = WebRequest.Create(uri)\n request.Timeout = 10000\n response = request.GetResponse\n s = response.GetResponseStream\n\n '2 - Receive file as memorystream\n Dim read(256) As Byte\n Dim count As Int32 = s.Read(read, 0, read.Length)\n File = New MemoryStream\n Do While (count &gt; 0)\n File.Write(read, 0, count)\n count = s.Read(read, 0, read.Length)\n Loop\n File.Position = 0\n 'Close responsestream\n s.Close()\n response.Close()\n\n '3 - Save file\n fs = New FileStream(\"c:\\test.html\", FileMode.CreateNew)\n count = file.Read(read, 0, read.Length)\n Do While (count &gt; 0)\n fs.Write(read, 0, count)\n count = file.Read(read, 0, read.Length)\n Loop\n fs.Close()\n File.Close()\n</code></pre>\n" }, { "answer_id": 4924357, "author": "Redwood", "author_id": 1512, "author_profile": "https://Stackoverflow.com/users/1512", "pm_score": 5, "selected": false, "text": "<p>There is a serious issue with SoloBold's <a href=\"https://stackoverflow.com/questions/179676/how-do-i-put-a-webresponse-into-a-memory-stream/179712#179712\">answer</a> that I discovered while testing it. When using it to read a file via an <code>FtpWebRequest</code> into a <code>MemoryStream</code> it intermittently failed to read the entire stream into memory. I tracked this down to <code>Peek()</code> sometimes returning -1 after the first 1460 bytes even though a <code>Read()</code> would have succeeded (the file was significantly larger than this). </p>\n\n<p>Instead I propose the solution below:</p>\n\n<pre><code>MemoryStream memStream;\nusing (Stream response = request.GetResponseStream()) {\n memStream = new MemoryStream();\n\n byte[] buffer = new byte[1024];\n int byteCount;\n do {\n byteCount = stream.Read(buffer, 0, buffer.Length);\n memStream.Write(buffer, 0, byteCount);\n } while (byteCount &gt; 0);\n}\n\n// If you're going to be reading from the stream afterwords you're going to want to seek back to the beginning.\nmemStream.Seek(0, SeekOrigin.Begin);\n\n// Use memStream as required\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
What is the best way to get a file (in this case, a .PDF, but any file will do) from a WebResponse and put it into a MemoryStream? Using .GetResponseStream() from WebResponse gets a Stream object, but if you want to convert that Stream to a specific type of stream, what do you do?
There is a serious issue with SoloBold's [answer](https://stackoverflow.com/questions/179676/how-do-i-put-a-webresponse-into-a-memory-stream/179712#179712) that I discovered while testing it. When using it to read a file via an `FtpWebRequest` into a `MemoryStream` it intermittently failed to read the entire stream into memory. I tracked this down to `Peek()` sometimes returning -1 after the first 1460 bytes even though a `Read()` would have succeeded (the file was significantly larger than this). Instead I propose the solution below: ``` MemoryStream memStream; using (Stream response = request.GetResponseStream()) { memStream = new MemoryStream(); byte[] buffer = new byte[1024]; int byteCount; do { byteCount = stream.Read(buffer, 0, buffer.Length); memStream.Write(buffer, 0, byteCount); } while (byteCount > 0); } // If you're going to be reading from the stream afterwords you're going to want to seek back to the beginning. memStream.Seek(0, SeekOrigin.Begin); // Use memStream as required ```
179,700
<p>Is there a way to take a class name and convert it to a string in C#? </p> <p>As part of the Entity Framework, the .Include method takes in a dot-delimited list of strings to join on when performing a query. I have the class model of what I want to join, and for reasons of refactoring and future code maintenance, I want to be able to have compile-time safety when referencing this class.</p> <p>Thus, is there a way that I could do this:</p> <pre><code>class Foo { } tblBar.Include ( Foo.GetType().ToString() ); </code></pre> <p>I don't think I can do GetType() without an instance. Any ideas?</p>
[ { "answer_id": 179711, "author": "Max Schmeling", "author_id": 3226, "author_profile": "https://Stackoverflow.com/users/3226", "pm_score": 7, "selected": false, "text": "<p>You can't use <code>.GetType()</code> without an instance because <code>GetType</code> is a method.</p>\n\n<p>You can get the name from the type though like this:</p>\n\n<pre><code>typeof(Foo).Name\n</code></pre>\n\n<p>And as pointed out by Chris, if you need the assembly qualified name you can use</p>\n\n<pre><code>typeof(Foo).AssemblyQualifiedName\n</code></pre>\n" }, { "answer_id": 179715, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 2, "selected": false, "text": "<pre><code>typeof(Foo).ToString()\n</code></pre>\n\n<p>?</p>\n" }, { "answer_id": 179724, "author": "Craig Stuntz", "author_id": 7714, "author_profile": "https://Stackoverflow.com/users/7714", "pm_score": 5, "selected": true, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/bb738708.aspx\" rel=\"noreferrer\">Include requires a property name</a>, not a class name. Hence, it's the name of the property you want, not the name of its type. <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx\" rel=\"noreferrer\">You can get that with reflection</a>.</p>\n" }, { "answer_id": 6711989, "author": "Albino", "author_id": 843267, "author_profile": "https://Stackoverflow.com/users/843267", "pm_score": 0, "selected": false, "text": "<p>You can use an <code>DbSet&lt;contact&gt;</code> instead of <code>ObjectSet&lt;contact&gt;</code>, so you can use lambda as a parameter, eg <code>tblBar.Include(a =&gt; a.foo)</code></p>\n" }, { "answer_id": 12692128, "author": "Glade Mellor", "author_id": 448675, "author_profile": "https://Stackoverflow.com/users/448675", "pm_score": 3, "selected": false, "text": "<p>You could also do something like this:</p>\n\n<pre><code>Type CLASS = typeof(MyClass);\n</code></pre>\n\n<p>And then you can just access the name, namespace, etc.</p>\n\n<pre><code> string CLASS_NAME = CLASS.Name;\n string NAMESPACE = CLASS.Namespace;\n</code></pre>\n" }, { "answer_id": 20080124, "author": "Gustavo Mori", "author_id": 556595, "author_profile": "https://Stackoverflow.com/users/556595", "pm_score": 0, "selected": false, "text": "<p>Another alternative using reflection, is to use the MethodBase class.</p>\n\n<p>In your example, you could add a static property (or method) that provides you with the info you want. Something like: </p>\n\n<pre><code>class Foo\n{\n public static string ClassName\n {\n get\n {\n return MethodBase.GetCurrentMethod().DeclaringType.Name;\n }\n }\n}\n</code></pre>\n\n<p>Which would allow you to use it without generating an instance of the type:</p>\n\n<pre><code>tblBar.Include(Foo.ClassName);\n</code></pre>\n\n<p>Which at runtime will give you:</p>\n\n<pre><code>tblBar.Include(\"Foo\");\n</code></pre>\n" }, { "answer_id": 71128769, "author": "Francesco Puglisi", "author_id": 579717, "author_profile": "https://Stackoverflow.com/users/579717", "pm_score": 2, "selected": false, "text": "<p>Alternatively to using <code>typeof(Foo).ToString()</code>, you could use <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/nameof\" rel=\"nofollow noreferrer\">nameof()</a>:</p>\n<pre><code>nameof(Foo)\n</code></pre>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179700", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24841/" ]
Is there a way to take a class name and convert it to a string in C#? As part of the Entity Framework, the .Include method takes in a dot-delimited list of strings to join on when performing a query. I have the class model of what I want to join, and for reasons of refactoring and future code maintenance, I want to be able to have compile-time safety when referencing this class. Thus, is there a way that I could do this: ``` class Foo { } tblBar.Include ( Foo.GetType().ToString() ); ``` I don't think I can do GetType() without an instance. Any ideas?
[Include requires a property name](http://msdn.microsoft.com/en-us/library/bb738708.aspx), not a class name. Hence, it's the name of the property you want, not the name of its type. [You can get that with reflection](http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx).
179,706
<p>I am writing a site that uses strongly typed datasets. </p> <p>The DBA who created the table made gave a column a value that represents a negative. The column is 'Do_Not_Estimate_Flag' where the column can contain 'T' or 'F'. I can't change the underlying table or the logic that fills it. What I want to do is to add a 'ESTIMATION_ALLOWED' column to the DataRow of my strongly typed DataSet. I have done this using the partial class that I can modify. (There is the autogenerated partial class and the non autogenerated partial class that I can safely modify.) The logic is in a property in the partial class. The trouble is that when the value is loaded ala </p> <pre><code>&lt;%#DataBinder.Eval(Container.DataItem, "ESTIMATION_ALLOWED")%&gt; </code></pre> <p>it goes straight to the underlying DataRow ignoring my property. How can I best achieve the desired result?</p> <p>here is my code:</p> <p>partial class MyFunkyDataTable {</p> <pre><code> private System.Data.DataColumn columnESTIMATION_ALLOWED; [System.Diagnostics.DebuggerNonUserCodeAttribute()] public System.Data.DataColumn ESTIMATION_ALLOWEDColumn { get { return columnESTIMATION_ALLOWED; } } public override void EndInit() { //init class columnESTIMATION_ALLOWED = new System.Data.DataColumn("ESTIMATION_ALLOWED", typeof(string), null, global::System.Data.MappingType.Element); Columns.Add(columnESTIMATION_ALLOWED); columnESTIMATION_ALLOWED.ReadOnly = true; //init Vars columnESTIMATION_ALLOWED = Columns["ESTIMATION_ALLOWED"]; base.EndInit(); } } partial class MyFunkyRow { public string ESTIMATION_ALLOWED { get { if(DO_NOT_EST_FLAG == "N") { return "Yes"; } return "No"; } } } </code></pre>
[ { "answer_id": 179820, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 2, "selected": true, "text": "<p>The DataBinder will see that you're binding to a DataRow and use its fields rather than any property you define. </p>\n\n<p>You could create a method to do what you want, e.g.:</p>\n\n<pre><code>&lt;%#FormatFlag(DataBinder.Eval(Container.DataItem, \"Do_Not_Estimate_Flag\" ))%&gt;\n</code></pre>\n\n<p>where you have a method:</p>\n\n<pre><code>protected string FormatFlag(object doNotEstimateFlag)\n{\n if (doNotEstimateFlag.ToString() == \"N\") return \"Yes\";\n return \"No\";\n} \n</code></pre>\n\n<p>An alternative is to modify the query that fills your DataTable. For example, you could have a column \"ESTIMATE_ALLOWED\" in your typed dataset. The query that fills it would look something like the following (database dependent, this is for SQL Server):</p>\n\n<pre><code>SELECT\n ...\n CASE WHEN Do_Not_Estimate_Flag = 'N' THEN 'Yes' ELSE 'No' END ESTIMATE_ALLOWED,\n ...\nFROM\n ...\n</code></pre>\n" }, { "answer_id": 3390948, "author": "Brady Moritz", "author_id": 177242, "author_profile": "https://Stackoverflow.com/users/177242", "pm_score": 0, "selected": false, "text": "<p>If I recall, ST datasets datarows are implemented in partial classes. So you might add the functionality you need in the partial class off the main ST dataset row class. </p>\n" } ]
2008/10/07
[ "https://Stackoverflow.com/questions/179706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4491/" ]
I am writing a site that uses strongly typed datasets. The DBA who created the table made gave a column a value that represents a negative. The column is 'Do\_Not\_Estimate\_Flag' where the column can contain 'T' or 'F'. I can't change the underlying table or the logic that fills it. What I want to do is to add a 'ESTIMATION\_ALLOWED' column to the DataRow of my strongly typed DataSet. I have done this using the partial class that I can modify. (There is the autogenerated partial class and the non autogenerated partial class that I can safely modify.) The logic is in a property in the partial class. The trouble is that when the value is loaded ala ``` <%#DataBinder.Eval(Container.DataItem, "ESTIMATION_ALLOWED")%> ``` it goes straight to the underlying DataRow ignoring my property. How can I best achieve the desired result? here is my code: partial class MyFunkyDataTable { ``` private System.Data.DataColumn columnESTIMATION_ALLOWED; [System.Diagnostics.DebuggerNonUserCodeAttribute()] public System.Data.DataColumn ESTIMATION_ALLOWEDColumn { get { return columnESTIMATION_ALLOWED; } } public override void EndInit() { //init class columnESTIMATION_ALLOWED = new System.Data.DataColumn("ESTIMATION_ALLOWED", typeof(string), null, global::System.Data.MappingType.Element); Columns.Add(columnESTIMATION_ALLOWED); columnESTIMATION_ALLOWED.ReadOnly = true; //init Vars columnESTIMATION_ALLOWED = Columns["ESTIMATION_ALLOWED"]; base.EndInit(); } } partial class MyFunkyRow { public string ESTIMATION_ALLOWED { get { if(DO_NOT_EST_FLAG == "N") { return "Yes"; } return "No"; } } } ```
The DataBinder will see that you're binding to a DataRow and use its fields rather than any property you define. You could create a method to do what you want, e.g.: ``` <%#FormatFlag(DataBinder.Eval(Container.DataItem, "Do_Not_Estimate_Flag" ))%> ``` where you have a method: ``` protected string FormatFlag(object doNotEstimateFlag) { if (doNotEstimateFlag.ToString() == "N") return "Yes"; return "No"; } ``` An alternative is to modify the query that fills your DataTable. For example, you could have a column "ESTIMATE\_ALLOWED" in your typed dataset. The query that fills it would look something like the following (database dependent, this is for SQL Server): ``` SELECT ... CASE WHEN Do_Not_Estimate_Flag = 'N' THEN 'Yes' ELSE 'No' END ESTIMATE_ALLOWED, ... FROM ... ```