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 |
|---|---|---|---|---|---|---|
43,778 | <p><strong>Update:</strong> Check out this follow-up question: <a href="https://stackoverflow.com/questions/134581/gem-update-on-windows-is-it-broken"><strong>Gem Update on Windows - is it broken?</strong></a></p>
<hr>
<p>On Windows, when I do this:</p>
<pre><code>gem install sqlite3-ruby
</code></pre>
<p>I get the following error:</p>
<pre><code>Building native extensions. This could take a while...
ERROR: Error installing sqlite3-ruby:
ERROR: Failed to build gem native extension.
c:/ruby/bin/ruby.exe extconf.rb install sqlite3-ruby --platform Win32
checking for fdatasync() in rt.lib... no
checking for sqlite3.h... no
nmake
'nmake' is not recognized as an internal or external command,
operable program or batch file.
Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4 for inspection.
Results logged to c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4/ext/sqlite3_api/gem_make.out
</code></pre>
<p><strong>Same thing happens with the hpricot gem</strong>. I seem to remember these gems installed just fine on < 1.0 gems, but now I'm on 1.2.0, things have gone screwy.</p>
<p>I have also tried this:</p>
<pre><code>gem install sqlite3-ruby --platform Win32
</code></pre>
<p>Needless to say, this doesn't work either (same error)</p>
<p>Does anyone know what is going on here and how to fix this?</p>
<hr>
<p><strong>Update:</strong> Check out this follow-up question: <a href="https://stackoverflow.com/questions/134581/gem-update-on-windows-is-it-broken"><strong>Gem Update on Windows - is it broken?</strong></a></p>
| [
{
"answer_id": 43804,
"author": "Nathan Fritz",
"author_id": 4142,
"author_profile": "https://Stackoverflow.com/users/4142",
"pm_score": 2,
"selected": false,
"text": "<p>Is it possible that the newest version has not yet been ported to Win32 yet? Since this particular gem does have bind... | 2008/09/04 | [
"https://Stackoverflow.com/questions/43778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1944/"
] | **Update:** Check out this follow-up question: [**Gem Update on Windows - is it broken?**](https://stackoverflow.com/questions/134581/gem-update-on-windows-is-it-broken)
---
On Windows, when I do this:
```
gem install sqlite3-ruby
```
I get the following error:
```
Building native extensions. This could take a while...
ERROR: Error installing sqlite3-ruby:
ERROR: Failed to build gem native extension.
c:/ruby/bin/ruby.exe extconf.rb install sqlite3-ruby --platform Win32
checking for fdatasync() in rt.lib... no
checking for sqlite3.h... no
nmake
'nmake' is not recognized as an internal or external command,
operable program or batch file.
Gem files will remain installed in c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4 for inspection.
Results logged to c:/ruby/lib/ruby/gems/1.8/gems/sqlite3-ruby-1.2.4/ext/sqlite3_api/gem_make.out
```
**Same thing happens with the hpricot gem**. I seem to remember these gems installed just fine on < 1.0 gems, but now I'm on 1.2.0, things have gone screwy.
I have also tried this:
```
gem install sqlite3-ruby --platform Win32
```
Needless to say, this doesn't work either (same error)
Does anyone know what is going on here and how to fix this?
---
**Update:** Check out this follow-up question: [**Gem Update on Windows - is it broken?**](https://stackoverflow.com/questions/134581/gem-update-on-windows-is-it-broken) | As Nathan suggests, this does appear to be related to the fact that the latest versions of the sqlite3-ruby and hpricot gems don't appear to have Windows versions. Here's what to do when faced with this situation (note, the name of the gem is automatically wildcarded, so you can type just *sql* and get a list of all gems beginning with *sql*):
```
$ gem list --remote --all sqlite
*** REMOTE GEMS ***
sqlite (2.0.1, 2.0.0, 1.3.1, 1.3.0, 1.2.9.1, 1.2.0, 1.1.3, 1.1.2, 1.1.1, 1.1)
sqlite-ruby (2.2.3, 2.2.2, 2.2.1, 2.2.0, 2.1.0, 2.0.3, 2.0.2)
sqlite3-ruby (1.2.4, 1.2.3, 1.2.2, 1.2.1, 1.2.0, 1.1.0, 1.0.1, 1.0.0, 0.9.0, 0.6.0, 0.5.0)
```
Then you can choose the version you would like to install:
```
gem install sqlite3-ruby -v 1.2.3
```
To successfully install hpricot, I did this:
```
gem install hpricot -v 0.6
```
Annoyingly, doing a **`gem update`** tries to update the gems to their latest, broken-on-Windows, versions. When the update routine encounters an error, it ditches you out of the whole process. There's a (hacky) solution to this problem **[here](https://stackoverflow.com/questions/134581/gem-update-on-windows-is-it-broken)**.
**So, is this issue a bug in gems? Should gems not automatically detect the platform and install the latest compatible version?** |
43,802 | <p>I have a <code>String</code> representation of a date that I need to create a <code>Date</code> or <code>Calendar</code> object from. I've looked through <code>Date</code> and <code>Calendar</code> APIs but haven't found anything that can do this other than creating my own ugly parse method. I know there must be a way, does anyone know of a solution?</p>
| [
{
"answer_id": 43806,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>DateFormat.parse(String)\n</code></pre>\n"
},
{
"answer_id": 43807,
"author": "M... | 2008/09/04 | [
"https://Stackoverflow.com/questions/43802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2628/"
] | I have a `String` representation of a date that I need to create a `Date` or `Calendar` object from. I've looked through `Date` and `Calendar` APIs but haven't found anything that can do this other than creating my own ugly parse method. I know there must be a way, does anyone know of a solution? | In brief:
```
DateFormat formatter = new SimpleDateFormat("MM/dd/yy");
try {
Date date = formatter.parse("01/29/02");
} catch (ParseException e) {
e.printStackTrace();
}
```
See [`SimpleDateFormat` javadoc](http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html) for more.
And to turn it into a `Calendar`, do:
```
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
``` |
43,803 | <p>This is what I've got. It works. But, is there a simpler or better way?</p>
<p>ASPX Page…</p>
<pre><code><asp:Repeater ID="RepeaterBooks" runat="server">
<HeaderTemplate>
<table class="report">
<tr>
<th>Published</th>
<th>Title</th>
<th>Author</th>
<th>Price</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:Literal ID="LiteralPublished" runat="server" /></td>
<td><asp:Literal ID="LiteralTitle" runat="server" /></td>
<td><asp:Literal ID="LiteralAuthor" runat="server" /></td>
<td><asp:Literal ID="LiteralPrice" runat="server" /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</code></pre>
<p>ASPX.VB Code Behind…</p>
<pre><code>Protected Sub Page_Load( ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim db As New BookstoreDataContext
RepeaterBooks.DataSource = From b In db.Books _
Order By b.Published _
Select b
RepeaterBooks.DataBind()
End Sub
Sub RepeaterBooks_ItemDataBound( ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles RepeaterBooks.ItemDataBound
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Dim b As Book = DirectCast(e.Item.DataItem, Book)
DirectCast(e.Item.FindControl("LiteralPublished"), Literal).Text = "<nobr>" + b.Published.ToShortDateString + "</nobr>"
DirectCast(e.Item.FindControl("LiteralTitle"), Literal).Text = "<nobr>" + TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Title)) + "</nobr>"
DirectCast(e.Item.FindControl("LiteralAuthor"), Literal).Text = "<nobr>" + TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Author)) + "</nobr>"
DirectCast(e.Item.FindControl("LiteralPrice"), Literal).Text = "<nobr>" + Format(b.Price, "c") + "</nobr>"
End If
End Sub
Function TryNbsp(ByVal s As String) As String
If s = "" Then
Return "&nbsp;"
Else
Return s
End If
End Function
</code></pre>
| [
{
"answer_id": 43818,
"author": "Geoff",
"author_id": 1097,
"author_profile": "https://Stackoverflow.com/users/1097",
"pm_score": 2,
"selected": false,
"text": "<p>In .Net 3.0+ you can replace your ItemDataBound to the asp:Literal by doing something like this:</p>\n\n<pre><code><ItemT... | 2008/09/04 | [
"https://Stackoverflow.com/questions/43803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | This is what I've got. It works. But, is there a simpler or better way?
ASPX Page…
```
<asp:Repeater ID="RepeaterBooks" runat="server">
<HeaderTemplate>
<table class="report">
<tr>
<th>Published</th>
<th>Title</th>
<th>Author</th>
<th>Price</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:Literal ID="LiteralPublished" runat="server" /></td>
<td><asp:Literal ID="LiteralTitle" runat="server" /></td>
<td><asp:Literal ID="LiteralAuthor" runat="server" /></td>
<td><asp:Literal ID="LiteralPrice" runat="server" /></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
```
ASPX.VB Code Behind…
```
Protected Sub Page_Load( ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim db As New BookstoreDataContext
RepeaterBooks.DataSource = From b In db.Books _
Order By b.Published _
Select b
RepeaterBooks.DataBind()
End Sub
Sub RepeaterBooks_ItemDataBound( ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles RepeaterBooks.ItemDataBound
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
Dim b As Book = DirectCast(e.Item.DataItem, Book)
DirectCast(e.Item.FindControl("LiteralPublished"), Literal).Text = "<nobr>" + b.Published.ToShortDateString + "</nobr>"
DirectCast(e.Item.FindControl("LiteralTitle"), Literal).Text = "<nobr>" + TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Title)) + "</nobr>"
DirectCast(e.Item.FindControl("LiteralAuthor"), Literal).Text = "<nobr>" + TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Author)) + "</nobr>"
DirectCast(e.Item.FindControl("LiteralPrice"), Literal).Text = "<nobr>" + Format(b.Price, "c") + "</nobr>"
End If
End Sub
Function TryNbsp(ByVal s As String) As String
If s = "" Then
Return " "
Else
Return s
End If
End Function
``` | @Geoff
That sort of Eval statement was actually added in 2.0, but if performance is important Eval should be avoided since it uses Reflection.
The repeater is a pretty good way of doing it, although it might be faster to generate the table in code:
ASPX Page:
```
<table class="report" id="bookTable" runat="server">
<tr>
<th>Published</th>
<th>Title</th>
<th>Author</th>
<th>Price</th>
</tr>
</table>
```
Code Behind:
```
Protected Sub Page_Load( ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostback Then
BuildTable()
End If
End Sub
Private Sub BuildTable()
Dim db As New BookstoreDataContext
Dim bookCollection = from b in db.Books _
Order By b.Published _
Select b
Dim row As HtmlTableRow
Dim cell As HtmlTableCell
For Each book As Books In bookCollection
row = New HtmlTableRow()
cell = New HtmlTableCell With { .InnerText = b.Published.ToShortDateString }
row.Controls.Add(cell)
cell = New HtmlTableCell With { .InnerText = TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Title)) }
row.Controls.Add(cell)
cell = New HtmlTableCell With { .InnerText = TryNbsp(HttpContext.Current.Server.HtmlEncode(b.Author))
row.Controls.Add(cell)
cell = New HtmlTableCell With { .InnerText = Format(b.Price, "c") }
row.Controls.Add(cell)
bookTable.Controls.Add(row)
Next
```
I guess it depends on how important speed is to you. For simplicity's sake I think I would go with the Repeater. |
43,808 | <p>I have a distributed Java application running on 5 application servers. The servers all use the same Oracle 9i database running on a 6th machine.</p>
<p>The application need to prefetch a batch of 100 IDs from a sequence. It's relatively easy to do in a single-threaded, non-distributed environment, you can just issue these queries:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT seq.nextval FROM dual;
ALTER SEQUENCE seq INCREMENT BY 100;
SELECT seq.nextval FROM dual;
</code></pre>
<p>The first select fetches the first sequence ID that the application can use, the second select returns the last one that can be used.</p>
<p>Things get way more interesting in a multithreaded environment. You can't be sure that before the second select another thread doesn't increase the sequence by 100 again. This issue can be solved by synchronizing the access on the Java side - you only let one thread begin fetching the IDs at one time.</p>
<p>The situation becomes really hard when you can't synchronize because parts of the application doesn't run on the same JVM, not even on the same physical machine. I found some references on forums that others have problems with solving this problem too, but none of the answers are really working not to mention being reasonable.</p>
<p>Can the community provide a solution for this problem?</p>
<p>Some more information:</p>
<ul>
<li>I can't really play with the transaction isolation levels. I use JPA and the change would affect the entire application, not only the prefetching queries and that's not acceptable for me.</li>
<li><p>On PostgreSQL I could do the following:
<code>SELECT setval('seq', NEXTVAL('seq') + n - 1)</code></p></li>
<li><p>The solution by Matthew works when you can use a fixed increment value (which is perfectly acceptable in my case). However is there a solution when you don't want to fix the size of the increment, but want to adjust it dynamically?</p></li>
</ul>
| [
{
"answer_id": 43830,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 5,
"selected": true,
"text": "<p>Why not just have the sequence as increment by 100 all the time? each \"nextval\" gives you 100 sequence numbers to ... | 2008/09/04 | [
"https://Stackoverflow.com/questions/43808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/686/"
] | I have a distributed Java application running on 5 application servers. The servers all use the same Oracle 9i database running on a 6th machine.
The application need to prefetch a batch of 100 IDs from a sequence. It's relatively easy to do in a single-threaded, non-distributed environment, you can just issue these queries:
```sql
SELECT seq.nextval FROM dual;
ALTER SEQUENCE seq INCREMENT BY 100;
SELECT seq.nextval FROM dual;
```
The first select fetches the first sequence ID that the application can use, the second select returns the last one that can be used.
Things get way more interesting in a multithreaded environment. You can't be sure that before the second select another thread doesn't increase the sequence by 100 again. This issue can be solved by synchronizing the access on the Java side - you only let one thread begin fetching the IDs at one time.
The situation becomes really hard when you can't synchronize because parts of the application doesn't run on the same JVM, not even on the same physical machine. I found some references on forums that others have problems with solving this problem too, but none of the answers are really working not to mention being reasonable.
Can the community provide a solution for this problem?
Some more information:
* I can't really play with the transaction isolation levels. I use JPA and the change would affect the entire application, not only the prefetching queries and that's not acceptable for me.
* On PostgreSQL I could do the following:
`SELECT setval('seq', NEXTVAL('seq') + n - 1)`
* The solution by Matthew works when you can use a fixed increment value (which is perfectly acceptable in my case). However is there a solution when you don't want to fix the size of the increment, but want to adjust it dynamically? | Why not just have the sequence as increment by 100 all the time? each "nextval" gives you 100 sequence numbers to work with
```
SQL> create sequence so_test start with 100 increment by 100 nocache;
Sequence created.
SQL> select so_test.nextval - 99 as first_seq, so_test.currval as last_seq from dual;
FIRST_SEQ LAST_SEQ
---------- ----------
1 100
SQL> /
FIRST_SEQ LAST_SEQ
---------- ----------
101 200
SQL> /
FIRST_SEQ LAST_SEQ
---------- ----------
201 300
SQL>
```
A note on your example.. Watch out for DDL.. It will produce an implicit commit
**Example of commit produced by DDL**
```
SQL> select * from xx;
no rows selected
SQL> insert into xx values ('x');
1 row created.
SQL> alter sequence so_test increment by 100;
Sequence altered.
SQL> rollback;
Rollback complete.
SQL> select * from xx;
Y
-----
x
SQL>
``` |
43,819 | <p>We are now using NHibernate to connect to different database base on where our software is installed. So I am porting many SQL Procedures to Oracle.</p>
<p>SQL Server has a nice function called DateDiff which takes a date part, startdate and enddate.</p>
<p>Date parts examples are day, week, month, year, etc. . . </p>
<p>What is the Oracle equivalent?</p>
<p>I have not found one do I have to create my own version of it?</p>
<p><strong>(update by Mark Harrison)</strong> there are several nice answers that explain Oracle date arithmetic. If you need an Oracle datediff() see Einstein's answer. (I need this to keep spme SQL scripts compatible between Sybase and Oracle.) Note that this question applies equally to Sybase.</p>
| [
{
"answer_id": 44597,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Tom's article is very old. It only discusses the DATE type. If you use TIMESTAMP types then date arithmetic is built into ... | 2008/09/04 | [
"https://Stackoverflow.com/questions/43819",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
] | We are now using NHibernate to connect to different database base on where our software is installed. So I am porting many SQL Procedures to Oracle.
SQL Server has a nice function called DateDiff which takes a date part, startdate and enddate.
Date parts examples are day, week, month, year, etc. . .
What is the Oracle equivalent?
I have not found one do I have to create my own version of it?
**(update by Mark Harrison)** there are several nice answers that explain Oracle date arithmetic. If you need an Oracle datediff() see Einstein's answer. (I need this to keep spme SQL scripts compatible between Sybase and Oracle.) Note that this question applies equally to Sybase. | I stole most of this from an old tom article a few years ago, fixed some bugs from the article and cleaned it up. The demarcation lines for datediff are calculated differently between oracle and MSSQL so you have to be careful with some examples floating around out there that don't properly account for MSSQL/Sybase style boundaries which do not provide fractional results.
With the following you should be able to use MSSQL syntax and get the same results as MSSQL such as SELECT DATEDIFF(dd,getdate(),DATEADD(dd,5,getdate())) FROM DUAL;
I claim only that it works - not that its effecient or the best way to do it. I'm not an Oracle person :) And you might want to think twice about using my function macros to workaround needing quotes around dd,mm,hh,mi..etc.
**(update by Mark Harrison)** added dy function as alias for dd.
```
CREATE OR REPLACE FUNCTION GetDate
RETURN date IS today date;
BEGIN
RETURN(sysdate);
END;
/
CREATE OR REPLACE FUNCTION mm RETURN VARCHAR2 IS BEGIN RETURN('mm'); END;
/
CREATE OR REPLACE FUNCTION yy RETURN VARCHAR2 IS BEGIN RETURN('yyyy'); END;
/
CREATE OR REPLACE FUNCTION dd RETURN VARCHAR2 IS BEGIN RETURN('dd'); END;
/
CREATE OR REPLACE FUNCTION dy RETURN VARCHAR2 IS BEGIN RETURN('dd'); END;
/
CREATE OR REPLACE FUNCTION hh RETURN VARCHAR2 IS BEGIN RETURN('hh'); END;
/
CREATE OR REPLACE FUNCTION mi RETURN VARCHAR2 IS BEGIN RETURN('mi'); END;
/
CREATE OR REPLACE FUNCTION ss RETURN VARCHAR2 IS BEGIN RETURN('ss'); END;
/
CREATE OR REPLACE Function DateAdd(date_type IN varchar2, offset IN integer, date_in IN date )
RETURN date IS date_returned date;
BEGIN
date_returned := CASE date_type
WHEN 'mm' THEN add_months(date_in,TRUNC(offset))
WHEN 'yyyy' THEN add_months(date_in,TRUNC(offset) * 12)
WHEN 'dd' THEN date_in + TRUNC(offset)
WHEN 'hh' THEN date_in + (TRUNC(offset) / 24)
WHEN 'mi' THEN date_in + (TRUNC(offset) /24/60)
WHEN 'ss' THEN date_in + (TRUNC(offset) /24/60/60)
END;
RETURN(date_returned);
END;
/
CREATE OR REPLACE Function DateDiff( return_type IN varchar2, date_1 IN date, date_2 IN date)
RETURN integer IS number_return integer;
BEGIN
number_return := CASE return_type
WHEN 'mm' THEN ROUND(MONTHS_BETWEEN(TRUNC(date_2,'MM'),TRUNC(date_1, 'MM')))
WHEN 'yyyy' THEN ROUND(MONTHS_BETWEEN(TRUNC(date_2,'YYYY'), TRUNC(date_1, 'YYYY')))/12
WHEN 'dd' THEN ROUND((TRUNC(date_2,'DD') - TRUNC(date_1, 'DD')))
WHEN 'hh' THEN (TRUNC(date_2,'HH') - TRUNC(date_1,'HH')) * 24
WHEN 'mi' THEN (TRUNC(date_2,'MI') - TRUNC(date_1,'MI')) * 24 * 60
WHEN 'ss' THEN (date_2 - date_1) * 24 * 60 * 60
END;
RETURN(number_return);
END;
/
``` |
43,832 | <p>I think I might be missing something here. Here is the relevant part of the trigger:</p>
<pre><code> CURSOR columnNames (inTableName IN VARCHAR2) IS
SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = inTableName;
/* Removed for brevity */
OPEN columnNames('TEMP');
</code></pre>
<p>And here is the error message that I'm getting back,</p>
<pre>
27/20 PLS-00306: wrong number or types of arguments in call to 'COLUMNNAMES'
27/2 PL/SQL: Statement ignored
</pre>
<p>If I am understanding the documentation correctly, that should work, but since it is not I must be doing something wrong. Any ideas?</p>
<hr />
<p>@<a href="https://stackoverflow.com/questions/43832/pls-00306-error-on-call-to-cursor#43859">Matthew</a> - I appreciate the help, but the reason that I am confused is because this bit of code isn't working for me and is raising the errors referenced. We have other triggers in the database with code almost exactly the as that so I'm not sure if it is something that I did wrong, or something with how I am trying to store the trigger, etc.</p>
<hr />
<p>@<a href="https://stackoverflow.com/questions/43832/pls-00306-error-on-call-to-cursor#43859">Matthew</a> - Well, now I get to feel embarrassed. I did a copy/paste of the code that you provided into a new trigger and it worked fine. So I went back into the original trigger and tried it and received the error message again, except this time I started to delete stuff out of the trigger and after getting rid of this line,</p>
<pre><code>FOR columnName IN columnNames LOOP
</code></pre>
<p>Things saved fine. So it turns out that where I thought the error was, wasn't actually were the error was.</p>
| [
{
"answer_id": 43859,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 1,
"selected": false,
"text": "<p>Works fine for me.</p>\n\n<pre><code>create or replace procedure so_test_procedure as \n CURSOR columnNames (inTabl... | 2008/09/04 | [
"https://Stackoverflow.com/questions/43832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1185/"
] | I think I might be missing something here. Here is the relevant part of the trigger:
```
CURSOR columnNames (inTableName IN VARCHAR2) IS
SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME = inTableName;
/* Removed for brevity */
OPEN columnNames('TEMP');
```
And here is the error message that I'm getting back,
```
27/20 PLS-00306: wrong number or types of arguments in call to 'COLUMNNAMES'
27/2 PL/SQL: Statement ignored
```
If I am understanding the documentation correctly, that should work, but since it is not I must be doing something wrong. Any ideas?
---
@[Matthew](https://stackoverflow.com/questions/43832/pls-00306-error-on-call-to-cursor#43859) - I appreciate the help, but the reason that I am confused is because this bit of code isn't working for me and is raising the errors referenced. We have other triggers in the database with code almost exactly the as that so I'm not sure if it is something that I did wrong, or something with how I am trying to store the trigger, etc.
---
@[Matthew](https://stackoverflow.com/questions/43832/pls-00306-error-on-call-to-cursor#43859) - Well, now I get to feel embarrassed. I did a copy/paste of the code that you provided into a new trigger and it worked fine. So I went back into the original trigger and tried it and received the error message again, except this time I started to delete stuff out of the trigger and after getting rid of this line,
```
FOR columnName IN columnNames LOOP
```
Things saved fine. So it turns out that where I thought the error was, wasn't actually were the error was. | To clarify the cause of the issue. As you state
**OPEN columnNames('TEMP');**
worked while
**FOR columnName IN columnNames LOOP**
did not. The FOR statement would work fine if it also included the parameter like so:
**FOR columnName IN columnNames('TEMP') LOOP**
You don't show the code where you fetch the rows so I can't tell your purpose, but where I work OPEN is commonly used to fetch the first row (in this case, the first column name of the given table) while the FOR is used to iterate through all returned rows.
@Rob's comment. I'm not allowed to comment so updating here instead. The missing parameter is what I describe above. You added a response stating you simply deleted the FOR loop. It did not look like you, at the time, understood why deleting it made a difference. Which is why I attempted to explain since, depending on your need, the FOR loop might be a better solution. |
43,842 | <p>I have a string that contains the representation of a date. It looks like: </p>
<p><strong>Thu Nov 30 19:00:00 EST 2006</strong></p>
<p>I'm trying to create a Date object using SimpleDateFormat and have 2 problems. </p>
<p>1.) I can't figure out the pattern to hard-code the solution into the SimpleDateFormat constructor</p>
<p>2.) I can't find a way I could parse the string using API to determine the pattern so I could reuse this for different patterns of date output </p>
<p>If anyone knows a solution using API or a custom solution I would greatly appreciate it.</p>
| [
{
"answer_id": 43849,
"author": "alexmcchessers",
"author_id": 998,
"author_profile": "https://Stackoverflow.com/users/998",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure there's any easy way to parse a date and work out its pattern, but I would have thought that the pattern... | 2008/09/04 | [
"https://Stackoverflow.com/questions/43842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2628/"
] | I have a string that contains the representation of a date. It looks like:
**Thu Nov 30 19:00:00 EST 2006**
I'm trying to create a Date object using SimpleDateFormat and have 2 problems.
1.) I can't figure out the pattern to hard-code the solution into the SimpleDateFormat constructor
2.) I can't find a way I could parse the string using API to determine the pattern so I could reuse this for different patterns of date output
If anyone knows a solution using API or a custom solution I would greatly appreciate it. | The format to pass to SimpleDateFormat could be looked up at <http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html>
```
new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy")
```
As for your second question, I don't know of any Java library to figure out a date format and parse it without knowing in advance what the format is. |
43,870 | <p>I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table:</p>
<pre><code>ID COMPANY_ID EMPLOYEE
1 1 Anna
2 1 Bill
3 2 Carol
4 2 Dave
</code></pre>
<p>and I wanted to group by company_id to get something like:</p>
<pre><code>COMPANY_ID EMPLOYEE
1 Anna, Bill
2 Carol, Dave
</code></pre>
<p>There is a built-in function in mySQL to do this <a href="http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat" rel="noreferrer">group_concat</a></p>
| [
{
"answer_id": 43889,
"author": "Guy C",
"author_id": 4045,
"author_profile": "https://Stackoverflow.com/users/4045",
"pm_score": 4,
"selected": false,
"text": "<p>I claim no credit for the answer because I found it after some searching:</p>\n\n<p>What I didn't know is that PostgreSQL al... | 2008/09/04 | [
"https://Stackoverflow.com/questions/43870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4045/"
] | I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table:
```
ID COMPANY_ID EMPLOYEE
1 1 Anna
2 1 Bill
3 2 Carol
4 2 Dave
```
and I wanted to group by company\_id to get something like:
```
COMPANY_ID EMPLOYEE
1 Anna, Bill
2 Carol, Dave
```
There is a built-in function in mySQL to do this [group\_concat](http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat) | ### PostgreSQL 9.0 or later:
Modern Postgres (since 2010) has the [`string_agg(expression, delimiter)`](http://www.postgresql.org/docs/current/static/functions-aggregate.html#FUNCTIONS-AGGREGATE-TABLE) function which will do exactly what the asker was looking for:
```
SELECT company_id, string_agg(employee, ', ')
FROM mytable
GROUP BY company_id;
```
Postgres 9 also added the ability to specify an `ORDER BY` clause [in any aggregate expression](https://www.postgresql.org/docs/current/static/sql-expressions.html#SYNTAX-AGGREGATES); otherwise you have to order all your results or deal with an undefined order. So you can now write:
```
SELECT company_id, string_agg(employee, ', ' ORDER BY employee)
FROM mytable
GROUP BY company_id;
```
### PostgreSQL 8.4.x:
PostgreSQL 8.4 (in 2009) introduced [the aggregate function `array_agg(expression)`](http://www.postgresql.org/docs/8.4/interactive/functions-aggregate.html "array_agg(expression)") which collects the values in an array. Then `array_to_string()` can be used to give the desired result:
```
SELECT company_id, array_to_string(array_agg(employee), ', ')
FROM mytable
GROUP BY company_id;
```
### PostgreSQL 8.3.x and older:
When this question was originally posed, there was no built-in aggregate function to concatenate strings. The simplest custom implementation ([suggested by Vajda Gabo in this mailing list post](http://archives.postgresql.org/pgsql-novice/2003-09/msg00177.php), among many others) is to use the built-in `textcat` function (which lies behind the `||` operator):
```
CREATE AGGREGATE textcat_all(
basetype = text,
sfunc = textcat,
stype = text,
initcond = ''
);
```
[Here is the `CREATE AGGREGATE` documentation.](http://www.postgresql.org/docs/8.3/static/sql-createaggregate.html)
This simply glues all the strings together, with no separator. In order to get a ", " inserted in between them without having it at the end, you might want to make your own concatenation function and substitute it for the "textcat" above. Here is one I put together and tested on 8.3.12:
```
CREATE FUNCTION commacat(acc text, instr text) RETURNS text AS $$
BEGIN
IF acc IS NULL OR acc = '' THEN
RETURN instr;
ELSE
RETURN acc || ', ' || instr;
END IF;
END;
$$ LANGUAGE plpgsql;
```
This version will output a comma even if the value in the row is null or empty, so you get output like this:
```
a, b, c, , e, , g
```
If you would prefer to remove extra commas to output this:
```
a, b, c, e, g
```
Then add an `ELSIF` check to the function like this:
```
CREATE FUNCTION commacat_ignore_nulls(acc text, instr text) RETURNS text AS $$
BEGIN
IF acc IS NULL OR acc = '' THEN
RETURN instr;
ELSIF instr IS NULL OR instr = '' THEN
RETURN acc;
ELSE
RETURN acc || ', ' || instr;
END IF;
END;
$$ LANGUAGE plpgsql;
``` |
43,874 | <p>I have a multiple selection SELECT field which I don't want the end user to be able to change the value of. </p>
<p>For UI reasons, I would like to be able to do this without using the disabled="true" attribute. I've tried using onmousedown, onfocus, onclick and setting each to blur or return false but with no success.</p>
<p>Can this be done or am I trying to do the impossible?</p>
| [
{
"answer_id": 43880,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 2,
"selected": false,
"text": "<p>Could you do it with an <code>onchange</code> event?</p>\n\n<pre><code><select onfocus=\"this.oldIndex=this.sele... | 2008/09/04 | [
"https://Stackoverflow.com/questions/43874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1980/"
] | I have a multiple selection SELECT field which I don't want the end user to be able to change the value of.
For UI reasons, I would like to be able to do this without using the disabled="true" attribute. I've tried using onmousedown, onfocus, onclick and setting each to blur or return false but with no success.
Can this be done or am I trying to do the impossible? | I know you mentioned that you don't want to, but I actually think that using the `disabled` attribute is a better solution:
```
<select multiple="multiple">
<option value="volvo" selected="true" disabled="disabled">Volvo</option>
<option value="saab" disabled="disabled">Saab</option>
<option value="opel" disabled="disabled">Opel</option>
<option value="audi" disabled="disabled">Audi</option>
</select>
```
If necessary, you can always give the `select` a `class` and style it with CSS. This solution will work in all browsers regardless of scripting capabilities. |
43,890 | <p><strong>Original Question</strong></p>
<p>I want to be able to generate a new (fully valid) MP3 file from an existing MP3 file to be used as a preview -- try-before-you-buy style. The new file should only contain the first <em>n</em> seconds of the track.</p>
<p>Now, I know I could just "chop the stream" at <em>n</em> seconds (calculating from the bitrate and header size) when delivering the file, but this is a bit dirty and a real PITA on a VBR track. I'd like to be able to generate a proper MP3 file.</p>
<p>Anyone any ideas?</p>
<p><strong>Answers</strong></p>
<p>Both <code>mp3split</code> and <code>ffmpeg</code> are both good solutions. I chose ffmpeg as it is commonly installed on linux servers and is also <a href="http://sourceforge.net/project/showfiles.php?group_id=205275&package_id=248632" rel="noreferrer">easily available for windows</a>. Here's some more good command line parameters for generating previews with ffmpeg</p>
<ul>
<li><strong><code>-t <seconds></code></strong> chop after specified number of seconds</li>
<li><strong><code>-y</code></strong> force file overwrite</li>
<li><strong><code>-ab <bitrate></code></strong> set bitrate e.g. <em>-ab 96k</em></li>
<li><strong><code>-ar <rate Hz></code></strong> set sampling rate e.g. <em>-ar 22050</em> for 22.05kHz</li>
<li><strong><code>-map_meta_data <outfile>:<infile></code></strong> copy track metadata from infile to outfile</li>
</ul>
<p>instead of setting -ab and -ar, you can copy the original track settings, as Tim Farley suggests, with:</p>
<ul>
<li><strong><code>-acodec copy</code></strong></li>
</ul>
| [
{
"answer_id": 43912,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 4,
"selected": false,
"text": "<p>try:</p>\n\n<pre><code>ffmpeg -t 30 -i inputfile.mp3 outputfile.mp3\n</code></pre>\n"
},
{
"answer_id": 43914,
... | 2008/09/04 | [
"https://Stackoverflow.com/questions/43890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1820/"
] | **Original Question**
I want to be able to generate a new (fully valid) MP3 file from an existing MP3 file to be used as a preview -- try-before-you-buy style. The new file should only contain the first *n* seconds of the track.
Now, I know I could just "chop the stream" at *n* seconds (calculating from the bitrate and header size) when delivering the file, but this is a bit dirty and a real PITA on a VBR track. I'd like to be able to generate a proper MP3 file.
Anyone any ideas?
**Answers**
Both `mp3split` and `ffmpeg` are both good solutions. I chose ffmpeg as it is commonly installed on linux servers and is also [easily available for windows](http://sourceforge.net/project/showfiles.php?group_id=205275&package_id=248632). Here's some more good command line parameters for generating previews with ffmpeg
* **`-t <seconds>`** chop after specified number of seconds
* **`-y`** force file overwrite
* **`-ab <bitrate>`** set bitrate e.g. *-ab 96k*
* **`-ar <rate Hz>`** set sampling rate e.g. *-ar 22050* for 22.05kHz
* **`-map_meta_data <outfile>:<infile>`** copy track metadata from infile to outfile
instead of setting -ab and -ar, you can copy the original track settings, as Tim Farley suggests, with:
* **`-acodec copy`** | I also recommend ffmpeg, but the command line suggested by John Boker has an unintended side effect: it re-encodes the file to the default bitrate (which is 64 kb/s in the version I have here at least). This might give your customers a false impression of the quality of your sound files, and it also takes longer to do.
Here's a command line that will slice to 30 seconds without transcoding:
```
ffmpeg -t 30 -i inputfile.mp3 -acodec copy outputfile.mp3
```
The -acodec switch tells ffmpeg to use the special "copy" codec which does not transcode. It is lightning fast.
NOTE: the command was updated based on comment from Oben Sonne |
43,903 | <p>In a stored procedure, when is #Temptable created in SQL Server 2005? When creating the query execution plan or when executing the stored procedure?</p>
<pre><code>if (@x = 1)
begin
select 1 as Text into #Temptable
end
else
begin
select 2 as Text into #Temptable
end
</code></pre>
| [
{
"answer_id": 43910,
"author": "Chris Miller",
"author_id": 206,
"author_profile": "https://Stackoverflow.com/users/206",
"pm_score": 2,
"selected": false,
"text": "<p>It's created when it's executed and dropped when the session ends.</p>\n"
},
{
"answer_id": 43925,
"author"... | 2008/09/04 | [
"https://Stackoverflow.com/questions/43903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2184/"
] | In a stored procedure, when is #Temptable created in SQL Server 2005? When creating the query execution plan or when executing the stored procedure?
```
if (@x = 1)
begin
select 1 as Text into #Temptable
end
else
begin
select 2 as Text into #Temptable
end
``` | Interesting question.
For the type of temporary table you're creating, I think it's when the stored procedure is executed. Tables created with the # prefix are accessible to the SQL Server session they're created in. Once the session ends, they're dropped.
This url: <http://www.sql-server-performance.com/tips/query_execution_plan_analysis_p1.aspx> seems to indicate that temp tables aren't created when query execution plans are created. |
43,926 | <p>A <code>.container</code> can contain many <code>.components</code>, and <code>.components</code> themselves can contain <code>.containers</code> (which in turn can contain .components etc. etc.)</p>
<p>Given code like this:</p>
<pre><code>$(".container .component").each(function(){
$(".container", this).css('border', '1px solid #f00');
});
</code></pre>
<p>What do I need to add to the line within the braces to select only the nested <code>.containers</code> that have their <code>width</code> in CSS set to <code>auto</code>? I'm sure it's something simple, but I haven't really used jQuery all that much.</p>
| [
{
"answer_id": 43933,
"author": "travis",
"author_id": 1414,
"author_profile": "https://Stackoverflow.com/users/1414",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$(\".container .component\").each(function() {\n if ($(\".container\", this).css('width') === \"auto\")\n ... | 2008/09/04 | [
"https://Stackoverflow.com/questions/43926",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2268/"
] | A `.container` can contain many `.components`, and `.components` themselves can contain `.containers` (which in turn can contain .components etc. etc.)
Given code like this:
```
$(".container .component").each(function(){
$(".container", this).css('border', '1px solid #f00');
});
```
What do I need to add to the line within the braces to select only the nested `.containers` that have their `width` in CSS set to `auto`? I'm sure it's something simple, but I haven't really used jQuery all that much. | ```
$(".container .component").each(function()
{
$(".container", this).each(function() {
if($(this).css('width') == 'auto')
{
$(this).css('border', '1px solid #f00');
}
});
});
```
Similar to the other answer but since components can also have multiple containers, also needs the .each() check in here too for the width. |
43,955 | <p>Is it possible to modify the title of the message box the confirm() function opens in JavaScript? </p>
<p>I could create a modal popup box, but I would like to do this as minimalistic as possible.
I would like to do something like this:</p>
<pre><code>confirm("This is the content of the message box", "Modified title");
</code></pre>
<p>The default title in Internet Explorer is "Windows Internet Explorer" and in Firefox it's "[JavaScript-program]." Not very informative. Though I can understand from a browser security stand point that you shouldn't be able to do this.</p>
| [
{
"answer_id": 43959,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 7,
"selected": true,
"text": "<p>This is not possible, as you say, from a security stand point. The only way you could simulate it, is by creating a modeless d... | 2008/09/04 | [
"https://Stackoverflow.com/questions/43955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2241/"
] | Is it possible to modify the title of the message box the confirm() function opens in JavaScript?
I could create a modal popup box, but I would like to do this as minimalistic as possible.
I would like to do something like this:
```
confirm("This is the content of the message box", "Modified title");
```
The default title in Internet Explorer is "Windows Internet Explorer" and in Firefox it's "[JavaScript-program]." Not very informative. Though I can understand from a browser security stand point that you shouldn't be able to do this. | This is not possible, as you say, from a security stand point. The only way you could simulate it, is by creating a modeless dialog window.
There are many third-party javascript-plugins that you could use to fake this effect so you do not have to write all that code. |
43,970 | <p>I'm setting up a server which is on a network behind a firewall and I want programs on this computer to be able to use sendmail to send emails to any email address. We have an SMTP server running on this network (let's call it mailrelay.example.com) which is how we're supposed to get outgoing emails through the firewall.</p>
<p>So how do I configure sendmail to send all mail through mailrelay.example.com? Googling hasn't given me the answer yet, and has only revealed that sendmail configuration is extremely complex and annoying.</p>
| [
{
"answer_id": 43977,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.elandsys.com/resources/sendmail/smarthost.html\" rel=\"noreferrer\">http://www.elandsys.com/resources/se... | 2008/09/04 | [
"https://Stackoverflow.com/questions/43970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1694/"
] | I'm setting up a server which is on a network behind a firewall and I want programs on this computer to be able to use sendmail to send emails to any email address. We have an SMTP server running on this network (let's call it mailrelay.example.com) which is how we're supposed to get outgoing emails through the firewall.
So how do I configure sendmail to send all mail through mailrelay.example.com? Googling hasn't given me the answer yet, and has only revealed that sendmail configuration is extremely complex and annoying. | @eli: modifying sendmail.cf directly is not usually recommended, since it is generated by the macro compiler.
Edit /etc/mail/sendmail.mc to include the line:
```
define(`SMART_HOST',`mailrelay.example.com')dnl
```
After changing the sendmail.mc macro configuration file, it must be recompiled
to produce the sendmail configuration file.
```
# m4 /etc/mail/sendmail.mc > /etc/sendmail.cf
```
And restart the sendmail service (Linux):
```
# /etc/init.d/sendmail restart
```
As well as setting the smarthost, you might want to also disable name resolution configuration and possibly shift your sendmail to non-standard port, or disable daemon mode.
Disable Name Resolution
=======================
Servers that are within fire-walled networks or using Network Address
Translation (NAT) may not have DNS or NIS services available. This creates
a problem for sendmail, since it will use DNS by default, and if it is not
available you will see messages like this in mailq:
```
host map: lookup (mydomain.com): deferred)
```
Unless you are prepared to setup an appropriate DNS or NIS service that
sendmail can use, in this situation you will typically configure name
resolution to be done using the /etc/hosts file. This is done by enabling
a 'service.switch' file and specifying resolution by file, as follows:
1: Enable service.switch for sendmail
Edit /etc/mail/sendmail.mc to include the lines:
```
define(`confSERVICE_SWITCH_FILE',`/etc/mail/service.switch')dnl
```
2: Configure service.switch for files
Create or modify /etc/mail/service.switch to refer only to /etc/hosts for name
resolution:
```
# cat /etc/mail/service.switch
hosts files
```
3: Recompile sendmail.mc and restart sendmail for this setting to take effect.
Shift sendmail to non-standard port, or disable daemon mode
===========================================================
By default, sendmail will listen on port 25. You may want to change this port
or disable the sendmail daemon mode altogether for various reasons:
- if there is a security policy prohibiting the use of well-known ports
- if another SMTP product/process is to be running on the same host on the standard port
- if you don't want to accept mail via smtp at all, just send it using sendmail
1: To shift sendmail to use non-standard port.
Edit /etc/mail/sendmail.mc and modify the "Port" setting in the line:
```
DAEMON_OPTIONS(`Port=smtp,Addr=127.0.0.1, Name=MTA')
```
For example, to get sendmail to use port 125:
```
DAEMON_OPTIONS(`Port=125,Addr=127.0.0.1, Name=MTA')
```
This will require sendmail.mc to be recompiled and sendmail to be restarted.
2: Alternatively, to disable sendmail daemon mode altogether (Linux)
Edit /etc/sysconfig/sendmail and modify the "DAEMON" setting to:
```
DAEMON=no
```
This change will require sendmail to be restarted. |
43,971 | <p>Let's say I have a web site for hosting community generated content that targets a very specific set of users. Now, let's say in the interest of fostering a better community I have an off-topic area where community members can post or talk about anything they want, regardless of the site's main theme.</p>
<p>Now, I <em>want</em> most of the content to get indexed by Google. The notable exception is the off-topic content. Each thread has it's own page, but all the threads are listed in the same folder so I can't just exclude search engines from a folder somewhere. It has to be per-page. A traditional robots.txt file would get huge, so how else could I accomplish this?</p>
| [
{
"answer_id": 43980,
"author": "James Marshall",
"author_id": 1025,
"author_profile": "https://Stackoverflow.com/users/1025",
"pm_score": 2,
"selected": false,
"text": "<p>If using Apache I'd use mod-rewrite to alias robots.txt to a script that could dynamically generate the necessary c... | 2008/09/04 | [
"https://Stackoverflow.com/questions/43971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] | Let's say I have a web site for hosting community generated content that targets a very specific set of users. Now, let's say in the interest of fostering a better community I have an off-topic area where community members can post or talk about anything they want, regardless of the site's main theme.
Now, I *want* most of the content to get indexed by Google. The notable exception is the off-topic content. Each thread has it's own page, but all the threads are listed in the same folder so I can't just exclude search engines from a folder somewhere. It has to be per-page. A traditional robots.txt file would get huge, so how else could I accomplish this? | This will work for all well-behaving search engines, just add it to the `<head>`:
```
<meta name="robots" content="noindex, nofollow" />
``` |
43,995 | <p>Handling multiple merges onto branches in Subversion or CVS is just one of those things that has to be experienced. It is inordinately easier to keep track of branches and merges in Mercurial (and probably any other distributed system) but I don't know why. Does anyone else know?</p>
<p>My question stems from the fact that with Mercurial you can adopt a working practice similar to that of Subversions/CVSs central repository and everything will work just fine. You can do multiple merges on the same branch and you won't need endless scraps of paper with commit numbers and tag names.</p>
<p>I know the latest version of Subversion has the ability to track merges to branches so you don't get quite the same degree of hassle but it was a huge and major development on their side and it still doesn't do everything the development team would like it to do.</p>
<p>There must be a fundamental difference in the way it all works.</p>
| [
{
"answer_id": 44030,
"author": "RedWolves",
"author_id": 648,
"author_profile": "https://Stackoverflow.com/users/648",
"pm_score": 1,
"selected": false,
"text": "<p>I only have experience with Subversion but I can tell you that the merge screen in TortoiseSVN is horribly complicated. L... | 2008/09/04 | [
"https://Stackoverflow.com/questions/43995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4003/"
] | Handling multiple merges onto branches in Subversion or CVS is just one of those things that has to be experienced. It is inordinately easier to keep track of branches and merges in Mercurial (and probably any other distributed system) but I don't know why. Does anyone else know?
My question stems from the fact that with Mercurial you can adopt a working practice similar to that of Subversions/CVSs central repository and everything will work just fine. You can do multiple merges on the same branch and you won't need endless scraps of paper with commit numbers and tag names.
I know the latest version of Subversion has the ability to track merges to branches so you don't get quite the same degree of hassle but it was a huge and major development on their side and it still doesn't do everything the development team would like it to do.
There must be a fundamental difference in the way it all works. | >
> In Subversion (and CVS), the repository is first and foremost. In git
> and mercurial there is not really the concept of a repository in the
> same way; here changes are the central theme.
>
>
>
+1
The hassle in CVS/SVN comes from the fact that these systems do **not**
remember the parenthood of changes. In Git and Mercurial,
not only can a commit have multiple children, it can also have multiple
parents!
That can easily observed using one of the graphical tools, `gitk` or `hg
view`. In the following example, branch #2 was forked from #1 at
commit A, and has since been merged once (at M, merged with commit B):
```
o---A---o---B---o---C (branch #1)
\ \
o---o---M---X---? (branch #2)
```
Note how A and B have two children, whereas M has two **parents**. These
relationships are *recorded* in the repository. Let's say the maintainer of
branch #2 now wants to merge the latest changes from branch #1, they can
issue a command such as:
```
$ git merge branch-1
```
and the tool will automatically know that the *base* is B--because it
was recorded in commit M, an ancestor of the tip of #2--and
that it has to merge whatever happened
between B and C. CVS does not record this information, nor did SVN prior to
version 1.5. In these systems, the graph
would look like:
```
o---A---o---B---o---C (branch #1)
\
o---o---M---X---? (branch #2)
```
where M is just a gigantic "squashed" commit of everything that happened between A and B,
applied on top of M. Note that after the deed is done, there is *no trace
left* (except potentially in human-readable comments) of where M did
originate from, nor of *how many* commits were collapsed together--making
history much more impenetrable.
Worse still, performing a second merge becomes a nightmare: one has to figure out
what the merge base was at the time of the first merge (and one *has* to *know*
that there has been a merge in the first place!), then
present that information to the tool so that it does not try to replay A..B on
top of M. All of this is difficult enough when working in close collaboration, but is
simply impossible in a distributed environment.
A (related) problem is that there is no way to answer the question: "does X
contain B?" where B is a
potentially important bug fix. So, why not just record that information in the commit, since
it is *known* at merge time!
P.-S. -- I have no experience with SVN 1.5+ merge recording abilities, but the workflow seems to be much more
contrived than in the distributed systems. If that is indeed the case, it's probably because--as mentioned
in the above comment--the focus is put on repository organization rather than on the changes themselves. |
44,007 | <p>Is there any chance to get this work? I want my tests to be run by nunit2 task in NAnt. In addition I want to run NCover without running tests again. </p>
| [
{
"answer_id": 44037,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 2,
"selected": false,
"text": "<p>Why not have NCover run NUnit? You get the exact same test results. Also, what exactly are you trying to measure when ru... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44007",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3182/"
] | Is there any chance to get this work? I want my tests to be run by nunit2 task in NAnt. In addition I want to run NCover without running tests again. | I figured it out. You change the path of the NUnit launcher to that of TeamCity's own. Here is an example:
```
<mkdir dir="${build}/coverage" failonerror="false"/>
<!-- run the unit tests and generate code coverage -->
<property name="tools.dir.tmp" value="${tools.dir}"/>
<if test="${not path::is-path-rooted(tools.dir)}">
<property name="tools.dir.tmp" value="../../${tools.dir}"/>
</if>
<property name="nunitpath" value="${lib.dir}/${lib.nunit.basedir}/bin/nunit-console.exe"/>
<property name="nunitargs" value=""/>
<if test="${property::exists('teamcity.dotnet.nunitlauncher')}">
<property name="nunitpath" value="${teamcity.dotnet.nunitlauncher}"/>
<property name="nunitargs" value="v2.0 x86 NUnit-2.4.8"/>
</if>
<ncover program="${tools.dir.tmp}/${tools.ncover.basedir}/ncover.console.exe"
commandLineExe="${nunitpath}"
commandLineArgs="${nunitargs} ${proj.name.unix}.dll"
workingDirectory="${build}"
assemblyList="${proj.srcproj.name.unix}"
logFile="${build}/coverage/coverage.log"
excludeAttributes="System.CodeDom.Compiler.GeneratedCodeAttribute"
typeExclusionPatterns=".*?\{.*?\}.*?"
methodExclusionPatterns="get_.*?; set_.*?"
coverageFile="${build}/coverage/coverage.xml"
coverageHtmlDirectory="${build}/coverage/html/"
/>
```
As you can see, I have some of my own variables in there, but you should be able to figure out what is going on. The property you are concerned with is teamcity.dotnet.nunitlauncher. You can read more about it here at <http://www.jetbrains.net/confluence/display/TCD4/TeamCity+NUnit+Test+Launcher>. |
44,019 | <p>I need to diff two log files but ignore the time stamp part of each line (the first 12 characters to be exact). Is there a good tool, or a clever awk command, that could help me out?</p>
| [
{
"answer_id": 44028,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 5,
"selected": false,
"text": "<p>@EbGreen said</p>\n\n<blockquote>\n <p>I would just take the log files and strip the timestamps off the start of eac... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4061/"
] | I need to diff two log files but ignore the time stamp part of each line (the first 12 characters to be exact). Is there a good tool, or a clever awk command, that could help me out? | Depending on the shell you are using, you can turn the approach [@Blair](https://stackoverflow.com/questions/44019/an-easy-way-to-diff-log-files-ignoring-the-time-stamps#44028) suggested into a 1-liner
```
diff <(cut -b13- file1) <(cut -b13- file2)
```
(+1 to [@Blair](https://stackoverflow.com/questions/44019/an-easy-way-to-diff-log-files-ignoring-the-time-stamps#44028) for the original suggestion :-) |
44,046 | <p>I'm trying to determine the best way to truncate or drop extra decimal places in SQL without rounding. For example:</p>
<pre><code>declare @value decimal(18,2)
set @value = 123.456
</code></pre>
<p>This will automatically round <code>@value</code> to be <code>123.46</code>, which is good in most cases. However, for this project, I don't need that. Is there a simple way to truncate the decimals I don't need? I know I can use the <code>left()</code> function and convert back to a decimal. Are there any other ways?</p>
| [
{
"answer_id": 44049,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": -1,
"selected": false,
"text": "<pre><code>select convert(int,@value)\n</code></pre>\n"
},
{
"answer_id": 44052,
"author": "Jimmy",
"author_... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44046",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105/"
] | I'm trying to determine the best way to truncate or drop extra decimal places in SQL without rounding. For example:
```
declare @value decimal(18,2)
set @value = 123.456
```
This will automatically round `@value` to be `123.46`, which is good in most cases. However, for this project, I don't need that. Is there a simple way to truncate the decimals I don't need? I know I can use the `left()` function and convert back to a decimal. Are there any other ways? | ```
select round(123.456, 2, 1)
``` |
44,066 | <p>Is it possible to pass a reference to a function to another function in F#? Specifically, I'd like to pass lambda functions like</p>
<p>foo(fun x -> x ** 3)</p>
<p>More specifically, I need to know how I would refer to the passed function in a function that I wrote myself.</p>
| [
{
"answer_id": 44079,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, it is possible. The <a href=\"http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc207785549\" rel=\"norefer... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2270/"
] | Is it possible to pass a reference to a function to another function in F#? Specifically, I'd like to pass lambda functions like
foo(fun x -> x \*\* 3)
More specifically, I need to know how I would refer to the passed function in a function that I wrote myself. | Yes, it is possible. The [manual](http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc207785549) has this example:
```
> List.map (fun x -> x % 2 = 0) [1 .. 5];;
val it : bool list
= [false; true; false; true; false]
``` |
44,078 | <p>I am trying to write a regular expression to strip all HTML with the exception of links (the <code><a href</code> and <code></a></code> tags respectively. It does not have to be 100% secure (I am not worried about injection attacks or anything as I am parsing content that has already been approved and published into a <a href="http://en.wikipedia.org/wiki/SWF" rel="noreferrer">SWF</a> movie).</p>
<p>The original "strip tags" regular expression I'm using was <code><(.|\n)+?></code>, and I tried to modify it to <code><([^a]|\n)+?></code>, but that of course will allow any tag that has an <strong>a</strong> in it rather than one that has it in the beginning, with a space.</p>
<p>Not that it should really matter, but in case anyone cares to know I am writing this in <a href="http://en.wikipedia.org/wiki/ActionScript#ActionScript_3.0" rel="noreferrer">ActionScript 3.0</a> for a <a href="http://en.wikipedia.org/wiki/Adobe_Flash" rel="noreferrer">Flash</a> movie.</p>
| [
{
"answer_id": 44088,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": -1,
"selected": false,
"text": "<p>How about</p>\n\n<pre><code><[^a](.|\\n)+?>\n</code></pre>\n\n<p>?</p>\n"
},
{
"answer_id": 44124,
"autho... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44078",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1306/"
] | I am trying to write a regular expression to strip all HTML with the exception of links (the `<a href` and `</a>` tags respectively. It does not have to be 100% secure (I am not worried about injection attacks or anything as I am parsing content that has already been approved and published into a [SWF](http://en.wikipedia.org/wiki/SWF) movie).
The original "strip tags" regular expression I'm using was `<(.|\n)+?>`, and I tried to modify it to `<([^a]|\n)+?>`, but that of course will allow any tag that has an **a** in it rather than one that has it in the beginning, with a space.
Not that it should really matter, but in case anyone cares to know I am writing this in [ActionScript 3.0](http://en.wikipedia.org/wiki/ActionScript#ActionScript_3.0) for a [Flash](http://en.wikipedia.org/wiki/Adobe_Flash) movie. | ```
<(?!\/?a(?=>|\s.*>))\/?.*?>
```
Try this. Had something similar for p tags. Worked for them so don't see why not. Uses negative lookahead to check that it doesn't match a (prefixed with an optional / character) where (using positive lookahead) a (with optional / prefix) is followed by a > or a space, stuff and then >. This then matches up until the next > character. Put this in a subst with
```
s/<(?!\/?a(?=>|\s.*>))\/?.*?>//g;
```
This should leave only the opening and closing a tags |
44,084 | <p>That's it. If you want to document a function or a class, you put a string just after the definition. For instance:</p>
<pre><code>def foo():
"""This function does nothing."""
pass
</code></pre>
<p>But what about a module? How can I document what a <em>file.py</em> does?</p>
| [
{
"answer_id": 44094,
"author": "David Locke",
"author_id": 1447,
"author_profile": "https://Stackoverflow.com/users/1447",
"pm_score": 2,
"selected": false,
"text": "<p>It's easy, you just add a docstring at the top of the module.</p>\n"
},
{
"answer_id": 44095,
"author": "G... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1679/"
] | That's it. If you want to document a function or a class, you put a string just after the definition. For instance:
```
def foo():
"""This function does nothing."""
pass
```
But what about a module? How can I document what a *file.py* does? | For the packages, you can document it in `__init__.py`.
For the modules, you can add a docstring simply in the module file.
All the information is here: <http://www.python.org/dev/peps/pep-0257/> |
44,100 | <p>This is a fairly trivial matter, but I'm curious to hear people's opinions on it.</p>
<p>If I have a Dictionary which I'm access through properties, which of these formats would you prefer for the property?</p>
<pre><code>/// <summary>
/// This class's FirstProperty property
/// </summary>
[DefaultValue("myValue")]
public string FirstProperty {
get {
return Dictionary["myKey"];
}
set {
Dictionary["myKey"] = value;
}
</code></pre>
<p>This is probably the typical way of doing it. It's fairly efficient, easy to understand, etc. The only disadvantage is with a longer or more complex key it would be possible to misspell it or change only one instance or something, leading me to this:</p>
<pre><code>/// <summary>
/// This class's SecondProperty property
/// </summary>
[DefaultValue("myValue")]
private const string DICT_MYKEY = "myKey"
public string SecondProperty {
get {
return Dictionary[DICT_MYKEY];
}
set {
Dictionary[DICT_MYKEY] = value;
}
</code></pre>
<p>Which is marginally more complicated, but seems to offer additional safety, and is closer to what I would think of as the "Code Complete" solution. The downside is that when you also have a /// block and a [DefaultValue()] block above the property already, it starts getting a bit crowded up there.</p>
<p>So which do you like better, and why? Does anybody have any better ideas?</p>
| [
{
"answer_id": 44106,
"author": "Glenn Slaven",
"author_id": 2975,
"author_profile": "https://Stackoverflow.com/users/2975",
"pm_score": 3,
"selected": true,
"text": "<p>I like the second one purely because any avoidance of magic strings/numbers in code is a good thing. IMO if you need ... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44100",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1512/"
] | This is a fairly trivial matter, but I'm curious to hear people's opinions on it.
If I have a Dictionary which I'm access through properties, which of these formats would you prefer for the property?
```
/// <summary>
/// This class's FirstProperty property
/// </summary>
[DefaultValue("myValue")]
public string FirstProperty {
get {
return Dictionary["myKey"];
}
set {
Dictionary["myKey"] = value;
}
```
This is probably the typical way of doing it. It's fairly efficient, easy to understand, etc. The only disadvantage is with a longer or more complex key it would be possible to misspell it or change only one instance or something, leading me to this:
```
/// <summary>
/// This class's SecondProperty property
/// </summary>
[DefaultValue("myValue")]
private const string DICT_MYKEY = "myKey"
public string SecondProperty {
get {
return Dictionary[DICT_MYKEY];
}
set {
Dictionary[DICT_MYKEY] = value;
}
```
Which is marginally more complicated, but seems to offer additional safety, and is closer to what I would think of as the "Code Complete" solution. The downside is that when you also have a /// block and a [DefaultValue()] block above the property already, it starts getting a bit crowded up there.
So which do you like better, and why? Does anybody have any better ideas? | I like the second one purely because any avoidance of magic strings/numbers in code is a good thing. IMO if you need to reference a number or string literal in code more than once, it should be a constant. In most cases even if it's only used once it should be in a constant |
44,131 | <p>I need to display a variable-length message and allow the text to be selectable. I have made the TextBox ReadOnly which does not allow the text to be edited, but the input caret is still shown. </p>
<p>The blinking input caret is confusing. How do I hide it?</p>
| [
{
"answer_id": 44146,
"author": "Simon Gillbee",
"author_id": 756,
"author_profile": "https://Stackoverflow.com/users/756",
"pm_score": 1,
"selected": false,
"text": "<p>If you disable the text box (set <code>Enable=false</code>), the text in it is still scrollable and selectable. If you... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1042/"
] | I need to display a variable-length message and allow the text to be selectable. I have made the TextBox ReadOnly which does not allow the text to be edited, but the input caret is still shown.
The blinking input caret is confusing. How do I hide it? | You can do through a win32 call
```
[DllImport("user32.dll")]
static extern bool HideCaret(IntPtr hWnd);
public void HideCaret()
{
HideCaret(someTextBox.Handle);
}
``` |
44,153 | <p>Like the title says: Can reflection give you the name of the currently executing method.</p>
<p>I'm inclined to guess not, because of the Heisenberg problem. How do you call a method that will tell you the current method without changing what the current method is? But I'm hoping someone can prove me wrong there.</p>
<p><strong>Update:</strong> </p>
<ul>
<li>Part 2: Could this be used to look inside code for a property as well? </li>
<li>Part 3: What would the performance be like?</li>
</ul>
<p><strong>Final Result</strong><br>
I learned about MethodBase.GetCurrentMethod(). I also learned that not only can I create a stack trace, I can create only the exact frame I need if I want. </p>
<p>To use this inside a property, just take a .Substring(4) to remove the 'set_' or 'get_'.</p>
| [
{
"answer_id": 44158,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 2,
"selected": false,
"text": "<p>I think you should be able to get that from creating a <a href=\"http://msdn.microsoft.com/en-us/library/6zh7csxz(VS.80).as... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44153",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3043/"
] | Like the title says: Can reflection give you the name of the currently executing method.
I'm inclined to guess not, because of the Heisenberg problem. How do you call a method that will tell you the current method without changing what the current method is? But I'm hoping someone can prove me wrong there.
**Update:**
* Part 2: Could this be used to look inside code for a property as well?
* Part 3: What would the performance be like?
**Final Result**
I learned about MethodBase.GetCurrentMethod(). I also learned that not only can I create a stack trace, I can create only the exact frame I need if I want.
To use this inside a property, just take a .Substring(4) to remove the 'set\_' or 'get\_'. | As of .NET 4.5, you can also use [[CallerMemberName]](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.callermembernameattribute).
Example: a property setter (to answer part 2):
```
protected void SetProperty<T>(T value, [CallerMemberName] string property = null)
{
this.propertyValues[property] = value;
OnPropertyChanged(property);
}
public string SomeProperty
{
set { SetProperty(value); }
}
```
The compiler will supply matching string literals at call sites, so there is basically no performance overhead. |
44,176 | <p>Is there a way to perform a full text search of a subversion repository, including all the history?</p>
<p>For example, I've written a feature that I used somewhere, but then it wasn't needed, so I svn rm'd the files, but now I need to find it again to use it for something else. The svn log probably says something like "removed unused stuff", and there's loads of checkins like that.</p>
<p><strong>Edit 2016-04-15:</strong> Please note that what is asked here by the term "full text search", is to <strong>search the actual diffs of the commit history, and not filenames and/or commit messages</strong>. I'm pointing this out because the author's phrasing above does not reflect that very well - since in his example he might as well be only looking for a filename and/or commit message. Hence a lot of the <code>svn log</code> answers and comments.</p>
| [
{
"answer_id": 44185,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 2,
"selected": false,
"text": "<p>I don't have any experience with it, but <a href=\"http://supose.soebes.de/\" rel=\"nofollow noreferrer\">SupoSE</a> (open sou... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3408/"
] | Is there a way to perform a full text search of a subversion repository, including all the history?
For example, I've written a feature that I used somewhere, but then it wasn't needed, so I svn rm'd the files, but now I need to find it again to use it for something else. The svn log probably says something like "removed unused stuff", and there's loads of checkins like that.
**Edit 2016-04-15:** Please note that what is asked here by the term "full text search", is to **search the actual diffs of the commit history, and not filenames and/or commit messages**. I'm pointing this out because the author's phrasing above does not reflect that very well - since in his example he might as well be only looking for a filename and/or commit message. Hence a lot of the `svn log` answers and comments. | ```
git svn clone <svn url>
```
```
git log -G<some regex>
``` |
44,181 | <p>I have a database with two tables (<code>Table1</code> and <code>Table2</code>). They both have a common column <code>[ColumnA]</code> which is an <code>nvarchar</code>. </p>
<p>How can I select this column from both tables and return it as a single column in my result set?</p>
<p>So I'm looking for something like:</p>
<pre><code>ColumnA in Table1:
a
b
c
ColumnA in Table2:
d
e
f
Result set should be:
a
b
c
d
e
f
</code></pre>
| [
{
"answer_id": 44183,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 5,
"selected": true,
"text": "<pre><code>SELECT ColumnA FROM Table1 UNION Select ColumnB FROM Table2 ORDER BY 1\n</code></pre>\n\n<p>Also, if you kn... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1980/"
] | I have a database with two tables (`Table1` and `Table2`). They both have a common column `[ColumnA]` which is an `nvarchar`.
How can I select this column from both tables and return it as a single column in my result set?
So I'm looking for something like:
```
ColumnA in Table1:
a
b
c
ColumnA in Table2:
d
e
f
Result set should be:
a
b
c
d
e
f
``` | ```
SELECT ColumnA FROM Table1 UNION Select ColumnB FROM Table2 ORDER BY 1
```
Also, if you know the contents of Table1 and Table2 will **NEVER** overlap, you can use UNION ALL in place of UNION instead. Saves a little bit of resources that way.
-- Kevin Fairchild |
44,190 | <p>I am looking for a simple JavaScript example that updates DOM.<br>
Any suggestions?</p>
| [
{
"answer_id": 44198,
"author": "Guy",
"author_id": 1463,
"author_profile": "https://Stackoverflow.com/users/1463",
"pm_score": 0,
"selected": false,
"text": "<p>I believe that this tutorial on jQuery has an example that might help you: <a href=\"http://docs.jquery.com/Tutorials:Getting_... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/370899/"
] | I am looking for a simple JavaScript example that updates DOM.
Any suggestions? | Here is a short pure-javascript example. Assume you have a div with the id "maincontent".
```
var newnode = document.createTextNode('Here is some text.');
document.getElementById('maincontent').appendChild(newnode);
```
Of course, things are a lot easier (especially when you want to do more complicated things) with jQuery. |
44,194 | <p>This is what I've got. It works. But, is there a simpler or better way?</p>
<p>One an ASPX page, I've got the download link...</p>
<pre><code><asp:HyperLink ID="HyperLinkDownload" runat="server" NavigateUrl="~/Download.aspx">Download as CSV file</asp:HyperLink>
</code></pre>
<p>And then I've got the Download.aspx.vb Code Behind...</p>
<pre><code>Public Partial Class Download
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'set header
Response.Clear()
Response.ContentType = "text/csv"
Dim FileName As String = "books.csv"
Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName)
'generate file content
Dim db As New bookDevelopmentDataContext
Dim Allbooks = From b In db.books _
Order By b.Added _
Select b
Dim CsvFile As New StringBuilder
CsvFile.AppendLine(CsvHeader())
For Each b As Book In Allbooks
CsvFile.AppendLine(bookString(b))
Next
'write the file
Response.Write(CsvFile.ToString)
Response.End()
End Sub
Function CsvHeader() As String
Dim CsvLine As New StringBuilder
CsvLine.Append("Published,")
CsvLine.Append("Title,")
CsvLine.Append("Author,")
CsvLine.Append("Price")
Return CsvLine.ToString
End Function
Function bookString(ByVal b As Book) As String
Dim CsvLine As New StringBuilder
CsvLine.Append(b.Published.ToShortDateString + ",")
CsvLine.Append(b.Title.Replace(",", "") + ",")
CsvLine.Append(b.Author.Replace(",", "") + ",")
CsvLine.Append(Format(b.Price, "c").Replace(",", ""))
Return CsvLine.ToString
End Function
End Class
</code></pre>
| [
{
"answer_id": 44219,
"author": "Simon Gillbee",
"author_id": 756,
"author_profile": "https://Stackoverflow.com/users/756",
"pm_score": 6,
"selected": true,
"text": "<p>CSV formatting has some gotchas. Have you asked yourself these questions:</p>\n\n<ul>\n<li>Does any of my data have emb... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] | This is what I've got. It works. But, is there a simpler or better way?
One an ASPX page, I've got the download link...
```
<asp:HyperLink ID="HyperLinkDownload" runat="server" NavigateUrl="~/Download.aspx">Download as CSV file</asp:HyperLink>
```
And then I've got the Download.aspx.vb Code Behind...
```
Public Partial Class Download
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'set header
Response.Clear()
Response.ContentType = "text/csv"
Dim FileName As String = "books.csv"
Response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName)
'generate file content
Dim db As New bookDevelopmentDataContext
Dim Allbooks = From b In db.books _
Order By b.Added _
Select b
Dim CsvFile As New StringBuilder
CsvFile.AppendLine(CsvHeader())
For Each b As Book In Allbooks
CsvFile.AppendLine(bookString(b))
Next
'write the file
Response.Write(CsvFile.ToString)
Response.End()
End Sub
Function CsvHeader() As String
Dim CsvLine As New StringBuilder
CsvLine.Append("Published,")
CsvLine.Append("Title,")
CsvLine.Append("Author,")
CsvLine.Append("Price")
Return CsvLine.ToString
End Function
Function bookString(ByVal b As Book) As String
Dim CsvLine As New StringBuilder
CsvLine.Append(b.Published.ToShortDateString + ",")
CsvLine.Append(b.Title.Replace(",", "") + ",")
CsvLine.Append(b.Author.Replace(",", "") + ",")
CsvLine.Append(Format(b.Price, "c").Replace(",", ""))
Return CsvLine.ToString
End Function
End Class
``` | CSV formatting has some gotchas. Have you asked yourself these questions:
* Does any of my data have embedded commas?
* Does any of my data have embedded double-quotes?
* Does any of my data have have newlines?
* Do I need to support Unicode strings?
I see several problems in your code above. The comma thing first of all... you are stripping commas:
```
CsvLine.Append(Format(b.Price, "c").Replace(",", ""))
```
Why? In CSV, you should be surrounding anything which has commas with quotes:
```
CsvLine.Append(String.Format("\"{0:c}\"", b.Price))
```
(or something like that... my VB is not very good). If you're not sure if there are commas, but put quotes around it. If there are quotes in the string, you need to escape them by doubling them. `"` becomes `""`.
```
b.Title.Replace("\"", "\"\"")
```
Then surround this by quotes if you want. If there are newlines in your string, you need to surround the string with quotes... yes, literal newlines *are* allowed in CSV files. It looks weird to humans, but it's all good.
A good CSV writer requires some thought. A good CSV reader (parser) is just plain hard (and no, regex not good enough for parsing CSV... it will only get you about 95% of the way there).
And then there is Unicode... or more generally I18N (Internationalization) issues. For example, you are stripping commas out of a formatted price. But that's assuming the price is formatted as you expect it in the US. In France, the number formatting is reversed (periods used instead of commas, and *vice versa*). Bottom line, use culture-agnostic formatting wherever possible.
While the issue here is *generating* CSV, inevitably you will need to parse CSV. In .NET, the best parser I have found (for free) is [Fast CSV Reader](http://www.codeproject.com/KB/database/CsvReader.aspx) on [CodeProject](http://www.codeproject.com). I've actually used it in production code and it is really really fast, and very easy to use! |
44,220 | <p>I have been told that there is a performance difference between the following code blocks.</p>
<pre><code>foreach (Entity e in entityList)
{
....
}
</code></pre>
<p>and </p>
<pre><code>for (int i=0; i<entityList.Count; i++)
{
Entity e = (Entity)entityList[i];
...
}
</code></pre>
<p>where</p>
<pre><code>List<Entity> entityList;
</code></pre>
<p>I am no CLR expect but from what I can tell they should boil down to basically the same code. Does anybody have concrete (heck, I'd take packed dirt) evidence one way or the other?</p>
| [
{
"answer_id": 44225,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 4,
"selected": true,
"text": "<p>foreach creates an instance of an enumerator (returned from GetEnumerator) and that enumerator also keeps state thr... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2894/"
] | I have been told that there is a performance difference between the following code blocks.
```
foreach (Entity e in entityList)
{
....
}
```
and
```
for (int i=0; i<entityList.Count; i++)
{
Entity e = (Entity)entityList[i];
...
}
```
where
```
List<Entity> entityList;
```
I am no CLR expect but from what I can tell they should boil down to basically the same code. Does anybody have concrete (heck, I'd take packed dirt) evidence one way or the other? | foreach creates an instance of an enumerator (returned from GetEnumerator) and that enumerator also keeps state throughout the course of the foreach loop. It then repeatedly calls for the Next() object on the enumerator and runs your code for each object it returns.
They don't boil down to the same code in any way, really, which you'd see if you wrote your own enumerator. |
44,272 | <p>This is a php example, but an algorithm for any language would do. What I specifically want to do is bubble up the United States and Canada to the top of the list. Here is an example of the array shortened for brevity. </p>
<pre><code>array(
0 => '-- SELECT --',
1 => 'Afghanistan',
2 => 'Albania',
3 => 'Algeria',
4 => 'American Samoa',
5 => 'Andorra',)
</code></pre>
<p>The id's need to stay intact. So making them -1 or -2 will unfortunately not work.</p>
| [
{
"answer_id": 44292,
"author": "Leigh Caldwell",
"author_id": 3267,
"author_profile": "https://Stackoverflow.com/users/3267",
"pm_score": 1,
"selected": false,
"text": "<p>My shortcut in similar cases is to add a space at the start of Canada and two spaces at the start of United States.... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44272",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1797/"
] | This is a php example, but an algorithm for any language would do. What I specifically want to do is bubble up the United States and Canada to the top of the list. Here is an example of the array shortened for brevity.
```
array(
0 => '-- SELECT --',
1 => 'Afghanistan',
2 => 'Albania',
3 => 'Algeria',
4 => 'American Samoa',
5 => 'Andorra',)
```
The id's need to stay intact. So making them -1 or -2 will unfortunately not work. | What I usually do in these situations is to add a separate field called DisplayOrder or something similar. Everything defaults to, say, 1... You then sort by DisplayOrder and then the Name. If you want something higher or lower on the list, you can tweak the display order accordingly while keeping your normal IDs as-is.
-- Kevin Fairchild |
44,288 | <p>Comparing string in C# is pretty simple. In fact there are several ways to do it. I have listed some in the block below. What I am curious about are the differences between them and when one should be used over the others? Should one be avoided at all costs? Are there more I haven't listed? </p>
<pre><code>string testString = "Test";
string anotherString = "Another";
if (testString.CompareTo(anotherString) == 0) {}
if (testString.Equals(anotherString)) {}
if (testString == anotherString) {}
</code></pre>
<p>(Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well)</p>
| [
{
"answer_id": 44301,
"author": "Ed S.",
"author_id": 1053,
"author_profile": "https://Stackoverflow.com/users/1053",
"pm_score": 6,
"selected": false,
"text": "<p>From MSDN:</p>\n\n<blockquote>\n <p>\"The CompareTo method was designed primarily for use in sorting or\n alphabetizing ... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2894/"
] | Comparing string in C# is pretty simple. In fact there are several ways to do it. I have listed some in the block below. What I am curious about are the differences between them and when one should be used over the others? Should one be avoided at all costs? Are there more I haven't listed?
```
string testString = "Test";
string anotherString = "Another";
if (testString.CompareTo(anotherString) == 0) {}
if (testString.Equals(anotherString)) {}
if (testString == anotherString) {}
```
(Note: I am looking for equality in this example, not less than or greater than but feel free to comment on that as well) | Here are the rules for how these functions work:
**`stringValue.CompareTo(otherStringValue)`**
1. `null` comes before a string
2. it uses `CultureInfo.CurrentCulture.CompareInfo.Compare`, which means it will use a culture-dependent comparison. This might mean that `ß` will compare equal to `SS` in Germany, or similar
**`stringValue.Equals(otherStringValue)`**
1. `null` is not considered equal to anything
2. unless you specify a `StringComparison` option, it will use what looks like a direct ordinal equality check, i.e. `ß` is not the same as `SS`, in any language or culture
**`stringValue == otherStringValue`**
1. Is not the same as `stringValue.Equals()`.
2. The `==` operator calls the static `Equals(string a, string b)` method (which in turn goes to an internal `EqualsHelper` to do the comparison.
3. Calling `.Equals()` on a `null` string gets `null` reference exception, while on `==` does not.
**`Object.ReferenceEquals(stringValue, otherStringValue)`**
Just checks that references are the same, i.e. it isn't just two strings with the same contents, you're comparing a string object with itself.
---
Note that with the options above that use method calls, there are overloads with more options to specify how to compare.
My advice if you just want to check for equality is to make up your mind whether you want to use a culture-dependent comparison or not, and then use `.CompareTo` or `.Equals`, depending on the choice. |
44,298 | <p>I have a databound TextBox in my application like so: (The type of <code>Height</code> is <code>decimal?</code>)</p>
<pre class="lang-xml prettyprint-override"><code> <TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged,
ValidatesOnExceptions=True,
Converter={StaticResource NullConverter}}" />
</code></pre>
<pre class="lang-cs prettyprint-override"><code> public class NullableConverter : IValueConverter {
public object Convert(object o, Type type, object parameter, CultureInfo culture) {
return o;
}
public object ConvertBack(object o, Type type, object parameter, CultureInfo culture) {
if (o as string == null || (o as string).Trim() == string.Empty)
return null;
return o;
}
}
</code></pre>
<p>Configured this way, any non-empty strings which cannot be converted to decimal result in a validation error which will immediately highlight the textbox. However, the TextBox can still lose focus and remain in an invalid state. What I would like to do is either:</p>
<ol>
<li>Not allow the TextBox to lose focus until it contains a valid value.</li>
<li>Revert the value in the TextBox to the last valid value.</li>
</ol>
<p>What is the best way to do this?</p>
<p><strong>Update:</strong></p>
<p>I've found a way to do #2. I don't love it, but it works:</p>
<pre><code>private void TextBox_LostKeyboardFocus(object sender, RoutedEventArgs e) {
var box = sender as TextBox;
var binding = box.GetBindingExpression(TextBox.TextProperty);
if (binding.HasError)
binding.UpdateTarget();
}
</code></pre>
<p>Does anyone know how to do this better? (Or do #1.)</p>
| [
{
"answer_id": 44362,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds to me that you'll want to handle two events:</p>\n\n<p>GotFocus: Will trigger when the textbox gains focus. You can... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/317/"
] | I have a databound TextBox in my application like so: (The type of `Height` is `decimal?`)
```xml
<TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged,
ValidatesOnExceptions=True,
Converter={StaticResource NullConverter}}" />
```
```cs
public class NullableConverter : IValueConverter {
public object Convert(object o, Type type, object parameter, CultureInfo culture) {
return o;
}
public object ConvertBack(object o, Type type, object parameter, CultureInfo culture) {
if (o as string == null || (o as string).Trim() == string.Empty)
return null;
return o;
}
}
```
Configured this way, any non-empty strings which cannot be converted to decimal result in a validation error which will immediately highlight the textbox. However, the TextBox can still lose focus and remain in an invalid state. What I would like to do is either:
1. Not allow the TextBox to lose focus until it contains a valid value.
2. Revert the value in the TextBox to the last valid value.
What is the best way to do this?
**Update:**
I've found a way to do #2. I don't love it, but it works:
```
private void TextBox_LostKeyboardFocus(object sender, RoutedEventArgs e) {
var box = sender as TextBox;
var binding = box.GetBindingExpression(TextBox.TextProperty);
if (binding.HasError)
binding.UpdateTarget();
}
```
Does anyone know how to do this better? (Or do #1.) | You can force the keyboard focus to stay on the `TextBox` by handling the `PreviewLostKeyBoardFocus` event like this:
```xml
<TextBox PreviewLostKeyboardFocus="TextBox_PreviewLostKeyboardFocus" />
```
```cs
private void TextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {
e.Handled = true;
}
``` |
44,337 | <p>As an exercise for myself, I was translating a sample program into various languages. Starting in C#, I had a visitor-pattern interface like so:</p>
<pre><code>interface Visitor
{
void Accept(Bedroom x);
void Accept(Bathroom x);
void Accept(Kitchen x);
void Accept(LivingRoom x);
}
</code></pre>
<p>Moving to ruby (or python, or whatever), I no longer get dispatch from the compiler based on type. Should I do the dispatch in the visitor itself?</p>
<pre><code>class Cleaner
def accept(x)
acceptBedroom(x) if Bedroom === x
acceptBathroom(x) if Bathroom === x
acceptKitchen(x) if Kitchen===x
acceptLivingRoom(x) if LivingRoom===x
end
...
</code></pre>
<p>Or should I do the dispatch in the different specializaions of the room:</p>
<pre><code>class Bathroom<Room
def initialize(name)
super(name)
end
def accept(visitor)
visitor.acceptBathroom(self)
end
end
</code></pre>
<p>Or is there another preferred idiom that is used in dynamic languages?</p>
| [
{
"answer_id": 44362,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds to me that you'll want to handle two events:</p>\n\n<p>GotFocus: Will trigger when the textbox gains focus. You can... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4540/"
] | As an exercise for myself, I was translating a sample program into various languages. Starting in C#, I had a visitor-pattern interface like so:
```
interface Visitor
{
void Accept(Bedroom x);
void Accept(Bathroom x);
void Accept(Kitchen x);
void Accept(LivingRoom x);
}
```
Moving to ruby (or python, or whatever), I no longer get dispatch from the compiler based on type. Should I do the dispatch in the visitor itself?
```
class Cleaner
def accept(x)
acceptBedroom(x) if Bedroom === x
acceptBathroom(x) if Bathroom === x
acceptKitchen(x) if Kitchen===x
acceptLivingRoom(x) if LivingRoom===x
end
...
```
Or should I do the dispatch in the different specializaions of the room:
```
class Bathroom<Room
def initialize(name)
super(name)
end
def accept(visitor)
visitor.acceptBathroom(self)
end
end
```
Or is there another preferred idiom that is used in dynamic languages? | You can force the keyboard focus to stay on the `TextBox` by handling the `PreviewLostKeyBoardFocus` event like this:
```xml
<TextBox PreviewLostKeyboardFocus="TextBox_PreviewLostKeyboardFocus" />
```
```cs
private void TextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {
e.Handled = true;
}
``` |
44,338 | <p>I'm trying to be better about unit testing my code, but right now I'm writing a lot of code that deals with remote systems. SNMP, WMI, that sort of thing. With most classes I can mock up objects to test them, but how do you deal with unit testing a real system? For example, if my class goes out and gets the Win32_LogicalDisk object for a server, how could I possibly unit test it?</p>
| [
{
"answer_id": 44525,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": true,
"text": "<p>Assuming you meant \"How do I test against things that are hard/impossible to mock\":</p>\n\n<p>If you have a class that \"go... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44338",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4550/"
] | I'm trying to be better about unit testing my code, but right now I'm writing a lot of code that deals with remote systems. SNMP, WMI, that sort of thing. With most classes I can mock up objects to test them, but how do you deal with unit testing a real system? For example, if my class goes out and gets the Win32\_LogicalDisk object for a server, how could I possibly unit test it? | Assuming you meant "How do I test against things that are hard/impossible to mock":
If you have a class that "goes out and gets the Win32\_LogicalDisk object for a server" AND does something else (consumes the 'Win32\_LogicalDisk' object in some way), assuming you want to test the pieces of the class that consume this object, you can use [Dependency Injection](http://en.wikipedia.org/wiki/Dependency_injection) to allow you to mock the 'Win32\_LogicalDisk' object. For instance:
```
class LogicalDiskConsumer(object):
def __init__(self, arg1, arg2, LogicalDiskFactory)
self.arg1=arg1
self.arg2=arg2
self.LogicalDisk=LogicalDiskFactory()
def consumedisk(self):
self.LogicalDisk.someaction()
```
Then in your unit test code, pass in a 'LogicalDiskFactory' that returns a mock object for the 'Win32\_LogicalDisk'. |
44,352 | <p>In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X?</p>
| [
{
"answer_id": 44381,
"author": "Chris AtLee",
"author_id": 4558,
"author_profile": "https://Stackoverflow.com/users/4558",
"pm_score": 5,
"selected": true,
"text": "<p>Here's one way to do it:</p>\n\n<pre><code>import inspect\n\ndef get_subclasses(mod, cls):\n \"\"\"Yield the classes... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44352",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | In Python, given a module X and a class Y, how can I iterate or generate a list of all subclasses of Y that exist in module X? | Here's one way to do it:
```
import inspect
def get_subclasses(mod, cls):
"""Yield the classes in module ``mod`` that inherit from ``cls``"""
for name, obj in inspect.getmembers(mod):
if hasattr(obj, "__bases__") and cls in obj.__bases__:
yield obj
``` |
44,359 | <p>I have built a basic data entry application allowing users to browse external content in iframe and enter data quickly from the same page. One of the data variables is the URL.
Ideally I would like to be able to load the iframes current url into a textbox with javascript. I realize now that this is not going to happen due to security issues.</p>
<p>Has anyone done anything on the server side? or know of any .Net browser in browser controls. The ultimate goal is to just give the user an easy method of extracting the url of the page they are viewing in the iframe It doesn't necessarily HAVE to be an iframe, a browser in the browser would be ideal.</p>
<p>Thanks,
Adam</p>
| [
{
"answer_id": 46361,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Does this help? </p>\n\n<p><a href=\"http://www.quirksmode.org/js/iframe.html\" rel=\"nofollow noreferrer\">http://www.quir... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4568/"
] | I have built a basic data entry application allowing users to browse external content in iframe and enter data quickly from the same page. One of the data variables is the URL.
Ideally I would like to be able to load the iframes current url into a textbox with javascript. I realize now that this is not going to happen due to security issues.
Has anyone done anything on the server side? or know of any .Net browser in browser controls. The ultimate goal is to just give the user an easy method of extracting the url of the page they are viewing in the iframe It doesn't necessarily HAVE to be an iframe, a browser in the browser would be ideal.
Thanks,
Adam | I did some tests in Firefox 3 comparing the value of `.src` and `.documentWindow.location.href` in an `iframe`. (Note: The `documentWindow` is called `contentDocument` in Chrome, so instead of `.documentWindow.location.href` in Chrome it will be `.contentDocument.location.href`.)
`src` is always the last URL that was loaded in the iframe without user interaction. I.e., it contains the first value for the URL, or the last value you set up with Javascript from the containing window doing:
```
document.getElementById("myiframe").src = 'http://www.google.com/';
```
If the user navigates inside the iframe, you can't anymore access the value of the URL using src. In the previous example, if the user goes away from www.google.com and you do:
```
alert(document.getElementById("myiframe").src);
```
You will still get "<http://www.google.com>".
`documentWindow.location.href` is only available if the iframe contains a page in the same domain as the containing window, but if it's available it always contains the right value for the URL, even if the user navigates in the iframe.
If you try to access `documentWindow.location.href` (or anything under `documentWindow`) and the iframe is in a page that doesn't belong to the domain of the containing window, it will raise an exception:
```
document.getElementById("myiframe").src = 'http://www.google.com/';
alert(document.getElementById("myiframe").documentWindow.location.href);
Error: Permission denied to get property Location.href
```
I have not tested any other browser.
Hope it helps! |
44,376 | <p>How do you shade alternating rows in a SQL Server Reporting Services report?</p>
<hr>
<p><strong>Edit:</strong> There are a bunch of good answers listed below--from <a href="https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#44378">quick</a> and <a href="https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#345935">simple</a> to <a href="https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#83832">complex and comprehensive</a>. Alas, I can choose only one...</p>
| [
{
"answer_id": 44378,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 9,
"selected": true,
"text": "<p>Go to the table row's BackgroundColor property and choose \"Expression...\"</p>\n\n<p>Use this expression: </p>\n\n<pre><... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44376",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29/"
] | How do you shade alternating rows in a SQL Server Reporting Services report?
---
**Edit:** There are a bunch of good answers listed below--from [quick](https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#44378) and [simple](https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#345935) to [complex and comprehensive](https://stackoverflow.com/questions/44376/add-alternating-row-color-to-sql-server-reporting-services-report#83832). Alas, I can choose only one... | Go to the table row's BackgroundColor property and choose "Expression..."
Use this expression:
```
= IIf(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")
```
This trick can be applied to many areas of the report.
And in .NET 3.5+ You could use:
```
= If(RowNumber(Nothing) Mod 2 = 0, "Silver", "Transparent")
```
Not looking for rep--I just researched this question myself and thought I'd share. |
44,394 | <p>I have a MemoryStream with the contents of a Font File (.ttf) and I would like to be able to create a FontFamily WPF object from that stream <strong>WITHOUT</strong> writing the contents of the stream to disk. I know this is possible with a System.Drawing.FontFamily but I cannot find out how to do it with System.Windows.Media.FontFamily.</p>
<p>Note: I will only have the stream, so I can't pack it as a resource in the application and because of disk permissions issues, will not be able to write the font file to disk for reference as "content"</p>
<p><strong>UPDATE:</strong></p>
<p>The <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.fontfamily?view=netframework-4.6.1" rel="nofollow noreferrer">API docs</a> how describe how an application resource can be used, though it is not clear to me whether that is an Embedded resource in the assembly or a file on disk.</p>
<blockquote>
<p>You can use a base URI value when you reference a font that is packaged as part of the application. For example, the base URI value can be a "pack://application" URI, which lets you reference fonts that are packaged as application resources. The following code example shows a font reference that is composed of a base URI value and a relative URI value.</p>
</blockquote>
| [
{
"answer_id": 7336238,
"author": "kobi7",
"author_id": 588613,
"author_profile": "https://Stackoverflow.com/users/588613",
"pm_score": 1,
"selected": false,
"text": "<p>The best approach I could think of, was to save the oldFont to a temp directory, and immediately load it using the new... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4572/"
] | I have a MemoryStream with the contents of a Font File (.ttf) and I would like to be able to create a FontFamily WPF object from that stream **WITHOUT** writing the contents of the stream to disk. I know this is possible with a System.Drawing.FontFamily but I cannot find out how to do it with System.Windows.Media.FontFamily.
Note: I will only have the stream, so I can't pack it as a resource in the application and because of disk permissions issues, will not be able to write the font file to disk for reference as "content"
**UPDATE:**
The [API docs](https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.fontfamily?view=netframework-4.6.1) how describe how an application resource can be used, though it is not clear to me whether that is an Embedded resource in the assembly or a file on disk.
>
> You can use a base URI value when you reference a font that is packaged as part of the application. For example, the base URI value can be a "pack://application" URI, which lets you reference fonts that are packaged as application resources. The following code example shows a font reference that is composed of a base URI value and a relative URI value.
>
>
> | There is a similar question [here](https://stackoverflow.com/questions/44912480/c-sharp-wpf-how-to-load-a-fontfamily-from-a-byte-array), which contains a supposed solution by converting a System.Drawing.FontFamily to a WPF font family, all in memory without any file IO:
```
public static void Load(MemoryStream stream)
{
byte[] streamData = new byte[stream.Length];
stream.Read(streamData, 0, streamData.Length);
IntPtr data = Marshal.AllocCoTaskMem(streamData.Length); // Very important.
Marshal.Copy(streamData, 0, data, streamData.Length);
PrivateFontCollection pfc = new PrivateFontCollection();
pfc.AddMemoryFont(data, streamData.Length);
MemoryFonts.Add(pfc); // Your own collection of fonts here.
Marshal.FreeCoTaskMem(data); // Very important.
}
public static System.Windows.Media.FontFamily LoadFont(int fontId)
{
if (!Exists(fontId))
{
return null;
}
/*
NOTE:
This is basically how you convert a System.Drawing.FontFamily to System.Windows.Media.FontFamily, using PrivateFontCollection.
*/
return new System.Windows.Media.FontFamily(MemoryFonts[fontId].Families[0].Name);
}
```
This seems to use the `System.Drawing.PrivateFontCollection`([^](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.text.privatefontcollection?view=dotnet-plat-ext-5.0)) to add a `System.Drawing.Font` created from a `MemoryStream` and then use the `Families[0].Name` of that font to pass into the `System.Windows.Media.FontFamily` constructor. I assume the family name would then be a URI to the instance of that font in the PrivateFontCollection but you'd probably have to try it out. |
44,401 | <p>I've got a sign up form that requires the user to enter their email and password, both are in two separate text boxes. I want to provide a button that the user can click so that the password (which is masked) will appear in a popup when the user clicks the button.</p>
<p>Currently my JavaScript code for this is as follows:</p>
<pre><code> function toggleShowPassword() {
var button = $get('PASSWORD_TEXTBOX_ID');
var password;
if (button)
{
password = button.value;
alert(password);
button.value = password;
}
}
</code></pre>
<p>The problem is that every time the user clicks the button, the password is cleared in both Firefox and IE. I want them to be able to see their password in clear text to verify without having to retype their password.</p>
<p>My questions are:</p>
<ol>
<li><p>Why does the password field keep getting reset with each button click?</p></li>
<li><p>How can I make it so the password field is NOT cleared once the user has seen his/her password in clear text?</p></li>
</ol>
| [
{
"answer_id": 44436,
"author": "matt b",
"author_id": 4249,
"author_profile": "https://Stackoverflow.com/users/4249",
"pm_score": 1,
"selected": false,
"text": "<p>I would assume that the browser has some issue with the script attempting to set the value of a password field:</p>\n\n<pre... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44401",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/750/"
] | I've got a sign up form that requires the user to enter their email and password, both are in two separate text boxes. I want to provide a button that the user can click so that the password (which is masked) will appear in a popup when the user clicks the button.
Currently my JavaScript code for this is as follows:
```
function toggleShowPassword() {
var button = $get('PASSWORD_TEXTBOX_ID');
var password;
if (button)
{
password = button.value;
alert(password);
button.value = password;
}
}
```
The problem is that every time the user clicks the button, the password is cleared in both Firefox and IE. I want them to be able to see their password in clear text to verify without having to retype their password.
My questions are:
1. Why does the password field keep getting reset with each button click?
2. How can I make it so the password field is NOT cleared once the user has seen his/her password in clear text? | I did a quick example up of a working version:
```
<html>
<head>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
function toggleShowPassword() {
var textBox = $('PasswordText');
if (textBox)
{
alert(textBox.value);
}
}
</script>
</head>
<body>
<input type="password" id="PasswordText" /><input type="button" onclick="toggleShowPassword();" value="Show Password" />
</body>
</html>
```
The key is that the input is of type button and not submit. I used the [prototype](http://prototypejs.org/) library for retrieving the element by ID. |
44,408 | <p>I would like to generate a random floating point number between 2 values. What is the best way to do this in C#?</p>
| [
{
"answer_id": 44424,
"author": "Ryan Farley",
"author_id": 1627,
"author_profile": "https://Stackoverflow.com/users/1627",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// generate a random number starting with 5 and less than 15\nRandom r = new Random();\nint num = r.Next(5, 15... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44408",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064/"
] | I would like to generate a random floating point number between 2 values. What is the best way to do this in C#? | The only thing I'd add to [Eric](https://stackoverflow.com/questions/44408/how-do-you-generate-a-random-number-in-c#44428)'s response is an explanation; I feel that knowledge of why code works is better than knowing what code works.
The explanation is this: let's say you want a number between 2.5 and 4.5. The range is 2.0 (4.5 - 2.5). `NextDouble` only returns a number between 0 and 1.0, but if you multiply this by the range you will get a number between 0 and *range*.
So, this would give us random doubles between 0.0 and 2.0:
```
rng.NextDouble() * 2.0
```
But, we want them between 2.5 and 4.5! How do we do this? Add the smallest number, 2.5:
```
2.5 + rng.NextDouble() * 2.0
```
Now, we get a number between 0.0 and 2.0; if you add 2.5 to each of these values we see that the range is now between 2.5 and 4.5.
At first I thought that it mattered if b > a or a > b, but if you work it out both ways you'll find it works out identically so long as you don't mess up the order of the variables used. I like to express it with longer variable names so I don't get mixed up:
```
double NextDouble(Random rng, double min, double max)
{
return min + (rng.NextDouble() * (max - min));
}
``` |
44,470 | <p>Every time I publish the application in <a href="http://en.wikipedia.org/wiki/ClickOnce" rel="nofollow noreferrer">ClickOnce</a> I get get it to update the revision number by one. Is there a way to get this change automatically to change the version number in AssemblyInfo.cs file (all our error reporting looks at the Assembly Version)?</p>
| [
{
"answer_id": 44606,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 0,
"selected": false,
"text": "<p>You'll probably need to create a piece of code that updates AssemblyInfo.cs according to the version number st... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3798/"
] | Every time I publish the application in [ClickOnce](http://en.wikipedia.org/wiki/ClickOnce) I get get it to update the revision number by one. Is there a way to get this change automatically to change the version number in AssemblyInfo.cs file (all our error reporting looks at the Assembly Version)? | We use Team Foundation Server Team Build and have added a block to the TFSBuild.proj's `AfterCompile` target to trigger the ClickOnce publish with our preferred version number:
```xml
<MSBuild Projects="$(SolutionRoot)\MyProject\Myproject.csproj"
Properties="PublishDir=$(OutDir)\myProjectPublish\;
ApplicationVersion=$(PublishApplicationVersion);
Configuration=$(Configuration);Platform=$(Platform)"
Targets="Publish" />
```
The `PublishApplicationVersion` variable is generated by a custom MSBuild task to use the TFS Changeset number, but you could use [your own custom task](http://msdn.microsoft.com/en-us/library/t9883dzc.aspx) or an [existing solution](http://msbuildtasks.tigris.org/) to get the version number from the AssemblyInfo file.
This could theoretically be done in your project file (which is just an MSBuild script anyway), but I'd recommend against deploying from a developer machine.
I'm sure other [continuous integration](http://en.wikipedia.org/wiki/Continuous_integration) (CI) solutions can handle this similarly.
---
**Edit:** Sorry, got your question backwards. Going from the ClickOnce version number to the AssemblyInfo file should be doable. I'm sure the MSBuild Community Tasks (link above) have a task for updating the AssemblyInfo file, so you'd just need a custom task to pull the version number from the ClickOnce configuration XML.
However, you may also consider changing your error reporting to include the ClickOnce publish version too:
```cs
if (System.Deployment.Application.ApplicationDeployment.IsNetworkDeployed)
{
Debug.WriteLine(System.Deployment.Application.ApplicationDeployment.
CurrentDeployment.CurrentVersion);
}
``` |
44,481 | <p>For this directory structure:</p>
<pre><code>.
|-- README.txt
|-- firstlevel.rb
`-- lib
|-- models
| |-- foo
| | `-- fourthlevel.rb
| `-- thirdlevel.rb
`-- secondlevel.rb
3 directories, 5 files
</code></pre>
<p>The glob would match: </p>
<pre><code>firstlevel.rb
lib/secondlevel.rb
lib/models/thirdlevel.rb
lib/models/foo/fourthlevel.rb
</code></pre>
| [
{
"answer_id": 44486,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 1,
"selected": false,
"text": "<p>In Ruby itself:</p>\n\n<pre><code>Dir.glob('**/*.rb') perhaps?\n</code></pre>\n"
},
{
"answer_id": 44494,
... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3624/"
] | For this directory structure:
```
.
|-- README.txt
|-- firstlevel.rb
`-- lib
|-- models
| |-- foo
| | `-- fourthlevel.rb
| `-- thirdlevel.rb
`-- secondlevel.rb
3 directories, 5 files
```
The glob would match:
```
firstlevel.rb
lib/secondlevel.rb
lib/models/thirdlevel.rb
lib/models/foo/fourthlevel.rb
``` | Apologies if I've missed the real point of the question but, if I was using sh/bash/etc., then I would probably use *find* to do the job:
```
find . -name '*.rb' -type f
```
Globs can get a bit nasty when used from within a script and *find* is much more flexible. |
44,542 | <p>Can someome provide code or pseudo-code for how the paging links on StackOverflow are generated?</p>
<p>I keep racking my brain but can't think of a decent way to build the dynamic links that always show the 2 pages around the current, plus the first and last.</p>
<p>Example: <code>1 ... 5 6 7 ... 593</code></p>
| [
{
"answer_id": 44560,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 1,
"selected": false,
"text": "<p>Well, if you know the current page, it's pretty trivial to just subtract the number by 1, and add it by 1, then check tho... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1097/"
] | Can someome provide code or pseudo-code for how the paging links on StackOverflow are generated?
I keep racking my brain but can't think of a decent way to build the dynamic links that always show the 2 pages around the current, plus the first and last.
Example: `1 ... 5 6 7 ... 593` | There are several other answers already, but I'd like to show you the approach I took to solve it:
First, let's check out how Stack Overflow handles normal cases and edge cases. Each of my pages displays 10 results, so to find out what it does for 1 page, find a tag that has less than 11 entries: [usability](https://stackoverflow.com/questions/tagged/usability) works today. We can see nothing is displayed, which makes sense.
How about 2 pages? Find a tag that has between 11 and 20 entries ([emacs](https://stackoverflow.com/questions/tagged/emacs) works today). We see: "**1** 2 Next" or "Prev 1 **2**", depending on which page we're on.
3 pages? "**1** 2 3 ... 3 Next", "Prev 1 **2** 3 Next", and "Prev 1 ... 2 **3**". Interestingly, we can see that Stack Overflow itself doesn't handle this edge case very well: it should display "**1** 2 ... 3 Next"
4 pages? "**1** 2 3 ... 4 Next", "Prev 1 **2** 3 ... 4 Next", "Prev 1 ... 2 **3** 4 Next" and "Prev 1 ... 3 **4**"
Finally let's look at the general case, N pages: "**1** 2 3 ... N Next", "Prev 1 **2** 3 ... N Next", "Prev 1 ... 2 **3** 4 ... N Next", "Prev 1 ... 3 **4** 5 ... N Next", etc.
Let's generalize based on what we've seen:
The algorithm seems to have these traits in common:
* If we're not on the first page, display link to Prev
* Always display the first page number
* Always display the current page number
* Always display the page before this page, and the page after this page.
* Always display the last page number
* If we're not on the last page, display link to Next
Let's ignore the edge case of a single page and make a good first attempt at the algorithm: (As has been mentioned, the code to actually print out the links would be more complicated. Imagine each place we place a page number, Prev or Next as a function call that will return the correct URL.)
```
function printPageLinksFirstTry(num totalPages, num currentPage)
if ( currentPage > 1 )
print "Prev"
print "1"
print "..."
print currentPage - 1
print currentPage
print currentPage + 1
print "..."
print totalPages
if ( currentPage < totalPages )
print "Next"
endFunction
```
This function works ok, but it doesn't take into account whether we're near the first or last page. Looking at the above examples, we only want to display the ... if the current page is two or more away.
```
function printPageLinksHandleCloseToEnds(num totalPages, num currentPage)
if ( currentPage > 1 )
print "Prev"
print "1"
if ( currentPage > 2 )
print "..."
if ( currentPage > 2 )
print currentPage - 1
print currentPage
if ( currentPage < totalPages - 1 )
print currentPage + 1
if ( currentPage < totalPages - 1 )
print "..."
print totalPages
if ( currentPage < totalPages )
print "Next"
endFunction
```
As you can see, we have some duplication here. We can go ahead and clean that up for readibility:
```
function printPageLinksCleanedUp(num totalPages, num currentPage)
if ( currentPage > 1 )
print "Prev"
print "1"
if ( currentPage > 2 )
print "..."
print currentPage - 1
print currentPage
if ( currentPage < totalPages - 1 )
print currentPage + 1
print "..."
print totalPages
if ( currentPage < totalPages )
print "Next"
endFunction
```
There are only two problems left. First, we don't print out correctly for one page, and secondly, we'll print out "1" twice if we're on the first or last page. Let's clean those both up in one go:
```
function printPageLinksFinal(num totalPages, num currentPage)
if ( totalPages == 1 )
return
if ( currentPage > 1 )
print "Prev"
print "1"
if ( currentPage > 2 )
print "..."
print currentPage - 1
if ( currentPage != 1 and currentPage != totalPages )
print currentPage
if ( currentPage < totalPages - 1 )
print currentPage + 1
print "..."
print totalPages
if ( currentPage < totalPages )
print "Next"
endFunction
```
Actually, I lied: We have one remaining issue. When you have at least 4 pages and are on the first or last page, you get an extra page in your display. Instead of "**1** 2 ... 10 Next" you get "**1** 2 3 ... 10 Next". To match what's going on at Stack Overflow exactly, you'll have to check for this situation:
```
function printPageLinksFinalReally(num totalPages, num currentPage)
if ( totalPages == 1 )
return
if ( currentPage > 1 )
print "Prev"
print "1"
if ( currentPage > 2 )
print "..."
if ( currentPage == totalPages and totalPages > 3 )
print currentPage - 2
print currentPage - 1
if ( currentPage != 1 and currentPage != totalPages )
print currentPage
if ( currentPage < totalPages - 1 )
print currentPage + 1
if ( currentPage == 1 and totalPages > 3 )
print currentPage + 2
print "..."
print totalPages
if ( currentPage < totalPages )
print "Next"
endFunction
```
I hope this helps! |
44,569 | <p>I have never used octal numbers in my code nor come across any code that used it (hexadecimal and bit twiddling notwithstanding).</p>
<p>I started programming in C/C++ about 1994 so maybe I'm too young for this? Does older code use octal? C includes support for these by prepending a 0, but where is the code that uses these base 8 number literals?</p>
| [
{
"answer_id": 44575,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>It's useful for the <code>chmod</code> and <code>mkdir</code> functions in Unix land, but aside from that I can't think... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2543/"
] | I have never used octal numbers in my code nor come across any code that used it (hexadecimal and bit twiddling notwithstanding).
I started programming in C/C++ about 1994 so maybe I'm too young for this? Does older code use octal? C includes support for these by prepending a 0, but where is the code that uses these base 8 number literals? | I recently had to write network protocol code that accesses 3-bit fields. Octal comes in handy when you want to debug that.
Just for effect, can you tell me what the 3-bit fields of this are?
```
0x492492
```
On the other hand, this same number in octal:
```
022222222
```
Now, finally, in binary (in groups of 3):
```
010 010 010 010 010 010 010 010
``` |
44,617 | <p>I would like to be able to add a "message" to a unit test, such that it actually appears within the TestResult.xml file generated by NUnit. For example, this is currently generated:</p>
<pre><code><results>
<test-case name="MyNamespace.Tests.MyTest" executed="True" success="True" time="0.203" asserts="4" />
</results>
</code></pre>
<p>I would like to be able to have an additional attribute (or node as the case may be), such as:</p>
<pre><code><results>
<test-case name="MyNamespace.Tests.MyTest" executed="True" success="True" time="0.203" asserts="4" message="Tested that some condition was met." />
</results>
</code></pre>
<p>The idea is that "message" above would somehow be defined within the test method itself (in my case, generated at run-time). Is there a property somewhere that I'm missing to be able to do something like this?</p>
| [
{
"answer_id": 44653,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 3,
"selected": true,
"text": "<p>This may be missing the point, but how about naming the tests so they indicate what they test - then you may not even ... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2696/"
] | I would like to be able to add a "message" to a unit test, such that it actually appears within the TestResult.xml file generated by NUnit. For example, this is currently generated:
```
<results>
<test-case name="MyNamespace.Tests.MyTest" executed="True" success="True" time="0.203" asserts="4" />
</results>
```
I would like to be able to have an additional attribute (or node as the case may be), such as:
```
<results>
<test-case name="MyNamespace.Tests.MyTest" executed="True" success="True" time="0.203" asserts="4" message="Tested that some condition was met." />
</results>
```
The idea is that "message" above would somehow be defined within the test method itself (in my case, generated at run-time). Is there a property somewhere that I'm missing to be able to do something like this? | This may be missing the point, but how about naming the tests so they indicate what they test - then you may not even need the message.
If it proves to be absolutely necessary, I think you'll need to produce your own testrunner that would (off the top of my head) read an additional attribute off the TestCase and attach it to the output. |
44,656 | <p>The code that I want to write is like this:</p>
<pre><code>void MethodOnThreadA()
{
for (;;)
{
// Do stuff
if (ErrorConditionMet)
ThrowOnThread(threadB, new MyException(...));
}
}
void MethodOnThreadB()
{
try
{
for (;;)
{
// Do stuff
}
}
catch (MyException ex)
{
// Do the right thing for this exception.
}
}
</code></pre>
<p>I know I can have thread B periodically check, in thread safe way, to see if a flag has been set by thread A, but that makes the code more complicated. Is there a better mechanism that I can use?</p>
<p>Here is a more fleshed out example of periodically checking:</p>
<pre><code>Dictionary<Thread, Exception> exceptionDictionary = new Dictionary<Thread, Exception>();
void ThrowOnThread(Thread thread, Exception ex)
{
// the exception passed in is going to be handed off to another thread,
// so it needs to be thread safe.
lock (exceptionDictionary)
{
exceptionDictionary[thread] = ex;
}
}
void ExceptionCheck()
{
lock (exceptionDictionary)
{
Exception ex;
if (exceptionDictionary.TryGetValue(Thread.CurrentThread, out ex))
throw ex;
}
}
void MethodOnThreadA()
{
for (;;)
{
// Do stuff
if (ErrorConditionMet)
ThrowOnThread(threadB, new MyException(...));
}
}
void MethodOnThreadB()
{
try
{
for (;;)
{
// Do stuff
ExceptionCheck();
}
}
catch (MyException ex)
{
// Do the right thing for this exception.
}
}
</code></pre>
| [
{
"answer_id": 44661,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 3,
"selected": false,
"text": "<p>There are enough problems with exceptions that can be thrown on threads by other mechanisms, like aborting threads ... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4592/"
] | The code that I want to write is like this:
```
void MethodOnThreadA()
{
for (;;)
{
// Do stuff
if (ErrorConditionMet)
ThrowOnThread(threadB, new MyException(...));
}
}
void MethodOnThreadB()
{
try
{
for (;;)
{
// Do stuff
}
}
catch (MyException ex)
{
// Do the right thing for this exception.
}
}
```
I know I can have thread B periodically check, in thread safe way, to see if a flag has been set by thread A, but that makes the code more complicated. Is there a better mechanism that I can use?
Here is a more fleshed out example of periodically checking:
```
Dictionary<Thread, Exception> exceptionDictionary = new Dictionary<Thread, Exception>();
void ThrowOnThread(Thread thread, Exception ex)
{
// the exception passed in is going to be handed off to another thread,
// so it needs to be thread safe.
lock (exceptionDictionary)
{
exceptionDictionary[thread] = ex;
}
}
void ExceptionCheck()
{
lock (exceptionDictionary)
{
Exception ex;
if (exceptionDictionary.TryGetValue(Thread.CurrentThread, out ex))
throw ex;
}
}
void MethodOnThreadA()
{
for (;;)
{
// Do stuff
if (ErrorConditionMet)
ThrowOnThread(threadB, new MyException(...));
}
}
void MethodOnThreadB()
{
try
{
for (;;)
{
// Do stuff
ExceptionCheck();
}
}
catch (MyException ex)
{
// Do the right thing for this exception.
}
}
``` | This is NOT a good idea
[This article talks about ruby's timeout library.](http://blog.headius.com/2008/02/rubys-threadraise-threadkill-timeoutrb.html) which throws exceptions across threads.
It explains how doing such a thing is fundamentally broken. It's not just broken in ruby, it's broken anywhere that throws exceptions across threads.
In a nutshell, what can (and does) happen is this:
ThreadA:
```
At some random time, throw an exception on thread B:
```
ThreadB:
```
try {
//do stuff
} finally {
CloseResourceOne();
// ThreadA's exception gets thrown NOW, in the middle
// of our finally block and resource two NEVER gets closed.
// Obviously this is BAD, and the only way to stop is to NOT throw
// exceptions across threads
CloseResourceTwo();
}
```
Your 'periodic checking' example is fine, as you're not actually throwing exceptions across threads.
You're just setting a flag which says "throw an exception the next time you look at this flag", which is fine as it doesn't suffer from the "can be thrown in the middle of your catch or finally block" problem.
However, if you're going to do that, you may as well just be setting an "exitnow" flag, and using that and save yourself the hassle of creating the exception object. A volatile bool will work just fine for that. |
44,693 | <p>In C++, what alternatives do I have for exposing a collection, from the point of view of performance and data integrity?</p>
<p>My problem is that I want to return an internal list of data to the caller, but I don't want to generate a copy. Thant leaves me with either returning a reference to the list, or a pointer to the list. However, I'm not crazy about letting the caller change the data, I just want to let it read the data. </p>
<ul>
<li>Do I have to choose between performance and data integrity? </li>
<li>If so, is in general better to go one way or is it particular to the case? </li>
<li>Are there other alternatives?</li>
</ul>
| [
{
"answer_id": 44697,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe something like this?</p>\n\n<pre><code>const std::vector<mydata>& getData()\n{\n return _myPrivateDat... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3081/"
] | In C++, what alternatives do I have for exposing a collection, from the point of view of performance and data integrity?
My problem is that I want to return an internal list of data to the caller, but I don't want to generate a copy. Thant leaves me with either returning a reference to the list, or a pointer to the list. However, I'm not crazy about letting the caller change the data, I just want to let it read the data.
* Do I have to choose between performance and data integrity?
* If so, is in general better to go one way or is it particular to the case?
* Are there other alternatives? | [RichQ's answer](https://stackoverflow.com/questions/44693/in-c-what-alternatives-do-i-have-for-exposing-a-collection-from-the-point-of-vi#44734) is a reasonable technique, if you're using an array, vector, etc.
If you're using a collection that isn't indexed by ordinal values... or think you *might need to* at some point in the near future... then you might want to consider exposing your own iterator type(s), and associated `begin()`/`end()` methods:
```
class Blah
{
public:
typedef std::vector<mydata> mydata_collection;
typedef myDataCollection::const_iterator mydata_const_iterator;
// ...
mydata_const_iterator data_begin() const
{ return myPreciousData.begin(); }
mydata_const_iterator data_end() const
{ return myPreciousData.end(); }
private:
mydata_collection myPreciousData;
};
```
...which you can then use in the normal fashion:
```
Blah blah;
for (Blah::mydata_const_iterator itr = blah.data_begin();
itr != blah.data_end();
++itr)
{
// ...
}
``` |
44,715 | <p>Ruby setters—whether created by <code>(c)attr_accessor</code> or manually—seem to be the only methods that need <code>self.</code> qualification when accessed within the class itself. This seems to put Ruby alone the world of languages:</p>
<ul>
<li>All methods need <code>self</code>/<code>this</code> (like Perl, and I think Javascript)</li>
<li>No methods require <code>self</code>/<code>this</code> is (C#, Java)</li>
<li>Only setters need <code>self</code>/<code>this</code> (Ruby?)</li>
</ul>
<p>The best comparison is C# vs Ruby, because both languages support accessor methods which work syntactically just like class instance variables: <code>foo.x = y</code>, <code>y = foo.x</code> . C# calls them properties.</p>
<p>Here's a simple example; the same program in Ruby then C#:</p>
<pre><code>class A
def qwerty; @q; end # manual getter
def qwerty=(value); @q = value; end # manual setter, but attr_accessor is same
def asdf; self.qwerty = 4; end # "self." is necessary in ruby?
def xxx; asdf; end # we can invoke nonsetters w/o "self."
def dump; puts "qwerty = #{qwerty}"; end
end
a = A.new
a.xxx
a.dump
</code></pre>
<p>take away the <code>self.qwerty =()</code> and it fails (Ruby 1.8.6 on Linux & OS X). Now C#:</p>
<pre><code>using System;
public class A {
public A() {}
int q;
public int qwerty {
get { return q; }
set { q = value; }
}
public void asdf() { qwerty = 4; } // C# setters work w/o "this."
public void xxx() { asdf(); } // are just like other methods
public void dump() { Console.WriteLine("qwerty = {0}", qwerty); }
}
public class Test {
public static void Main() {
A a = new A();
a.xxx();
a.dump();
}
}
</code></pre>
<p>Question: Is this true? Are there other occasions besides setters where self is necessary? I.e., are there other occasions where a Ruby method <em>cannot</em> be invoked <em>without</em> self?</p>
<p>There are certainly lots of cases where self <em>becomes</em> necessary. This is not unique to Ruby, just to be clear:</p>
<pre><code>using System;
public class A {
public A() {}
public int test { get { return 4; }}
public int useVariable() {
int test = 5;
return test;
}
public int useMethod() {
int test = 5;
return this.test;
}
}
public class Test {
public static void Main() {
A a = new A();
Console.WriteLine("{0}", a.useVariable()); // prints 5
Console.WriteLine("{0}", a.useMethod()); // prints 4
}
}
</code></pre>
<p>Same ambiguity is resolved in same way. But while subtle I'm asking about the case where </p>
<ul>
<li>A method <em>has</em> been defined, and</li>
<li><em>No</em> local variable has been defined, and</li>
</ul>
<p>we encounter</p>
<pre><code>qwerty = 4
</code></pre>
<p>which is ambiguous—is this a method invocation or an new local variable assignment?</p>
<hr>
<p>@Mike Stone</p>
<p>Hi! I understand and appreciate the points you've made and your
example was great. Believe me when I say, if I had enough reputation,
I'd vote up your response. Yet we still disagree: </p>
<ul>
<li>on a matter of semantics, and</li>
<li>on a central point of fact</li>
</ul>
<p>First I claim, not without irony, we're having a semantic debate about the
meaning of 'ambiguity'.</p>
<p>When it comes to parsing and programming language semantics (the subject
of this question), surely you would admit a broad spectrum of the notion
'ambiguity'. Let's just adopt some random notation: </p>
<ol>
<li>ambiguous: lexical ambiguity (lex must 'look ahead')</li>
<li>Ambiguous: grammatical ambiguity (yacc must defer to parse-tree analysis)</li>
<li>AMBIGUOUS: ambiguity knowing everything at the moment of execution</li>
</ol>
<p>(and there's junk between 2-3 too). All these categories are resolved by
gathering more contextual info, looking more and more globally. So when you
say,</p>
<blockquote>
<p>"qwerty = 4" is UNAMBIGUOUS in C#
when there is no variable defined...</p>
</blockquote>
<p>I couldn't agree more. But by the same token, I'm saying </p>
<blockquote>
<p>"qwerty = 4" is un-Ambiguous in ruby
(as it now exists)</p>
<p>"qwerty = 4" is Ambiguous in C#</p>
</blockquote>
<p>And we're not yet contradicting each other. Finally, here's where we really
disagree: Either ruby could or could not be implemented without any further
language constructs such that,</p>
<blockquote>
<p>For "qwerty = 4," ruby UNAMBIGUOUSLY
invokes an existing setter if there<br>
is no local variable defined</p>
</blockquote>
<p>You say no. I say yes; another ruby could exist which behaves exactly like
the current in every respect, <em>except</em> "qwerty = 4" defines a new
variable when no setter and no local exists, it invokes the setter if one
exists, and it assigns to the local if one exists. I fully accept that I
could be wrong. In fact, a reason why I might be wrong would be interesting.</p>
<p>Let me explain.</p>
<p>Imagine you are writing a new OO language with accessor methods looking
like instances vars (like ruby & C#). You'd probably start with
conceptual grammars something like:</p>
<pre><code> var = expr // assignment
method = expr // setter method invocation
</code></pre>
<p>But the parser-compiler (not even the runtime) will puke, because even after
all the input is grokked there's no way to know which grammar is pertinent.
You're faced which a classic choice. I can't be sure of the details, but
basically ruby does this:</p>
<pre><code> var = expr // assignment (new or existing)
// method = expr, disallow setter method invocation without .
</code></pre>
<p>that is why it's un-Ambiguous, while and C# does this:</p>
<pre><code> symbol = expr // push 'symbol=' onto parse tree and decide later
// if local variable is def'd somewhere in scope: assignment
// else if a setter is def'd in scope: invocation
</code></pre>
<p>For C#, 'later' is still at compile time.</p>
<p>I'm sure ruby could do the same, but 'later' would have to be at runtime, because
as ben points out you don't know until the statement is executed which case
applies.</p>
<p>My question was never intended to mean "do I really need the 'self.'?" or "what
potential ambiguity is being avoided?" Rather I wanted to know why was this
particular choice made? Maybe it's not performance. Maybe it just got the job
done, or it was considered best to always allow a 1-liner local to override a
method (a pretty rare case requirement) ...</p>
<p>But I'm sort of suggesting that the most dynamical language might be the one which
postpones this decision the longest, and chooses semantics based on the most contextual
info: so if you have no local and you defined a setter, it would use the setter. Isn't
this why we like ruby, smalltalk, objc, because method invocation is decided at runtime,
offering maximum expressiveness?</p>
| [
{
"answer_id": 44779,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 6,
"selected": false,
"text": "<p>Well, I think the reason this is the case is because <code>qwerty = 4</code> is ambiguous—are you defining a new variable... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4615/"
] | Ruby setters—whether created by `(c)attr_accessor` or manually—seem to be the only methods that need `self.` qualification when accessed within the class itself. This seems to put Ruby alone the world of languages:
* All methods need `self`/`this` (like Perl, and I think Javascript)
* No methods require `self`/`this` is (C#, Java)
* Only setters need `self`/`this` (Ruby?)
The best comparison is C# vs Ruby, because both languages support accessor methods which work syntactically just like class instance variables: `foo.x = y`, `y = foo.x` . C# calls them properties.
Here's a simple example; the same program in Ruby then C#:
```
class A
def qwerty; @q; end # manual getter
def qwerty=(value); @q = value; end # manual setter, but attr_accessor is same
def asdf; self.qwerty = 4; end # "self." is necessary in ruby?
def xxx; asdf; end # we can invoke nonsetters w/o "self."
def dump; puts "qwerty = #{qwerty}"; end
end
a = A.new
a.xxx
a.dump
```
take away the `self.qwerty =()` and it fails (Ruby 1.8.6 on Linux & OS X). Now C#:
```
using System;
public class A {
public A() {}
int q;
public int qwerty {
get { return q; }
set { q = value; }
}
public void asdf() { qwerty = 4; } // C# setters work w/o "this."
public void xxx() { asdf(); } // are just like other methods
public void dump() { Console.WriteLine("qwerty = {0}", qwerty); }
}
public class Test {
public static void Main() {
A a = new A();
a.xxx();
a.dump();
}
}
```
Question: Is this true? Are there other occasions besides setters where self is necessary? I.e., are there other occasions where a Ruby method *cannot* be invoked *without* self?
There are certainly lots of cases where self *becomes* necessary. This is not unique to Ruby, just to be clear:
```
using System;
public class A {
public A() {}
public int test { get { return 4; }}
public int useVariable() {
int test = 5;
return test;
}
public int useMethod() {
int test = 5;
return this.test;
}
}
public class Test {
public static void Main() {
A a = new A();
Console.WriteLine("{0}", a.useVariable()); // prints 5
Console.WriteLine("{0}", a.useMethod()); // prints 4
}
}
```
Same ambiguity is resolved in same way. But while subtle I'm asking about the case where
* A method *has* been defined, and
* *No* local variable has been defined, and
we encounter
```
qwerty = 4
```
which is ambiguous—is this a method invocation or an new local variable assignment?
---
@Mike Stone
Hi! I understand and appreciate the points you've made and your
example was great. Believe me when I say, if I had enough reputation,
I'd vote up your response. Yet we still disagree:
* on a matter of semantics, and
* on a central point of fact
First I claim, not without irony, we're having a semantic debate about the
meaning of 'ambiguity'.
When it comes to parsing and programming language semantics (the subject
of this question), surely you would admit a broad spectrum of the notion
'ambiguity'. Let's just adopt some random notation:
1. ambiguous: lexical ambiguity (lex must 'look ahead')
2. Ambiguous: grammatical ambiguity (yacc must defer to parse-tree analysis)
3. AMBIGUOUS: ambiguity knowing everything at the moment of execution
(and there's junk between 2-3 too). All these categories are resolved by
gathering more contextual info, looking more and more globally. So when you
say,
>
> "qwerty = 4" is UNAMBIGUOUS in C#
> when there is no variable defined...
>
>
>
I couldn't agree more. But by the same token, I'm saying
>
> "qwerty = 4" is un-Ambiguous in ruby
> (as it now exists)
>
>
> "qwerty = 4" is Ambiguous in C#
>
>
>
And we're not yet contradicting each other. Finally, here's where we really
disagree: Either ruby could or could not be implemented without any further
language constructs such that,
>
> For "qwerty = 4," ruby UNAMBIGUOUSLY
> invokes an existing setter if there
>
> is no local variable defined
>
>
>
You say no. I say yes; another ruby could exist which behaves exactly like
the current in every respect, *except* "qwerty = 4" defines a new
variable when no setter and no local exists, it invokes the setter if one
exists, and it assigns to the local if one exists. I fully accept that I
could be wrong. In fact, a reason why I might be wrong would be interesting.
Let me explain.
Imagine you are writing a new OO language with accessor methods looking
like instances vars (like ruby & C#). You'd probably start with
conceptual grammars something like:
```
var = expr // assignment
method = expr // setter method invocation
```
But the parser-compiler (not even the runtime) will puke, because even after
all the input is grokked there's no way to know which grammar is pertinent.
You're faced which a classic choice. I can't be sure of the details, but
basically ruby does this:
```
var = expr // assignment (new or existing)
// method = expr, disallow setter method invocation without .
```
that is why it's un-Ambiguous, while and C# does this:
```
symbol = expr // push 'symbol=' onto parse tree and decide later
// if local variable is def'd somewhere in scope: assignment
// else if a setter is def'd in scope: invocation
```
For C#, 'later' is still at compile time.
I'm sure ruby could do the same, but 'later' would have to be at runtime, because
as ben points out you don't know until the statement is executed which case
applies.
My question was never intended to mean "do I really need the 'self.'?" or "what
potential ambiguity is being avoided?" Rather I wanted to know why was this
particular choice made? Maybe it's not performance. Maybe it just got the job
done, or it was considered best to always allow a 1-liner local to override a
method (a pretty rare case requirement) ...
But I'm sort of suggesting that the most dynamical language might be the one which
postpones this decision the longest, and chooses semantics based on the most contextual
info: so if you have no local and you defined a setter, it would use the setter. Isn't
this why we like ruby, smalltalk, objc, because method invocation is decided at runtime,
offering maximum expressiveness? | The important thing to remember here is that Ruby methods can be (un)defined at any point, so to intelligently resolve the ambiguity, every assignment would need to run code to check whether there is a method with the assigned-to name at the time of assignment. |
44,771 | <p>Ok, so my method in my webservice requires a type to be passed, it is called in the ServiceMethod property of the AutoCompleteExtender, I am fuzzy about how I should do that so I called it like this:</p>
<pre><code>ServiceMethod="DropDownLoad<<%=(typeof)subCategory%>>"
</code></pre>
<p>where subCategory is a page property that looks like this:</p>
<pre><code>protected SubCategory subCategory
{
get
{
var subCategory = NHibernateObjectHelper.LoadDataObject<SubCategory>(Convert.ToInt32(Request.QueryString["SCID"]));
return subCategory;
}
}
</code></pre>
| [
{
"answer_id": 44923,
"author": "bentford",
"author_id": 946,
"author_profile": "https://Stackoverflow.com/users/946",
"pm_score": 2,
"selected": true,
"text": "<p>I dont' think calling a Generic Method on a webservice is possible.</p>\n\n<p>If you look at the service description of two ... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4140/"
] | Ok, so my method in my webservice requires a type to be passed, it is called in the ServiceMethod property of the AutoCompleteExtender, I am fuzzy about how I should do that so I called it like this:
```
ServiceMethod="DropDownLoad<<%=(typeof)subCategory%>>"
```
where subCategory is a page property that looks like this:
```
protected SubCategory subCategory
{
get
{
var subCategory = NHibernateObjectHelper.LoadDataObject<SubCategory>(Convert.ToInt32(Request.QueryString["SCID"]));
return subCategory;
}
}
``` | I dont' think calling a Generic Method on a webservice is possible.
If you look at the service description of two identical methods, one generic, one not:
```
[WebMethod]
public string[] GetSearchList(string prefixText, int count)
{
}
[WebMethod]
public string[] GetSearchList2<T>(string prefixText, int count)
{
}
```
They are identical. It appears that both SOAP 1.x and HTTP POST do not allow this type of operation. |
44,778 | <p>What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, <code>['a', 'b', 'c']</code> to <code>'a,b,c'</code>? (The cases <code>['s']</code> and <code>[]</code> should be mapped to <code>'s'</code> and <code>''</code>, respectively.)</p>
<p>I usually end up using something like <code>''.join(map(lambda x: x+',',l))[:-1]</code>, but also feeling somewhat unsatisfied.</p>
| [
{
"answer_id": 44781,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 11,
"selected": true,
"text": "<pre><code>my_list = ['a', 'b', 'c', 'd']\nmy_string = ','.join(my_list)\n</code></pre>\n\n<pre><code>'a,b,c,d'\n</code></pre... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44778",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4285/"
] | What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, `['a', 'b', 'c']` to `'a,b,c'`? (The cases `['s']` and `[]` should be mapped to `'s'` and `''`, respectively.)
I usually end up using something like `''.join(map(lambda x: x+',',l))[:-1]`, but also feeling somewhat unsatisfied. | ```
my_list = ['a', 'b', 'c', 'd']
my_string = ','.join(my_list)
```
```
'a,b,c,d'
```
This won't work if the list contains integers
---
And if the list contains non-string types (such as integers, floats, bools, None) then do:
```
my_string = ','.join(map(str, my_list))
``` |
44,780 | <p>What's the best way to implement a SQL script that will grant select, references, insert, update, and delete permissions to a database role on all the user tables in a database?</p>
<p>Ideally, this script could be run multiple times, as new tables were added to the database. SQL Server Management Studio generates scripts for individual database objects, but I'm looking for more of a "fire-and-forget" script.</p>
| [
{
"answer_id": 44841,
"author": "Dr Zimmerman",
"author_id": 4605,
"author_profile": "https://Stackoverflow.com/users/4605",
"pm_score": 2,
"selected": false,
"text": "<p>I'm sure there is an easier way, but you could loop through the sysobjects table in the database and grant permission... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3475/"
] | What's the best way to implement a SQL script that will grant select, references, insert, update, and delete permissions to a database role on all the user tables in a database?
Ideally, this script could be run multiple times, as new tables were added to the database. SQL Server Management Studio generates scripts for individual database objects, but I'm looking for more of a "fire-and-forget" script. | Dr Zimmerman is on the right track here. I'd be looking to write a stored procedure that has a cursor looping through user objects using execute immediate to affect the grant. Something like this:
```
IF EXISTS (
SELECT 1 FROM sysobjects
WHERE name = 'sp_grantastic'
AND type = 'P'
)
DROP PROCEDURE sp_grantastic
GO
CREATE PROCEDURE sp_grantastic
AS
DECLARE
@object_name VARCHAR(30)
,@time VARCHAR(8)
,@rights VARCHAR(20)
,@role VARCHAR(20)
DECLARE c_objects CURSOR FOR
SELECT name
FROM sysobjects
WHERE type IN ('P', 'U', 'V')
FOR READ ONLY
BEGIN
SELECT @rights = 'ALL'
,@role = 'PUBLIC'
OPEN c_objects
WHILE (1=1)
BEGIN
FETCH c_objects INTO @object_name
IF @@SQLSTATUS <> 0 BREAK
SELECT @time = CONVERT(VARCHAR, GetDate(), 108)
PRINT '[%1!] hitting up object %2!', @time, @object_name
EXECUTE('GRANT '+ @rights +' ON '+ @object_name+' TO '+@role)
END
PRINT '[%1!] fin!', @time
CLOSE c_objects
DEALLOCATE CURSOR c_objects
END
GO
GRANT ALL ON sp_grantastic TO PUBLIC
GO
```
Then you can fire and forget:
```
EXEC sp_grantastic
``` |
44,787 | <p>Scenario: You have an ASP.Net webpage that should display the next image in a series of images. If 1.jpg is currently loaded, the refresh should load 2.jpg.<br>
Assuming I would use this code, where do you get the current images name.</p>
<pre><code>string currImage = MainPic.ImageUrl.Replace(".jpg", "");
currImage = currImage.Replace("~/Images/", "");
int num = (Convert.ToInt32(currImage) + 1) % 3;
MainPic.ImageUrl = "~/Images/" + num.ToString() + ".jpg";
</code></pre>
<p>The problem with the above code is that the webpage used is the default site with the image set to 1.jpg, so the loaded image is always 2.jpg.<br>
So in the process of loading the page, is it possible to pull the last image used from the pages properties?</p>
| [
{
"answer_id": 44802,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 0,
"selected": false,
"text": "<p>You'll have to hide the last value in a HiddenField or ViewState or somewhere like that...</p>\n"
},
{
"answer_id":... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4298/"
] | Scenario: You have an ASP.Net webpage that should display the next image in a series of images. If 1.jpg is currently loaded, the refresh should load 2.jpg.
Assuming I would use this code, where do you get the current images name.
```
string currImage = MainPic.ImageUrl.Replace(".jpg", "");
currImage = currImage.Replace("~/Images/", "");
int num = (Convert.ToInt32(currImage) + 1) % 3;
MainPic.ImageUrl = "~/Images/" + num.ToString() + ".jpg";
```
The problem with the above code is that the webpage used is the default site with the image set to 1.jpg, so the loaded image is always 2.jpg.
So in the process of loading the page, is it possible to pull the last image used from the pages properties? | ```
int num = 1;
if(Session["ImageNumber"] != null)
{
num = Convert.ToInt32(Session["ImageNumber"]) + 1;
}
Session["ImageNumber"] = num;
``` |
44,799 | <p>We're currently building an application that executes a number of external tools. We often have to pass information entered into our system by users to these tools.</p>
<p>Obviously, this is a big security nightmare waiting to happen.</p>
<p>Unfortunately, we've not yet found any classes in the .NET Framework that execute command line programs while providing the same kind of guards against injection attacks as the IDbCommand objects do for databases.</p>
<p>Right now, we're using a very primitive string substitution which I suspect is rather insufficient:</p>
<blockquote>
<pre><code>protected virtual string Escape(string value)
{
return value
.Replace(@"\", @"\\")
.Replace(@"$", @"\$")
.Replace(@"""", @"\""")
.Replace("`", "'")
;
}
</code></pre>
</blockquote>
<p>What do you guys do to prevent command-line injection attacks? We're planning to implement a regex that is very strict and only allows a very small subset of characters through, but I was wondering if there was a better way.</p>
<p>Some clarifications:</p>
<ul>
<li>Some of these tools do not have APIs we can program against. If they did, we wouldn't be having this problem.</li>
<li>The users don't pick tools to execute, they enter meta-data which the tools we've chosen use (for example, injecting meta data such as copyright notices into target files). </li>
</ul>
| [
{
"answer_id": 44807,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 4,
"selected": true,
"text": "<p>Are you executing the programs directly or going through the shell? If you always launch an external program by giv... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44799",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1931/"
] | We're currently building an application that executes a number of external tools. We often have to pass information entered into our system by users to these tools.
Obviously, this is a big security nightmare waiting to happen.
Unfortunately, we've not yet found any classes in the .NET Framework that execute command line programs while providing the same kind of guards against injection attacks as the IDbCommand objects do for databases.
Right now, we're using a very primitive string substitution which I suspect is rather insufficient:
>
>
> ```
> protected virtual string Escape(string value)
> {
> return value
> .Replace(@"\", @"\\")
> .Replace(@"$", @"\$")
> .Replace(@"""", @"\""")
> .Replace("`", "'")
> ;
> }
>
> ```
>
>
What do you guys do to prevent command-line injection attacks? We're planning to implement a regex that is very strict and only allows a very small subset of characters through, but I was wondering if there was a better way.
Some clarifications:
* Some of these tools do not have APIs we can program against. If they did, we wouldn't be having this problem.
* The users don't pick tools to execute, they enter meta-data which the tools we've chosen use (for example, injecting meta data such as copyright notices into target files). | Are you executing the programs directly or going through the shell? If you always launch an external program by giving the full path name to the executable and leaving the shell out of the equation, then you aren't really susceptible to any kind of command line injection.
EDIT: DrFloyd, the shell is responsible for evaluating things like the backtick. No shell, no shell evaluation. Obviously, you've still got to be aware of any potential security gotchas in the programs that you're calling -- but I don't think this question is about that. |
44,817 | <p>Has anyone used ADO.NET Data Services as a data source for Adobe Flex applications? If so, any success stories or tragedies to avoid? If you did use it, how did you handle security?</p>
| [
{
"answer_id": 45891,
"author": "Adam Cuzzort",
"author_id": 4760,
"author_profile": "https://Stackoverflow.com/users/4760",
"pm_score": 3,
"selected": true,
"text": "<p>I use WebORB for .NET to do Flex remoting and then use DLINQ on the server. One tricky thing about using LINQ with Web... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44817",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4541/"
] | Has anyone used ADO.NET Data Services as a data source for Adobe Flex applications? If so, any success stories or tragedies to avoid? If you did use it, how did you handle security? | I use WebORB for .NET to do Flex remoting and then use DLINQ on the server. One tricky thing about using LINQ with WebORB is that WebORB uses Reflection to automatically retrieve all the relationships of the object(s) you return to Flex. This causes severe time penalties as LINQ uses lazy loading to load relationships. To prevent this from happening, I do something like the following:
Override your DataContext's constructor and add the following code:
```
this.DeferredLoadingEnabled = false;
DataLoadOptions dlo = new DataLoadOptions();
dlo.LoadWith<Order>(q => q.Payments);
dlo.LoadWith<Order>(q => q.Customer);
this.LoadOptions = dlo;
```
This tells the DataContext to disable deferred loading of relationships and specifically instructs it to load just the relationships you want, without lazy loading. That way, WebORB isn't causing any lazy loading to happen through Reflection and the number of relationships being transferred to Flex is kept at a minimum.
Hope this helps you in some way. It's definitely one of those little "gotchas" when working with Flex/WebORB and LINQ. |
44,853 | <p>I'm using ant to generate javadocs, but get this exception over and over - why?</p>
<p>I'm using JDK version <strong>1.6.0_06</strong>.</p>
<pre><code>[javadoc] java.lang.ClassCastException: com.sun.tools.javadoc.ClassDocImpl cannot be cast to com.sun.javadoc.AnnotationTypeDoc
[javadoc] at com.sun.tools.javadoc.AnnotationDescImpl.annotationType(AnnotationDescImpl.java:46)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.getAnnotations(HtmlDocletWriter.java:1739)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1713)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1702)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1681)
[javadoc] at com.sun.tools.doclets.formats.html.FieldWriterImpl.writeSignature(FieldWriterImpl.java:130)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildSignature(FieldBuilder.java:184)
[javadoc] at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildFieldDoc(FieldBuilder.java:158)
[javadoc] at sun.reflect.GeneratedMethodAccessor51.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildFieldDetails(ClassBuilder.java:301)
[javadoc] at sun.reflect.GeneratedMethodAccessor43.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildClassDoc(ClassBuilder.java:124)
[javadoc] at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.build(ClassBuilder.java:108)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.generateClassFiles(HtmlDoclet.java:155)
[javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.generateClassFiles(AbstractDoclet.java:164)
[javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.startGeneration(AbstractDoclet.java:106)
[javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.start(AbstractDoclet.java:64)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.start(HtmlDoclet.java:42)
[javadoc] at com.sun.tools.doclets.standard.Standard.start(Standard.java:23)
[javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.javadoc.DocletInvoker.invoke(DocletInvoker.java:215)
[javadoc] at com.sun.tools.javadoc.DocletInvoker.start(DocletInvoker.java:91)
[javadoc] at com.sun.tools.javadoc.Start.parseAndExecute(Start.java:340)
[javadoc] at com.sun.tools.javadoc.Start.begin(Start.java:128)
[javadoc] at com.sun.tools.javadoc.Main.execute(Main.java:41)
[javadoc] at com.sun.tools.javadoc.Main.main(Main.java:31)
</code></pre>
| [
{
"answer_id": 44870,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 7,
"selected": true,
"text": "<p>It looks like this has been reported as a <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6442982\" rel=\... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
] | I'm using ant to generate javadocs, but get this exception over and over - why?
I'm using JDK version **1.6.0\_06**.
```
[javadoc] java.lang.ClassCastException: com.sun.tools.javadoc.ClassDocImpl cannot be cast to com.sun.javadoc.AnnotationTypeDoc
[javadoc] at com.sun.tools.javadoc.AnnotationDescImpl.annotationType(AnnotationDescImpl.java:46)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.getAnnotations(HtmlDocletWriter.java:1739)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1713)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1702)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1681)
[javadoc] at com.sun.tools.doclets.formats.html.FieldWriterImpl.writeSignature(FieldWriterImpl.java:130)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildSignature(FieldBuilder.java:184)
[javadoc] at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildFieldDoc(FieldBuilder.java:158)
[javadoc] at sun.reflect.GeneratedMethodAccessor51.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildFieldDetails(ClassBuilder.java:301)
[javadoc] at sun.reflect.GeneratedMethodAccessor43.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildClassDoc(ClassBuilder.java:124)
[javadoc] at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90)
[javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.build(ClassBuilder.java:108)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.generateClassFiles(HtmlDoclet.java:155)
[javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.generateClassFiles(AbstractDoclet.java:164)
[javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.startGeneration(AbstractDoclet.java:106)
[javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.start(AbstractDoclet.java:64)
[javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.start(HtmlDoclet.java:42)
[javadoc] at com.sun.tools.doclets.standard.Standard.start(Standard.java:23)
[javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
[javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
[javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
[javadoc] at java.lang.reflect.Method.invoke(Method.java:597)
[javadoc] at com.sun.tools.javadoc.DocletInvoker.invoke(DocletInvoker.java:215)
[javadoc] at com.sun.tools.javadoc.DocletInvoker.start(DocletInvoker.java:91)
[javadoc] at com.sun.tools.javadoc.Start.parseAndExecute(Start.java:340)
[javadoc] at com.sun.tools.javadoc.Start.begin(Start.java:128)
[javadoc] at com.sun.tools.javadoc.Main.execute(Main.java:41)
[javadoc] at com.sun.tools.javadoc.Main.main(Main.java:31)
``` | It looks like this has been reported as a [Java bug](http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6442982). It appears to be caused by using annotations from a 3rd party library (like JUnit) and not including the jar with that annotation in the javadoc invocation.
If that is the case, just use the -classpath option on javadoc and include the extra jar files. |
44,864 | <p>For example I have a situation where I have something like this (contrived) example:</p>
<pre><code><div id="outer" style="margin: auto>
<div id="inner1" style="float: left">content</div>
<div id="inner2" style="float: left">content</div>
<div id="inner3" style="float: left">content</div>
<br style="clear: both"/>
</div>
</code></pre>
<p>where there are no widths set on any elements, and what I want is <code>#inner1</code>, <code>#inner2</code> and <code>#inner3</code> to appear next to each other horizontally inside <code>#outer</code> but what is happening is that <code>#inner1</code> and <code>#inner2</code> are appearing next to each other and then <code>#inner3</code> is wrapping on to the next line.</p>
<p>In the actual page where this is happening there is a lot more going on, but I have inspected all of the elements very carefully with Firebug and do not understand why the <code>#inner3</code> element is not appearing on the same line as <code>#inner1</code> and <code>#inner2</code> and causing <code>#outer</code> to get wider.</p>
<p>So, my question is: Is there any way to determine <strong>why</strong> the browser is sizing #outer the way it is, or why it is choosing to wrap <code>#inner3</code> even though there is plenty of room to put it on the previous "line"? Baring specific solutions to this problem, what tips or techniques do you hardcore HTML/CSS/Web UI guys have for a poor back end developer who has found himself working on the front end?</p>
| [
{
"answer_id": 44872,
"author": "Simon Young",
"author_id": 4330,
"author_profile": "https://Stackoverflow.com/users/4330",
"pm_score": 2,
"selected": false,
"text": "<p>Try the <a href=\"https://addons.mozilla.org/en-US/firefox/addon/60\" rel=\"nofollow noreferrer\">Web Developer Plugin... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] | For example I have a situation where I have something like this (contrived) example:
```
<div id="outer" style="margin: auto>
<div id="inner1" style="float: left">content</div>
<div id="inner2" style="float: left">content</div>
<div id="inner3" style="float: left">content</div>
<br style="clear: both"/>
</div>
```
where there are no widths set on any elements, and what I want is `#inner1`, `#inner2` and `#inner3` to appear next to each other horizontally inside `#outer` but what is happening is that `#inner1` and `#inner2` are appearing next to each other and then `#inner3` is wrapping on to the next line.
In the actual page where this is happening there is a lot more going on, but I have inspected all of the elements very carefully with Firebug and do not understand why the `#inner3` element is not appearing on the same line as `#inner1` and `#inner2` and causing `#outer` to get wider.
So, my question is: Is there any way to determine **why** the browser is sizing #outer the way it is, or why it is choosing to wrap `#inner3` even though there is plenty of room to put it on the previous "line"? Baring specific solutions to this problem, what tips or techniques do you hardcore HTML/CSS/Web UI guys have for a poor back end developer who has found himself working on the front end? | Try the [Web Developer Plugin](https://addons.mozilla.org/en-US/firefox/addon/60) for Firefox. Specifically, the **Information -> Display Block Size** and **Outline -> Outline Block Level Elements** options. This will allow to see the borders of your elements, and their size as Firefox sees them. |
44,903 | <p>I have multiple selects:</p>
<pre><code><select id="one">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<select id="two">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
</code></pre>
<p>What I want is to select "one" from the first select, then have that option be removed from the second one.
Then if you select "two" from the second one, I want that one removed from the first one.</p>
<p>Here's the JS I have currently:</p>
<pre><code>$(function () {
var $one = $("#one");
var $two = $("#two");
var selectOptions = [];
$("select").each(function (index) {
selectOptions[index] = [];
for (var i = 0; i < this.options.length; i++) {
selectOptions[index][i] = this.options[i];
}
});
$one.change(function () {
var selectedValue = $("option:selected", this).val();
for (var i = 0; i < selectOptions[1].length; i++) {
var exists = false;
for (var x = 0; x < $two[0].options.length; x++) {
if ($two[0].options[x].value == selectOptions[1][i].value)
exists = true;
}
if (!exists)
$two.append(selectOptions[1][i]);
}
$("option[value='" + selectedValue + "']", $two).remove();
});
$two.change(function () {
var selectedValue = $("option:selected", this).val();
for (var i = 0; i < selectOptions[0].length; i++) {
var exists = false;
for (var x = 0; x < $one[0].options.length; x++) {
if ($one[0].options[x].value == selectOptions[0][i].value)
exists = true;
}
if (!exists)
$one.append(selectOptions[0][i]);
}
$("option[value='" + selectedValue + "']", $one).remove();
});
});
</code></pre>
<p>But when the elements get repopulated, it fires the change event in the select whose options are changing. I tried just setting the <code>disabled</code> attribute on the option I want to remove, but that doesn't work with IE6.</p>
| [
{
"answer_id": 44908,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 3,
"selected": true,
"text": "<p>I am not (currently) a user of jQuery, but I can tell you that you need to temporarily disconnect your event handler ... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44903",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1414/"
] | I have multiple selects:
```
<select id="one">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<select id="two">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
```
What I want is to select "one" from the first select, then have that option be removed from the second one.
Then if you select "two" from the second one, I want that one removed from the first one.
Here's the JS I have currently:
```
$(function () {
var $one = $("#one");
var $two = $("#two");
var selectOptions = [];
$("select").each(function (index) {
selectOptions[index] = [];
for (var i = 0; i < this.options.length; i++) {
selectOptions[index][i] = this.options[i];
}
});
$one.change(function () {
var selectedValue = $("option:selected", this).val();
for (var i = 0; i < selectOptions[1].length; i++) {
var exists = false;
for (var x = 0; x < $two[0].options.length; x++) {
if ($two[0].options[x].value == selectOptions[1][i].value)
exists = true;
}
if (!exists)
$two.append(selectOptions[1][i]);
}
$("option[value='" + selectedValue + "']", $two).remove();
});
$two.change(function () {
var selectedValue = $("option:selected", this).val();
for (var i = 0; i < selectOptions[0].length; i++) {
var exists = false;
for (var x = 0; x < $one[0].options.length; x++) {
if ($one[0].options[x].value == selectOptions[0][i].value)
exists = true;
}
if (!exists)
$one.append(selectOptions[0][i]);
}
$("option[value='" + selectedValue + "']", $one).remove();
});
});
```
But when the elements get repopulated, it fires the change event in the select whose options are changing. I tried just setting the `disabled` attribute on the option I want to remove, but that doesn't work with IE6. | I am not (currently) a user of jQuery, but I can tell you that you need to temporarily disconnect your event handler while you repopulate the items or, at the least, set a flag that you then test for and based on its value, handle the change. |
44,905 | <p>When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.</p>
<p>For example (and yes, I know, if you're doing this sort of thing it probably means your <a href="https://en.wikipedia.org/wiki/Object-oriented_programming" rel="noreferrer">object-oriented</a> (OO) architecture is iffy - this is just a contrived example!),</p>
<pre><code> Type t = typeof(int);
switch (t) {
case typeof(int):
Console.WriteLine("int!");
break;
case typeof(string):
Console.WriteLine("string!");
break;
default:
Console.WriteLine("unknown!");
break;
}
</code></pre>
<p>Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.</p>
<p>Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement <em>has</em> to succumb to static analysis only, and why the value being switched on has to be integral (that is, primitive). What is the justification?</p>
| [
{
"answer_id": 44921,
"author": "Brian Ensink",
"author_id": 1254,
"author_profile": "https://Stackoverflow.com/users/1254",
"pm_score": 8,
"selected": true,
"text": "<p>This is my original post, which sparked some debate... <strong>because it is wrong</strong>:</p>\n\n<blockquote>\n <p... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] | When writing a switch statement, there appears to be two limitations on what you can switch on in case statements.
For example (and yes, I know, if you're doing this sort of thing it probably means your [object-oriented](https://en.wikipedia.org/wiki/Object-oriented_programming) (OO) architecture is iffy - this is just a contrived example!),
```
Type t = typeof(int);
switch (t) {
case typeof(int):
Console.WriteLine("int!");
break;
case typeof(string):
Console.WriteLine("string!");
break;
default:
Console.WriteLine("unknown!");
break;
}
```
Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'.
Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement *has* to succumb to static analysis only, and why the value being switched on has to be integral (that is, primitive). What is the justification? | This is my original post, which sparked some debate... **because it is wrong**:
>
> The switch statement is not the same
> thing as a big if-else statement.
> Each case must be unique and evaluated
> statically. The switch statement does
> a constant time branch regardless of
> how many cases you have. The if-else
> statement evaluates each condition
> until it finds one that is true.
>
>
>
---
In fact, the C# switch statement is **not** always a constant time branch.
In some cases the compiler will use a CIL switch statement which is indeed a constant time branch using a jump table. However, in sparse cases as pointed out by [Ivan Hamilton](https://stackoverflow.com/questions/44905/c-switch-statement-limitations-why#48259) the compiler may generate something else entirely.
This is actually quite easy to verify by writing various C# switch statements, some sparse, some dense, and looking at the resulting CIL with the ildasm.exe tool. |
44,917 | <p>Is there any efficiency difference in an explicit vs implicit inner join?
For example:</p>
<pre><code>SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;
</code></pre>
<p>vs.</p>
<pre><code>SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;
</code></pre>
| [
{
"answer_id": 44932,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 8,
"selected": true,
"text": "<p>Performance wise, they are exactly the same (at least in SQL Server).</p>\n\n<p>PS: Be aware that the <code>IMPLICIT OUTER JOI... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4316/"
] | Is there any efficiency difference in an explicit vs implicit inner join?
For example:
```
SELECT * FROM
table a INNER JOIN table b
ON a.id = b.id;
```
vs.
```
SELECT a.*, b.*
FROM table a, table b
WHERE a.id = b.id;
``` | Performance wise, they are exactly the same (at least in SQL Server).
PS: Be aware that the `IMPLICIT OUTER JOIN` syntax is deprecated since SQL Server 2005. (The `IMPLICIT INNER JOIN` syntax as used in the question is still supported)
[Deprecation of "Old Style" JOIN Syntax: Only A Partial Thing](https://learn.microsoft.com/en-us/archive/blogs/wardpond/deprecation-of-old-style-join-syntax-only-a-partial-thing) |
44,937 | <p>I want to make an etag that matches what Apache produces. How does apache create it's etags?</p>
| [
{
"answer_id": 44939,
"author": "Chris Bartow",
"author_id": 497,
"author_profile": "https://Stackoverflow.com/users/497",
"pm_score": 5,
"selected": true,
"text": "<p>Apache uses the standard format of inode-filesize-mtime. The only caveat to this is that the mtime must be epoch time a... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/497/"
] | I want to make an etag that matches what Apache produces. How does apache create it's etags? | Apache uses the standard format of inode-filesize-mtime. The only caveat to this is that the mtime must be epoch time and padded with zeros so it is 16 digits. Here is how to do it in PHP:
```
$fs = stat($file);
header("Etag: ".sprintf('"%x-%x-%s"', $fs['ino'], $fs['size'],base_convert(str_pad($fs['mtime'],16,"0"),10,16)));
``` |
44,942 | <p>Can you cast a <code>List<int></code> to <code>List<string></code> somehow?</p>
<p>I know I could loop through and .ToString() the thing, but a cast would be awesome.</p>
<p>I'm in C# 2.0 (so no <a href="http://en.wikipedia.org/wiki/Language_Integrated_Query" rel="noreferrer">LINQ</a>).</p>
| [
{
"answer_id": 44949,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 3,
"selected": false,
"text": "<p>Is C# 2.0 able to do <code>List<T>.Convert</code>? If so, I think your best guess would be to use that with a ... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44942",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/493/"
] | Can you cast a `List<int>` to `List<string>` somehow?
I know I could loop through and .ToString() the thing, but a cast would be awesome.
I'm in C# 2.0 (so no [LINQ](http://en.wikipedia.org/wiki/Language_Integrated_Query)). | .NET 2.0 has the `ConvertAll` method where you can pass in a converter function:
```
List<int> l1 = new List<int>(new int[] { 1, 2, 3 } );
List<string> l2 = l1.ConvertAll<string>(delegate(int i) { return i.ToString(); });
``` |
44,961 | <p>I've searched on the Internet for comparisons between <a href="http://en.wikipedia.org/wiki/F_Sharp_%28programming_language%29" rel="noreferrer">F#</a> and <a href="http://en.wikipedia.org/wiki/Haskell_%28programming_language%29" rel="noreferrer">Haskell</a> but haven't found anything really definitive. What are the primary differences and why would I want to choose one over the other?</p>
| [
{
"answer_id": 44969,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 2,
"selected": false,
"text": "<p>Well, for one I'd say a main advantage is that F# compiles against the .NET platform which makes it easy to deploy o... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] | I've searched on the Internet for comparisons between [F#](http://en.wikipedia.org/wiki/F_Sharp_%28programming_language%29) and [Haskell](http://en.wikipedia.org/wiki/Haskell_%28programming_language%29) but haven't found anything really definitive. What are the primary differences and why would I want to choose one over the other? | Haskell is a "pure" functional language, where as F# has aspects of both imperative/OO and functional languages. Haskell also has lazy evaluation, which is fairly rare amongst functional languages.
What do these things mean? A pure functional language, means there are no side effects (or changes in shared state, when a function is called) which means that you are guaranteed that if you call f(x), nothing else happens besides returning a value from the function, such as console output, database output, changes to global or static variables.. and although Haskell can have non pure functions (through monads), it must be 'explicitly' implied through declaration.
Pure functional languages and 'No side effect' programming has gained popularity recently as it lends itself well to multi core concurrency, as it is much harder to get wrong with no shared state, rather than myriad locks & semaphores.
Lazy evaluation is where a function is NOT evaluated until it is absolutely necessary required. meaning that many operation can be avoided when not necessary. Think of this in a basic C# if clause such as this:
```
if(IsSomethingTrue() && AnotherThingTrue())
{
do something;
}
```
If `IsSomethingTrue()` is false then `AnotherThingTrue()` method is never evaluated.
While Haskell is an amazing language, the major benefit of F# (for the time being), is that it sits on top of the CLR. This lends it self to polyglot programming. One day, you may write your web UI in ASP.net MVC, your business logic in C#, your core algorithms in F# and your unit tests in Ironruby.... All amongst the the .Net framework.
Listen to the Software Engineering radio with Simon Peyton Jones for more info on Haskell: [Episode 108: Simon Peyton Jones on Functional Programming and Haskell](http://www.se-radio.net/2008/08/episode-108-simon-peyton-jones-on-functional-programming-and-haskell/) |
44,965 | <p>Having briefly looked at Haskell recently, what would be a <em>brief, succinct, practical</em> explanation as to what a monad essentially is?</p>
<p>I have found most explanations I've come across to be fairly inaccessible and lacking in practical detail.</p>
| [
{
"answer_id": 2538,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 7,
"selected": false,
"text": "<p>But, <a href=\"http://blog.sigfpe.com/2006/08/you-could-have-invented-monads-and.html\" rel=\"noreferrer\">You could have i... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44965",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] | Having briefly looked at Haskell recently, what would be a *brief, succinct, practical* explanation as to what a monad essentially is?
I have found most explanations I've come across to be fairly inaccessible and lacking in practical detail. | First: The term **monad** is a bit vacuous if you are not a mathematician. An alternative term is **computation builder** which is a bit more descriptive of what they are actually useful for.
They are a pattern for chaining operations. It looks a bit like method chaining in object-oriented languages, but the mechanism is slightly different.
The pattern is mostly used in functional languages (especially Haskell which uses monads pervasively) but can be used in any language which support higher-order functions (that is, functions which can take other functions as arguments).
Arrays in JavaScript support the pattern, so let’s use that as the first example.
The gist of the pattern is we have a type (`Array` in this case) which has a method which takes a function as argument. The operation supplied must return an instance of the same type (i.e. return an `Array`).
First an example of method chaining which does *not* use the monad pattern:
```
[1,2,3].map(x => x + 1)
```
The result is `[2,3,4]`. The code does not conform to the monad pattern, since the function we are supplying as an argument returns a number, not an Array. The same logic in monad form would be:
```
[1,2,3].flatMap(x => [x + 1])
```
Here we supply an operation which returns an `Array`, so now it conforms to the pattern. The [`flatMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap) method executes the provided function for every element in the array. It expects an array as result for each invocation (rather than single values), but merges the resulting set of arrays into a single array. So the end result is the same, the array `[2,3,4]`.
(The function argument provided to a method like `map` or `flatMap` is often called a "callback" in JavaScript. I will call it the "operation" since it is more general.)
If we chain multiple operations (in the traditional way):
```
[1,2,3].map(a => a + 1).filter(b => b != 3)
```
Results in the array `[2,4]`
The same chaining in monad form:
```
[1,2,3].flatMap(a => [a + 1]).flatMap(b => b != 3 ? [b] : [])
```
Yields the same result, the array `[2,4]`.
You will immediately notice that the monad form is quite a bit uglier than the non-monad! This just goes to show that monads are not necessarily “good”. They are a pattern which is sometimes beneficial and sometimes not.
Do note that the monad pattern can be combined in a different way:
```
[1,2,3].flatMap(a => [a + 1].flatMap(b => b != 3 ? [b] : []))
```
Here the binding is nested rather than chained, but the result is the same. This is an important property of monads as we will see later. It means two operations combined can be treated the same as a single operation.
The operation is allowed to return an array with different element types, for example transforming an array of numbers into an array of strings or something else; as long as it still an Array.
This can be described a bit more formally using Typescript notation. An array has the type `Array<T>`, where `T` is the type of the elements in the array. The method `flatMap()` takes a function argument of the type `T => Array<U>` and returns an `Array<U>`.
Generalized, a monad is any type `Foo<Bar>` which has a "bind" method which takes a function argument of type `Bar => Foo<Baz>` and returns a `Foo<Baz>`.
This answers *what* monads are. The rest of this answer will try to explain through examples why monads can be a useful pattern in a language like Haskell which has good support for them.
**Haskell and Do-notation**
To translate the map/filter example directly to Haskell, we replace `flatMap` with the `>>=` operator:
```
[1,2,3] >>= \a -> [a+1] >>= \b -> if b == 3 then [] else [b]
```
The `>>=` operator is the bind function in Haskell. It does the same as `flatMap` in JavaScript when the operand is a list, but it is overloaded with different meaning for other types.
But Haskell also has a dedicated syntax for monad expressions, the `do`-block, which hides the bind operator altogether:
```
do a <- [1,2,3]
b <- [a+1]
if b == 3 then [] else [b]
```
This hides the "plumbing" and lets you focus on the actual operations applied at each step.
In a `do`-block, each line is an operation. The constraint still holds that all operations in the block must return the same type. Since the first expression is a list, the other operations must also return a list.
The back-arrow `<-` looks deceptively like an assignment, but note that this is the parameter passed in the bind. So, when the expression on the right side is a List of Integers, the variable on the left side will be a single Integer – but will be executed for each integer in the list.
**Example: Safe navigation (the Maybe type)**
Enough about lists, lets see how the monad pattern can be useful for other types.
Some functions may not always return a valid value. In Haskell this is represented by the `Maybe`-type, which is an option that is either `Just value` or `Nothing`.
Chaining operations which always return a valid value is of course straightforward:
```
streetName = getStreetName (getAddress (getUser 17))
```
But what if any of the functions could return `Nothing`? We need to check each result individually and only pass the value to the next function if it is not `Nothing`:
```
case getUser 17 of
Nothing -> Nothing
Just user ->
case getAddress user of
Nothing -> Nothing
Just address ->
getStreetName address
```
Quite a lot of repetitive checks! Imagine if the chain was longer. Haskell solves this with the monad pattern for `Maybe`:
```
do
user <- getUser 17
addr <- getAddress user
getStreetName addr
```
This `do`-block invokes the bind-function for the `Maybe` type (since the result of the first expression is a `Maybe`). The bind-function only executes the following operation if the value is `Just value`, otherwise it just passes the `Nothing` along.
Here the monad-pattern is used to avoid repetitive code. This is similar to how some other languages use macros to simplify syntax, although macros achieve the same goal in a very different way.
Note that it is the *combination* of the monad pattern and the monad-friendly syntax in Haskell which result in the cleaner code. In a language like JavaScript without any special syntax support for monads, I doubt the monad pattern would be able to simplify the code in this case.
**Mutable state**
Haskell does not support mutable state. All variables are constants and all values immutable. But the `State` type can be used to emulate programming with mutable state:
```
add2 :: State Integer Integer
add2 = do
-- add 1 to state
x <- get
put (x + 1)
-- increment in another way
modify (+1)
-- return state
get
evalState add2 7
=> 9
```
The `add2` function builds a monad chain which is then evaluated with 7 as the initial state.
Obviously this is something which only makes sense in Haskell. Other languages support mutable state out of the box. Haskell is generally "opt-in" on language features - you enable mutable state when you need it, and the type system ensures the effect is explicit. IO is another example of this.
**IO**
The `IO` type is used for chaining and executing “impure” functions.
Like any other practical language, Haskell has a bunch of built-in functions which interface with the outside world: `putStrLine`, `readLine` and so on. These functions are called “impure” because they either cause side effects or have non-deterministic results. Even something simple like getting the time is considered impure because the result is non-deterministic – calling it twice with the same arguments may return different values.
A pure function is deterministic – its result depends purely on the arguments passed and it has no side effects on the environment beside returning a value.
Haskell heavily encourages the use of pure functions – this is a major selling point of the language. Unfortunately for purists, you need some impure functions to do anything useful. The Haskell compromise is to cleanly separate pure and impure, and guarantee that there is no way that pure functions can execute impure functions, directly or indirect.
This is guaranteed by giving all impure functions the `IO` type. The entry point in Haskell program is the `main` function which have the `IO` type, so we can execute impure functions at the top level.
But how does the language prevent pure functions from executing impure functions? This is due to the lazy nature of Haskell. A function is only executed if its output is consumed by some other function. But there is no way to consume an `IO` value except to assign it to `main`. So if a function wants to execute an impure function, it has to be connected to `main` and have the `IO` type.
Using monad chaining for IO operations also ensures that they are executed in a linear and predictable order, just like statements in an imperative language.
This brings us to the first program most people will write in Haskell:
```
main :: IO ()
main = do
putStrLn ”Hello World”
```
The `do` keyword is superfluous when there is only a single operation and therefore nothing to bind, but I keep it anyway for consistency.
The `()` type means “void”. This special return type is only useful for IO functions called for their side effect.
A longer example:
```
main = do
putStrLn "What is your name?"
name <- getLine
putStrLn "hello" ++ name
```
This builds a chain of `IO` operations, and since they are assigned to the `main` function, they get executed.
Comparing `IO` with `Maybe` shows the versatility of the monad pattern. For `Maybe`, the pattern is used to avoid repetitive code by moving conditional logic to the binding function. For `IO`, the pattern is used to ensure that all operations of the `IO` type are sequenced and that `IO` operations cannot "leak" to pure functions.
**Summing up**
In my subjective opinion, the monad pattern is only really worthwhile in a language which has some built-in support for the pattern. Otherwise it just leads to overly convoluted code. But Haskell (and some other languages) have some built-in support which hides the tedious parts, and then the pattern can be used for a variety of useful things. Like:
* Avoiding repetitive code (`Maybe`)
* Adding language features like mutable state or exceptions for delimited areas of the program.
* Isolating icky stuff from nice stuff (`IO`)
* Embedded domain-specific languages (`Parser`)
* Adding GOTO to the language. |
44,980 | <p>How can one determine, in code, how long the machine is locked?</p>
<p>Other ideas outside of C# are also welcome.</p>
<hr>
<p>I like the windows service idea (and have accepted it) for simplicity and cleanliness, but unfortunately I don't think it will work for me in this particular case. I wanted to run this on my workstation at work rather than home (or in addition to home, I suppose), but it's locked down pretty hard courtesy of the DoD. That's part of the reason I'm rolling my own, actually.</p>
<p>I'll write it up anyway and see if it works. Thanks everyone!</p>
| [
{
"answer_id": 44987,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Below is the 100% working code to find if the PC is locked or not.</p>\n\n<p>Before using this use the namespace <code>Syst... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1588/"
] | How can one determine, in code, how long the machine is locked?
Other ideas outside of C# are also welcome.
---
I like the windows service idea (and have accepted it) for simplicity and cleanliness, but unfortunately I don't think it will work for me in this particular case. I wanted to run this on my workstation at work rather than home (or in addition to home, I suppose), but it's locked down pretty hard courtesy of the DoD. That's part of the reason I'm rolling my own, actually.
I'll write it up anyway and see if it works. Thanks everyone! | I hadn't found this before, but from any application you can hookup a SessionSwitchEventHandler. Obviously your application will need to be running, but so long as it is:
```
Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
{
if (e.Reason == SessionSwitchReason.SessionLock)
{
//I left my desk
}
else if (e.Reason == SessionSwitchReason.SessionUnlock)
{
//I returned to my desk
}
}
``` |
44,989 | <p>I'm trying to get the following bit of code to work in LINQPad but am unable to index into a var. Anybody know how to index into a var in LINQ?</p>
<pre><code>string[] sa = {"one", "two", "three"};
sa[1].Dump();
var va = sa.Select( (a,i) => new {Line = a, Index = i});
va[1].Dump();
// Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<AnonymousType#1>'
</code></pre>
| [
{
"answer_id": 44991,
"author": "Joseph Daigle",
"author_id": 507,
"author_profile": "https://Stackoverflow.com/users/507",
"pm_score": 5,
"selected": true,
"text": "<p>As the comment says, you cannot apply indexing with <code>[]</code> to an expression of type <code>System.Collections.G... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1463/"
] | I'm trying to get the following bit of code to work in LINQPad but am unable to index into a var. Anybody know how to index into a var in LINQ?
```
string[] sa = {"one", "two", "three"};
sa[1].Dump();
var va = sa.Select( (a,i) => new {Line = a, Index = i});
va[1].Dump();
// Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<AnonymousType#1>'
``` | As the comment says, you cannot apply indexing with `[]` to an expression of type `System.Collections.Generic.IEnumerable<T>`. The IEnumerable interface only supports the method `GetEnumerator()`. However with LINQ you can call the extension method `ElementAt(int)`. |
44,999 | <p>I have a "showall" query string parameter in the url, the parameter is being added dynamically when "Show All/Show Pages" button is clicked. </p>
<p>I want the ability to toggle "showall" query string parameter value depending on user clicking the "Show All/Show Pages" button.</p>
<p>I'm doing some nested "if's" and <code>string.Replace()</code> on the url, is there a better way?</p>
<p>All manipulations are done on the server.</p>
<p><strong>p.s.</strong> Toran, good suggestion, however I HAVE TO USE URL PARAMETER due to some other issues.</p>
| [
{
"answer_id": 45003,
"author": "Toran Billups",
"author_id": 2701,
"author_profile": "https://Stackoverflow.com/users/2701",
"pm_score": 0,
"selected": false,
"text": "<p>Another dirty alternative could be just to use a hidden input and set that on/off instead of manipulating the url.</... | 2008/09/04 | [
"https://Stackoverflow.com/questions/44999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661/"
] | I have a "showall" query string parameter in the url, the parameter is being added dynamically when "Show All/Show Pages" button is clicked.
I want the ability to toggle "showall" query string parameter value depending on user clicking the "Show All/Show Pages" button.
I'm doing some nested "if's" and `string.Replace()` on the url, is there a better way?
All manipulations are done on the server.
**p.s.** Toran, good suggestion, however I HAVE TO USE URL PARAMETER due to some other issues. | Just to elaborate on Toran's answer:
Use:
`<asp:HiddenField ID="ShowAll" Value="False" runat="server" />`
To toggle your state:
```
protected void ToggleState(object sender, EventArgs e)
{
//parse string as boolean, invert, and convert back to string
ShowAll.Value = (!Boolean.Parse(ShowAll.Value)).ToString();
}
``` |
45,004 | <p>Is there a way to select a parent element based on the class of a child element in the class? The example that is relevant to me relating to HTML output by a nice menu plugin for <a href="http://drupal.org" rel="noreferrer">http://drupal.org</a>. The output renders like this: </p>
<pre><code><ul class="menu">
<li>
<a class="active">Active Page</a>
</li>
<li>
<a>Some Other Page</a>
</li>
</ul>
</code></pre>
<p>My question is whether or not it is possible to apply a style to the list item that contains the anchor with the active class on it. Obviously, I'd prefer that the list item be marked as active, but I don't have control of the code that gets produced. I could perform this sort of thing using javascript (JQuery springs to mind), but I was wondering if there is a way to do this using CSS selectors.</p>
<p>Just to be clear, I want to apply a style to the list item, not the anchor.</p>
| [
{
"answer_id": 45008,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 8,
"selected": true,
"text": "<p>Unfortunately, there's no way to do that with CSS.</p>\n\n<p>It's not very difficult with JavaScript though:</p>\n\n<pre><cod... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4640/"
] | Is there a way to select a parent element based on the class of a child element in the class? The example that is relevant to me relating to HTML output by a nice menu plugin for <http://drupal.org>. The output renders like this:
```
<ul class="menu">
<li>
<a class="active">Active Page</a>
</li>
<li>
<a>Some Other Page</a>
</li>
</ul>
```
My question is whether or not it is possible to apply a style to the list item that contains the anchor with the active class on it. Obviously, I'd prefer that the list item be marked as active, but I don't have control of the code that gets produced. I could perform this sort of thing using javascript (JQuery springs to mind), but I was wondering if there is a way to do this using CSS selectors.
Just to be clear, I want to apply a style to the list item, not the anchor. | Unfortunately, there's no way to do that with CSS.
It's not very difficult with JavaScript though:
```
// JavaScript code:
document.getElementsByClassName("active")[0].parentNode;
// jQuery code:
$('.active').parent().get(0); // This would be the <a>'s parent <li>.
``` |
45,015 | <p>Given a string of JSON data, how can I safely turn that string into a JavaScript object?</p>
<p>Obviously I can do this unsafely with something like:</p>
<pre><code>var obj = eval("(" + json + ')');
</code></pre>
<p>but that leaves me vulnerable to the JSON string containing other code, which it seems very dangerous to simply eval.</p>
| [
{
"answer_id": 45019,
"author": "Mark Biek",
"author_id": 305,
"author_profile": "https://Stackoverflow.com/users/305",
"pm_score": 5,
"selected": false,
"text": "<p>I'm not sure about other ways to do it but here's how you do it in <a href=\"http://www.prototypejs.org/learn/json\" rel=\... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/797/"
] | Given a string of JSON data, how can I safely turn that string into a JavaScript object?
Obviously I can do this unsafely with something like:
```
var obj = eval("(" + json + ')');
```
but that leaves me vulnerable to the JSON string containing other code, which it seems very dangerous to simply eval. | [`JSON.parse(jsonString)`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) is a pure JavaScript approach so long as you can guarantee a reasonably modern browser. |
45,030 | <p>I'm wanting to parse a string into a nullable int in C#. ie. I want to get back either the int value of the string or null if it can't be parsed.</p>
<p>I was kind of hoping that this would work</p>
<pre><code>int? val = stringVal as int?;
</code></pre>
<p>But that won't work, so the way I'm doing it now is I've written this extension method</p>
<pre><code>public static int? ParseNullableInt(this string value)
{
if (value == null || value.Trim() == string.Empty)
{
return null;
}
else
{
try
{
return int.Parse(value);
}
catch
{
return null;
}
}
}
</code></pre>
<p>Is there a better way of doing this?</p>
<p><strong>EDIT:</strong> Thanks for the TryParse suggestions, I did know about that, but it worked out about the same. I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?</p>
| [
{
"answer_id": 45037,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 10,
"selected": true,
"text": "<p><code>int.TryParse</code> is probably a tad easier:</p>\n\n<pre><code>public static int? ToNullableInt(this string s)\... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2975/"
] | I'm wanting to parse a string into a nullable int in C#. ie. I want to get back either the int value of the string or null if it can't be parsed.
I was kind of hoping that this would work
```
int? val = stringVal as int?;
```
But that won't work, so the way I'm doing it now is I've written this extension method
```
public static int? ParseNullableInt(this string value)
{
if (value == null || value.Trim() == string.Empty)
{
return null;
}
else
{
try
{
return int.Parse(value);
}
catch
{
return null;
}
}
}
```
Is there a better way of doing this?
**EDIT:** Thanks for the TryParse suggestions, I did know about that, but it worked out about the same. I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int? | `int.TryParse` is probably a tad easier:
```
public static int? ToNullableInt(this string s)
{
int i;
if (int.TryParse(s, out i)) return i;
return null;
}
```
**Edit** @Glenn `int.TryParse` is "built into the framework". It and `int.Parse` are *the* way to parse strings to ints. |
45,036 | <p>The .NET <a href="http://msdn.microsoft.com/en-us/library/system.idisposable.aspx" rel="noreferrer">IDisposable Pattern</a> <em>implies</em> that if you write a finalizer, and implement IDisposable, that your finalizer needs to explicitly call Dispose.
This is logical, and is what I've always done in the rare situations where a finalizer is warranted.</p>
<p>However, what happens if I just do this:</p>
<pre><code>class Foo : IDisposable
{
public void Dispose(){ CloseSomeHandle(); }
}
</code></pre>
<p>and don't implement a finalizer, or anything. Will the framework call the Dispose method for me?</p>
<p>Yes I realise this sounds dumb, and all logic implies that it won't, but I've always had 2 things at the back of my head which have made me unsure.</p>
<ol>
<li><p>Someone a few years ago once told me that it would in fact do this, and that person had a very solid track record of "knowing their stuff."</p></li>
<li><p>The compiler/framework does other 'magic' things depending on what interfaces you implement (eg: foreach, extension methods, serialization based on attributes, etc), so it makes sense that this might be 'magic' too. </p></li>
</ol>
<p>While I've read a lot of stuff about it, and there's been lots of things implied, I've never been able to find a <strong>definitive</strong> Yes or No answer to this question.</p>
| [
{
"answer_id": 45043,
"author": "Matt Bishop",
"author_id": 4301,
"author_profile": "https://Stackoverflow.com/users/4301",
"pm_score": 3,
"selected": false,
"text": "<p>I don't think so. You have control over when Dispose is called, which means you could in theory write disposal code th... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234/"
] | The .NET [IDisposable Pattern](http://msdn.microsoft.com/en-us/library/system.idisposable.aspx) *implies* that if you write a finalizer, and implement IDisposable, that your finalizer needs to explicitly call Dispose.
This is logical, and is what I've always done in the rare situations where a finalizer is warranted.
However, what happens if I just do this:
```
class Foo : IDisposable
{
public void Dispose(){ CloseSomeHandle(); }
}
```
and don't implement a finalizer, or anything. Will the framework call the Dispose method for me?
Yes I realise this sounds dumb, and all logic implies that it won't, but I've always had 2 things at the back of my head which have made me unsure.
1. Someone a few years ago once told me that it would in fact do this, and that person had a very solid track record of "knowing their stuff."
2. The compiler/framework does other 'magic' things depending on what interfaces you implement (eg: foreach, extension methods, serialization based on attributes, etc), so it makes sense that this might be 'magic' too.
While I've read a lot of stuff about it, and there's been lots of things implied, I've never been able to find a **definitive** Yes or No answer to this question. | The .Net Garbage Collector calls the Object.Finalize method of an object on garbage collection. By **default** this does **nothing** and must be overidden if you want to free additional resources.
Dispose is NOT automatically called and must be **explicity** called if resources are to be released, such as within a 'using' or 'try finally' block
see <http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx> for more information |
45,045 | <p>When executing SubmitChanges to the DataContext after updating a couple properties with a LINQ to SQL connection (against SQL Server Compact Edition) I get a "Row not found or changed." ChangeConflictException.</p>
<pre><code>var ctx = new Data.MobileServerDataDataContext(Common.DatabasePath);
var deviceSessionRecord = ctx.Sessions.First(sess => sess.SessionRecId == args.DeviceSessionId);
deviceSessionRecord.IsActive = false;
deviceSessionRecord.Disconnected = DateTime.Now;
ctx.SubmitChanges();
</code></pre>
<p>The query generates the following SQL:</p>
<pre><code>UPDATE [Sessions]
SET [Is_Active] = @p0, [Disconnected] = @p1
WHERE 0 = 1
-- @p0: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False]
-- @p1: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:12:02 PM]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8
</code></pre>
<p>The obvious problem is the <strong>WHERE 0=1</strong>, After the record was loaded, I've confirmed that all the properties in the "deviceSessionRecord" are correct to include the primary key. Also when catching the "ChangeConflictException" there is no additional information about why this failed. I've also confirmed that this exception get's thrown with exactly one record in the database (the record I'm attempting to update)</p>
<p>What's strange is that I have a very similar update statement in a different section of code and it generates the following SQL and does indeed update my SQL Server Compact Edition database.</p>
<pre><code>UPDATE [Sessions]
SET [Is_Active] = @p4, [Disconnected] = @p5
WHERE ([Session_RecId] = @p0) AND ([App_RecId] = @p1) AND ([Is_Active] = 1) AND ([Established] = @p2) AND ([Disconnected] IS NULL) AND ([Member_Id] IS NULL) AND ([Company_Id] IS NULL) AND ([Site] IS NULL) AND (NOT ([Is_Device] = 1)) AND ([Machine_Name] = @p3)
-- @p0: Input Guid (Size = 0; Prec = 0; Scale = 0) [0fbbee53-cf4c-4643-9045-e0a284ad131b]
-- @p1: Input Guid (Size = 0; Prec = 0; Scale = 0) [7a174954-dd18-406e-833d-8da650207d3d]
-- @p2: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:50 PM]
-- @p3: Input String (Size = 0; Prec = 0; Scale = 0) [CWMOBILEDEV]
-- @p4: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False]
-- @p5: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:52 PM]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8
</code></pre>
<p>I have confirmed that the proper primary fields values have been identified in both the Database Schema and the DBML that generates the LINQ classes.</p>
<p>I guess this is almost a two part question:</p>
<ol>
<li>Why is the exception being thrown?</li>
<li>After reviewing the second set of generated SQL, it seems like for detecting conflicts it would be nice to check all the fields, but I imagine this would be fairly inefficient. Is this the way this always works? Is there a setting to just check the primary key?</li>
</ol>
<p>I've been fighting with this for the past two hours so any help would be appreciated.</p>
| [
{
"answer_id": 83999,
"author": "Sam",
"author_id": 7021,
"author_profile": "https://Stackoverflow.com/users/7021",
"pm_score": 9,
"selected": true,
"text": "<p>Thats nasty, but simple:</p>\n\n<p>Check if the data types for all fields in the O/R-Designer match the data types in your SQL ... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2723/"
] | When executing SubmitChanges to the DataContext after updating a couple properties with a LINQ to SQL connection (against SQL Server Compact Edition) I get a "Row not found or changed." ChangeConflictException.
```
var ctx = new Data.MobileServerDataDataContext(Common.DatabasePath);
var deviceSessionRecord = ctx.Sessions.First(sess => sess.SessionRecId == args.DeviceSessionId);
deviceSessionRecord.IsActive = false;
deviceSessionRecord.Disconnected = DateTime.Now;
ctx.SubmitChanges();
```
The query generates the following SQL:
```
UPDATE [Sessions]
SET [Is_Active] = @p0, [Disconnected] = @p1
WHERE 0 = 1
-- @p0: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False]
-- @p1: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:12:02 PM]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8
```
The obvious problem is the **WHERE 0=1**, After the record was loaded, I've confirmed that all the properties in the "deviceSessionRecord" are correct to include the primary key. Also when catching the "ChangeConflictException" there is no additional information about why this failed. I've also confirmed that this exception get's thrown with exactly one record in the database (the record I'm attempting to update)
What's strange is that I have a very similar update statement in a different section of code and it generates the following SQL and does indeed update my SQL Server Compact Edition database.
```
UPDATE [Sessions]
SET [Is_Active] = @p4, [Disconnected] = @p5
WHERE ([Session_RecId] = @p0) AND ([App_RecId] = @p1) AND ([Is_Active] = 1) AND ([Established] = @p2) AND ([Disconnected] IS NULL) AND ([Member_Id] IS NULL) AND ([Company_Id] IS NULL) AND ([Site] IS NULL) AND (NOT ([Is_Device] = 1)) AND ([Machine_Name] = @p3)
-- @p0: Input Guid (Size = 0; Prec = 0; Scale = 0) [0fbbee53-cf4c-4643-9045-e0a284ad131b]
-- @p1: Input Guid (Size = 0; Prec = 0; Scale = 0) [7a174954-dd18-406e-833d-8da650207d3d]
-- @p2: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:50 PM]
-- @p3: Input String (Size = 0; Prec = 0; Scale = 0) [CWMOBILEDEV]
-- @p4: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False]
-- @p5: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:52 PM]
-- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8
```
I have confirmed that the proper primary fields values have been identified in both the Database Schema and the DBML that generates the LINQ classes.
I guess this is almost a two part question:
1. Why is the exception being thrown?
2. After reviewing the second set of generated SQL, it seems like for detecting conflicts it would be nice to check all the fields, but I imagine this would be fairly inefficient. Is this the way this always works? Is there a setting to just check the primary key?
I've been fighting with this for the past two hours so any help would be appreciated. | Thats nasty, but simple:
Check if the data types for all fields in the O/R-Designer match the data types in your SQL table.
**Double check for nullable!** A column should be either nullable in both the O/R-Designer and SQL, or not nullable in both.
For example, a NVARCHAR column "title" is marked as NULLable in your database, and contains the value NULL. Even though the column is marked as NOT NULLable in your O/R-Mapping, LINQ will load it successfully and set the column-String to null.
* Now you change something and call
SubmitChanges().
* LINQ will generate a SQL query
containing "WHERE [title] IS NULL", to make sure the title has not been changed by someone else.
* LINQ looks up the properties of
[title] in the mapping.
* LINQ will find [title] NOT NULLable.
* Since [title] is NOT NULLable, by
logic it never could be NULL!
* So, optimizing the query, LINQ
replaces it with "where 0 = 1", the
SQL equivalent of "never".
The same symptom will appear when the data types of a field does not match the data type in SQL, or if fields are missing, since LINQ will not be able to make sure the SQL data has not changed since reading the data. |
45,062 | <p>I am trying to link two fields of a given table to the same field in another table.
I have done this before so I can't work out what is wrong this time.</p>
<p>Anyway:</p>
<pre><code>Table1
- Id (Primary)
- FK-Table2a (Nullable, foreign key relationship in DB to Table2.Id)
- FK-Table2b (Nullable, foreign key relationship in DB to Table2.Id)
Table2
- Id (Primary)
</code></pre>
<p>The association works for FK-Table2a but not FK-Table2b.
In fact, when I load into LINQ to SQL, it shows Table2.Id as associated to Table1.Id.
If I try and change this, or add a new association for FK-Table2b to Table2.Id it says: "Properties do not have matching types".</p>
<p>This also works in other projects - maybe I should just copy over the .dbml?</p>
<p>Any ideas?</p>
| [
{
"answer_id": 45065,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 3,
"selected": true,
"text": "<p>No idea on the cause, but I just reconstructed my .dbml from scratch and it fixed itself.\nOh for a \"refresh\" feature... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45062",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] | I am trying to link two fields of a given table to the same field in another table.
I have done this before so I can't work out what is wrong this time.
Anyway:
```
Table1
- Id (Primary)
- FK-Table2a (Nullable, foreign key relationship in DB to Table2.Id)
- FK-Table2b (Nullable, foreign key relationship in DB to Table2.Id)
Table2
- Id (Primary)
```
The association works for FK-Table2a but not FK-Table2b.
In fact, when I load into LINQ to SQL, it shows Table2.Id as associated to Table1.Id.
If I try and change this, or add a new association for FK-Table2b to Table2.Id it says: "Properties do not have matching types".
This also works in other projects - maybe I should just copy over the .dbml?
Any ideas? | No idea on the cause, but I just reconstructed my .dbml from scratch and it fixed itself.
Oh for a "refresh" feature... |
45,075 | <p>Is there a better way to flash a window in Java than this:</p>
<pre><code>public static void flashWindow(JFrame frame) throws InterruptedException {
int sleepTime = 50;
frame.setVisible(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
Thread.sleep(sleepTime);
frame.setVisible(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
Thread.sleep(sleepTime);
frame.setVisible(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
}
</code></pre>
<p>I know that this code is scary...But it works alright. (I should implement a loop...)</p>
| [
{
"answer_id": 45234,
"author": "David Crow",
"author_id": 2783,
"author_profile": "https://Stackoverflow.com/users/2783",
"pm_score": 1,
"selected": false,
"text": "<p>Well, there are a few minor improvements we could make. ;)</p>\n\n<p>I would use a Timer to make sure callers don't hav... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
] | Is there a better way to flash a window in Java than this:
```
public static void flashWindow(JFrame frame) throws InterruptedException {
int sleepTime = 50;
frame.setVisible(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
Thread.sleep(sleepTime);
frame.setVisible(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
Thread.sleep(sleepTime);
frame.setVisible(false);
Thread.sleep(sleepTime);
frame.setVisible(true);
}
```
I know that this code is scary...But it works alright. (I should implement a loop...) | There are two common ways to do this: use JNI to set urgency hints on the taskbar's window, and create a notification icon/message. I prefer the second way, since it's cross-platform and less annoying.
See [documentation on the `TrayIcon` class](http://java.sun.com/javase/6/docs/api/java/awt/TrayIcon.html), particularly the [`displayMessage()`](http://java.sun.com/javase/6/docs/api/java/awt/TrayIcon.html#displayMessage(java.lang.String,%20java.lang.String,%20java.awt.TrayIcon.MessageType)) method.
The following links may be of interest:
* [New System Tray Functionality in Java SE 6](http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/systemtray/)
* [Java Programming - Iconified window blinking](http://forums.sun.com/thread.jspa?threadID=5130669&messageID=9469354)
* [`TrayIcon` for earlier versions of Java](https://jdic.dev.java.net/documentation/incubator/tray/) |
45,097 | <p>I assume that you can't use a JavaScript code snippet to validate if the browser user has turned off JavaScript. So what can I use instead? Can someone offer a code sample?</p>
<p>I'm looking to wrap an if/then statement around it.</p>
<p>I often code in CFML, if that helps.</p>
| [
{
"answer_id": 45102,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 3,
"selected": false,
"text": "<p>Use the <noscript> HTML tags.</p>\n"
},
{
"answer_id": 45104,
"author": "Chris Marasti-Georg",
... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I assume that you can't use a JavaScript code snippet to validate if the browser user has turned off JavaScript. So what can I use instead? Can someone offer a code sample?
I'm looking to wrap an if/then statement around it.
I often code in CFML, if that helps. | Are we talking about something like this:
JavaScript:
```
<body>
...
...
<script type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
<noscript>Your browser does not support JavaScript!</noscript>
...
...
</body>
``` |
45,123 | <p>I am designing a new System and I have a lot of Interfaces that will grow over time with the system. What is the best practice to name this interfaces</p>
<pre><code>ISomethingV01
ISomethingV02
etc
</code></pre>
<p>and I do this</p>
<pre><code>public interface ISomething{
void method();
}
</code></pre>
<p>then I have to add method 2 so now what I do?</p>
<pre><code>public interface ISomethingV2:ISomething{
void method2();
}
</code></pre>
<p>or same other way?</p>
| [
{
"answer_id": 45127,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<p>The purpose of an interface is to define an abstract pattern that at type must implement.</p>\n\n<p>It would be better imp... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1154/"
] | I am designing a new System and I have a lot of Interfaces that will grow over time with the system. What is the best practice to name this interfaces
```
ISomethingV01
ISomethingV02
etc
```
and I do this
```
public interface ISomething{
void method();
}
```
then I have to add method 2 so now what I do?
```
public interface ISomethingV2:ISomething{
void method2();
}
```
or same other way? | Ideally, you shouldn't be changing your interfaces very often (if at all). If you do need to change an interface, you should reconsider its purpose and see if the original name still applies to it.
If you still feel that the interfaces will change, and the interfaces changes are small (adding items) and you have control of the whole code base, then you should just modify the interface and fix all the compilation errors.
If your change is a change in how the interface is to be used, then you need to create a separate interface (most likely with a different name) to support that alternative usage pattern.
Even if you end up creating ISomething, ISomething2 and ISomething3, the consumers of your interfaces will have a hard time figuring out what the differences are between the interfaces. When should they use ISomething2 and when should they use ISomething3? Then you have to go about the process of obsoleting ISomething and ISomething2. |
45,132 | <p>In particular, I have to extract all the messages and attachments from Lotus Notes files in the fastest and most reliable way. Another point that may be relevant is that I need to do this from a secondary thread.</p>
<p><strong>Edit</strong></p>
<p>Thanks for the answers - both of which are good. I should provide more background information. </p>
<p>We currently have a WinForms application with a background thread using the Notes COM API. </p>
<p>However it seems to be unstable. (Of course it may be we are doing something wrong.) For example, we have found we have to preinitialize the Notes session on the main thread or else the call to session.CreateDXLExporter() on the background thread throws an exception.</p>
| [
{
"answer_id": 45143,
"author": "Joshua Turner",
"author_id": 820,
"author_profile": "https://Stackoverflow.com/users/820",
"pm_score": 2,
"selected": false,
"text": "<p>Take a look at NotesSQL:<br/></p>\n\n<p><a href=\"http://www.ibm.com/developerworks/lotus/products/notesdomino/notessq... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1899/"
] | In particular, I have to extract all the messages and attachments from Lotus Notes files in the fastest and most reliable way. Another point that may be relevant is that I need to do this from a secondary thread.
**Edit**
Thanks for the answers - both of which are good. I should provide more background information.
We currently have a WinForms application with a background thread using the Notes COM API.
However it seems to be unstable. (Of course it may be we are doing something wrong.) For example, we have found we have to preinitialize the Notes session on the main thread or else the call to session.CreateDXLExporter() on the background thread throws an exception. | I really do hate that NotesSession COM object.
You cannot use it in another thread than the thread it was initialized.
Threads in .NET are fibers, the real underlying thread may change at any time.
So I suggest using it this way, in a *using* block :
```
Imports Domino
Imports System.Threading
Public Class AffinitedSession
Implements IDisposable
Private _session As NotesSession
Public Sub New(ByVal pass As String)
Thread.BeginThreadAffinity()
_session = New NotesSession()
_session.Initialize(pass)
End Sub
Public ReadOnly Property NotesSession() As NotesSession
Get
Return _session
End Get
End Property
Private disposedValue As Boolean = False ' To detect redundant calls
' IDisposable
Protected Overridable Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposedValue Then
If disposing Then
' TODO: free other state (managed objects).
End If
' TODO: free your own state (unmanaged objects).
' TODO: set large fields to null.
_session = Nothing
Thread.EndThreadAffinity()
End If
Me.disposedValue = True
End Sub
#Region " IDisposable Support "
' This code added by Visual Basic to correctly implement the disposable pattern.
Public Sub Dispose() Implements IDisposable.Dispose
' Do not change this code. Put cleanup code in Dispose(ByVal disposing As Boolean) above.
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
#End Region
End Class
```
Notice the Thread.BeginThreadAffinity() and the Thread.EndThreadAffinity()
Those are your friends.
Cheers ! |
45,135 | <p>Why does the order in which libraries are linked sometimes cause errors in GCC?</p>
| [
{
"answer_id": 45206,
"author": "titanae",
"author_id": 2387,
"author_profile": "https://Stackoverflow.com/users/2387",
"pm_score": 2,
"selected": false,
"text": "<p>I have seen this a lot, some of our modules link in excess of a 100 libraries of our code plus system & 3rd party libs... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1597/"
] | Why does the order in which libraries are linked sometimes cause errors in GCC? | (See the history on this answer to get the more elaborate text, but I now think it's easier for the reader to see real command lines).
---
Common files shared by all below commands
```
// a depends on b, b depends on d
$ cat a.cpp
extern int a;
int main() {
return a;
}
$ cat b.cpp
extern int b;
int a = b;
$ cat d.cpp
int b;
```
Linking to static libraries
===========================
```
$ g++ -c b.cpp -o b.o
$ ar cr libb.a b.o
$ g++ -c d.cpp -o d.o
$ ar cr libd.a d.o
$ g++ -L. -ld -lb a.cpp # wrong order
$ g++ -L. -lb -ld a.cpp # wrong order
$ g++ a.cpp -L. -ld -lb # wrong order
$ g++ a.cpp -L. -lb -ld # right order
```
The linker searches from left to right, and notes unresolved symbols as it goes. If a library resolves the symbol, it takes the object files of that library to resolve the symbol (b.o out of libb.a in this case).
Dependencies of static libraries against each other work the same - the library that needs symbols must be first, then the library that resolves the symbol.
If a static library depends on another library, but the other library again depends on the former library, there is a cycle. You can resolve this by enclosing the cyclically dependent libraries by `-(` and `-)`, such as `-( -la -lb -)` (you may need to escape the parens, such as `-\(` and `-\)`). The linker then searches those enclosed lib multiple times to ensure cycling dependencies are resolved. Alternatively, you can specify the libraries multiple times, so each is before one another: `-la -lb -la`.
Linking to dynamic libraries
============================
```
$ export LD_LIBRARY_PATH=. # not needed if libs go to /usr/lib etc
$ g++ -fpic -shared d.cpp -o libd.so
$ g++ -fpic -shared b.cpp -L. -ld -o libb.so # specifies its dependency!
$ g++ -L. -lb a.cpp # wrong order (works on some distributions)
$ g++ -Wl,--as-needed -L. -lb a.cpp # wrong order
$ g++ -Wl,--as-needed a.cpp -L. -lb # right order
```
It's the same here - the libraries must follow the object files of the program. The difference here compared with static libraries is that you need not care about the dependencies of the libraries against each other, because *dynamic libraries sort out their dependencies themselves*.
Some recent distributions apparently default to using the `--as-needed` linker flag, which enforces that the program's object files come before the dynamic libraries. If that flag is passed, the linker will not link to libraries that are not actually needed by the executable (and it detects this from left to right). My recent archlinux distribution doesn't use this flag by default, so it didn't give an error for not following the correct order.
It is not correct to omit the dependency of `b.so` against `d.so` when creating the former. You will be required to specify the library when linking `a` then, but `a` doesn't really need the integer `b` itself, so it should not be made to care about `b`'s own dependencies.
Here is an example of the implications if you miss specifying the dependencies for `libb.so`
```
$ export LD_LIBRARY_PATH=. # not needed if libs go to /usr/lib etc
$ g++ -fpic -shared d.cpp -o libd.so
$ g++ -fpic -shared b.cpp -o libb.so # wrong (but links)
$ g++ -L. -lb a.cpp # wrong, as above
$ g++ -Wl,--as-needed -L. -lb a.cpp # wrong, as above
$ g++ a.cpp -L. -lb # wrong, missing libd.so
$ g++ a.cpp -L. -ld -lb # wrong order (works on some distributions)
$ g++ -Wl,--as-needed a.cpp -L. -ld -lb # wrong order (like static libs)
$ g++ -Wl,--as-needed a.cpp -L. -lb -ld # "right"
```
If you now look into what dependencies the binary has, you note the binary itself depends also on `libd`, not just `libb` as it should. The binary will need to be relinked if `libb` later depends on another library, if you do it this way. And if someone else loads `libb` using `dlopen` at runtime (think of loading plugins dynamically), the call will fail as well. So the `"right"` really should be a `wrong` as well. |
45,163 | <p>Given this HTML:</p>
<pre><code><ul id="topnav">
<li id="topnav_galleries"><a href="#">Galleries</a></li>
<li id="topnav_information"><a href="#">Information</a></li>
</ul>
</code></pre>
<p>And this CSS:</p>
<pre class="lang-css prettyprint-override"><code>#topnav_galleries a, #topnav_information a {
background-repeat: no-repeat;
text-indent: -9000px;
padding: 0;
margin: 0 0;
overflow: hidden;
height: 46px;
width: 136px;
display: block;
}
#topnav { list-style-type: none; }
#topnav_galleries a { background-image: url('image1.jpg'); }
#topnav_information a { background-image: url('image2.jpg'); }
</code></pre>
<p>How would I go about turning the <code>topnav</code> list into an inline list?</p>
| [
{
"answer_id": 45429,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 3,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#topnav {\n overflow:hidden;\n}\n#topnav li {\n ... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1306/"
] | Given this HTML:
```
<ul id="topnav">
<li id="topnav_galleries"><a href="#">Galleries</a></li>
<li id="topnav_information"><a href="#">Information</a></li>
</ul>
```
And this CSS:
```css
#topnav_galleries a, #topnav_information a {
background-repeat: no-repeat;
text-indent: -9000px;
padding: 0;
margin: 0 0;
overflow: hidden;
height: 46px;
width: 136px;
display: block;
}
#topnav { list-style-type: none; }
#topnav_galleries a { background-image: url('image1.jpg'); }
#topnav_information a { background-image: url('image2.jpg'); }
```
How would I go about turning the `topnav` list into an inline list? | Try this:
```css
#topnav {
overflow:hidden;
}
#topnav li {
float:left;
}
```
And for IE you will need to add the following:
```css
#topnav {
zoom:1;
}
```
Otherwise your floated < li > tags will spill out of the containing < ul >. |
45,169 | <p>I need to call into a Win32 API to get a series of strings, and I would like to return an array of those strings to JavaScript. This is for script that runs on local machine for administration scripts, not for the web browser.</p>
<p>My IDL file for the COM object has the interface that I am calling into as:</p>
<pre>
HRESULT GetArrayOfStrings([out, retval] SAFEARRAY(BSTR) * rgBstrStringArray);
</pre>
<p>The function returns correctly, but the strings are getting 'lost' when they are being assigned to a variable in JavaScript.</p>
<p>The question is:
What is the proper way to get the array of strings returned to a JavaScript variable?
</p>
| [
{
"answer_id": 45211,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": true,
"text": "<p>If i recall correctly, you'll need to wrap the <code>SAFEARRAY</code> in a <code>VARIANT</code> in order for it to get through,... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1462171/"
] | I need to call into a Win32 API to get a series of strings, and I would like to return an array of those strings to JavaScript. This is for script that runs on local machine for administration scripts, not for the web browser.
My IDL file for the COM object has the interface that I am calling into as:
```
HRESULT GetArrayOfStrings([out, retval] SAFEARRAY(BSTR) * rgBstrStringArray);
```
The function returns correctly, but the strings are getting 'lost' when they are being assigned to a variable in JavaScript.
The question is:
What is the proper way to get the array of strings returned to a JavaScript variable?
| If i recall correctly, you'll need to wrap the `SAFEARRAY` in a `VARIANT` in order for it to get through, and then use a [VBArray object](http://msdn.microsoft.com/en-us/library/y39d47w8(VS.85).aspx) to unpack it on the JS side of things:
```
HRESULT GetArrayOfStrings(/*[out, retval]*/ VARIANT* pvarBstrStringArray)
{
// ...
_variant_t ret;
ret.vt = VT_ARRAY|VT_VARIANT;
ret.parray = rgBstrStringArray;
*pvarBstrStringArray = ret.Detach();
return S_OK;
}
```
then
```
var jsFriendlyStrings = new VBArray( axOb.GetArrayOfStrings() ).toArray();
``` |
45,176 | <p>I have a rather complex page that dynamically builds user controls inside of a repeater. This repeater must be bound during the Init page event before <code>ViewState</code> is initialized or the dynamically created user controls will not retain their state.</p>
<p>This creates an interesting Catch-22 because the object I bind the repeater to needs to be created on initial page load, and then persisted in memory until the user opts to leave or save.</p>
<p>Because I cannot use <code>ViewState</code> to store this object, yet have it available during Init, I have been forced to store it in Session.</p>
<p>This also has issues, because I have to explicitly null the session value during non postbacks in order to emulate how <code>ViewState</code> works.</p>
<p>There has to be a better way to state management in this scenario. Any ideas?</p>
<p><strong>Edit:</strong> Some good suggestions about using <code>LoadViewState</code>, but I'm still having issues with state not being restored when I do that.</p>
<p>Here is somewhat if the page structure</p>
<p>Page --> UserControl --> Repeater --> N amount of UserControls Dynamicly Created.</p>
<p>I put the overridden <code>LoadViewState</code> in the parent <code>UserControl</code>, as it is designed to be completely encapsulated and independent of the page it is on. I am wondering if that is where the problem is.</p>
| [
{
"answer_id": 45181,
"author": "Greg Hurlman",
"author_id": 35,
"author_profile": "https://Stackoverflow.com/users/35",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>This also has issues, because I have to explicitly null the session value during non postbacks in order t... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45176",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | I have a rather complex page that dynamically builds user controls inside of a repeater. This repeater must be bound during the Init page event before `ViewState` is initialized or the dynamically created user controls will not retain their state.
This creates an interesting Catch-22 because the object I bind the repeater to needs to be created on initial page load, and then persisted in memory until the user opts to leave or save.
Because I cannot use `ViewState` to store this object, yet have it available during Init, I have been forced to store it in Session.
This also has issues, because I have to explicitly null the session value during non postbacks in order to emulate how `ViewState` works.
There has to be a better way to state management in this scenario. Any ideas?
**Edit:** Some good suggestions about using `LoadViewState`, but I'm still having issues with state not being restored when I do that.
Here is somewhat if the page structure
Page --> UserControl --> Repeater --> N amount of UserControls Dynamicly Created.
I put the overridden `LoadViewState` in the parent `UserControl`, as it is designed to be completely encapsulated and independent of the page it is on. I am wondering if that is where the problem is. | The LoadViewState method on the page is definitely the answer. Here's the general idea:
```
protected override void LoadViewState( object savedState ) {
var savedStateArray = (object[])savedState;
// Get repeaterData from view state before the normal view state restoration occurs.
repeaterData = savedStateArray[ 0 ];
// Bind your repeater control to repeaterData here.
// Instruct ASP.NET to perform the normal restoration of view state.
// This will restore state to your dynamically created controls.
base.LoadViewState( savedStateArray[ 1 ] );
}
```
SaveViewState needs to create the savedState array that we are using above:
```
protected override object SaveViewState() {
var stateToSave = new List<object> { repeaterData, base.SaveViewState() };
return stateToSave.ToArray();
}
```
Don't forget to also bind the repeater in Init or Load using code like this:
```
if( !IsPostBack ) {
// Bind your repeater here.
}
``` |
45,227 | <p>I have been searching everywhere for the following functionality in Lisp, and have gotten nowhere:</p>
<ol>
<li><p>find the index of something in a list. example:</p>
<pre><code>(index-of item InThisList)
</code></pre></li>
<li><p>replace something at a specific spot in a list. example:</p>
<pre><code>(replace item InThisList AtThisIndex) ;i think this can be done with 'setf'?
</code></pre></li>
<li><p>return an item at a specific index. example:</p>
<pre><code>(return InThisList ItemAtThisIndex)
</code></pre></li>
</ol>
<p>Up until this point, I've been faking it with my own functions. I'm wondering if I'm just creating more work for myself.</p>
<p>This is how I've been faking number 1:</p>
<pre><code>(defun my-index (findMe mylist)
(let ((counter 0) (found 1))
(dolist (item mylist)
(cond
((eq item findMe) ;this works because 'eq' checks place in memory,
;and as long as 'findMe' was from the original list, this will work.
(setq found nil)
(found (incf counter))))
counter))
</code></pre>
| [
{
"answer_id": 45233,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 6,
"selected": true,
"text": "<p>You can use <code>setf</code> and <code>nth</code> to replace and retrieve values by index.</p>\n\n<pre><code>(let ((myList ... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45227",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/50/"
] | I have been searching everywhere for the following functionality in Lisp, and have gotten nowhere:
1. find the index of something in a list. example:
```
(index-of item InThisList)
```
2. replace something at a specific spot in a list. example:
```
(replace item InThisList AtThisIndex) ;i think this can be done with 'setf'?
```
3. return an item at a specific index. example:
```
(return InThisList ItemAtThisIndex)
```
Up until this point, I've been faking it with my own functions. I'm wondering if I'm just creating more work for myself.
This is how I've been faking number 1:
```
(defun my-index (findMe mylist)
(let ((counter 0) (found 1))
(dolist (item mylist)
(cond
((eq item findMe) ;this works because 'eq' checks place in memory,
;and as long as 'findMe' was from the original list, this will work.
(setq found nil)
(found (incf counter))))
counter))
``` | You can use `setf` and `nth` to replace and retrieve values by index.
```
(let ((myList '(1 2 3 4 5 6)))
(setf (nth 4 myList) 101); <----
myList)
(1 2 3 4 101 6)
```
To find by index you can use [the `position` function](http://www.cs.cmu.edu/afs/cs/project/ai-repository/ai/html/cltl/clm/node145.html).
```
(let ((myList '(1 2 3 4 5 6)))
(setf (nth 4 myList) 101)
(list myList (position 101 myList)))
((1 2 3 4 101 6) 4)
```
I found these all [in this index of functions](http://www.cs.cmu.edu/afs/cs/project/ai-repository/ai/html/cltl/clm/index.html). |
45,230 | <p>I have a small local network. Only one of the machines is available to the outside world (this is not easily changeable). I'd like to be able to set it up such that ssh requests that don't come in on the standard port go to another machine. Is this possible? If so, how?</p>
<p>Oh and all of these machines are running either Ubuntu or OS X. </p>
| [
{
"answer_id": 45231,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 0,
"selected": false,
"text": "<p>You can use Port Fowarding to do this. Take a look here:</p>\n\n<p><a href=\"http://portforward.com/help/portforwarding.htm\"... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] | I have a small local network. Only one of the machines is available to the outside world (this is not easily changeable). I'd like to be able to set it up such that ssh requests that don't come in on the standard port go to another machine. Is this possible? If so, how?
Oh and all of these machines are running either Ubuntu or OS X. | Another way to go would be to use ssh tunneling (which happens on the client side).
You'd do an ssh command like this:
```
ssh -L 8022:myinsideserver:22 paul@myoutsideserver
```
That connects you to the machine that's accessible from the outside (myoutsideserver) and creates a tunnel through that ssh connection to port 22 (the standard ssh port) on the server that's only accessible from the inside.
Then you'd do another ssh command like this (leaving the first one still connected):
```
ssh -p 8022 paul@localhost
```
That connection to port 8022 on your localhost will then get tunneled through the first ssh connection taking you over myinsideserver.
There may be something you have to do on myoutsideserver to allow forwarding of the ssh port. I'm double-checking that now.
**Edit**
Hmmm. The ssh manpage says this: \*\*Only the superuser can forward privileged ports. \*\*
That sort of implies to me that the first ssh connection has to be as root. Maybe somebody else can clarify that.
It looks like superuser privileges aren't required as long as the forwarded port ***(in this case, 8022)*** isn't a privileged port (like 22). Thanks for the clarification [Mike Stone](https://stackoverflow.com/questions/45230/is-it-possible-to-forward-ssh-requests-that-come-in-over-a-certain-port-to-anot#45254). |
45,253 | <p>I'm working on a Rails app and am looking to include some functionality from "<a href="https://stackoverflow.com/questions/42566/getting-the-hostname-or-ip-in-ruby-on-rails">Getting the Hostname or IP in Ruby on Rails</a>" that I asked.</p>
<p>I'm having problems getting it to work. I was under the impression that I should just make a file in the lib directory, so I named it 'get_ip.rb', with the contents:</p>
<pre><code>require 'socket'
module GetIP
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
end
</code></pre>
<p>I had also tried defining GetIP as a class but when I do the usual <code>ruby script/console</code>, I'm not able to use the <code>local_ip</code> method at all. Any ideas?</p>
| [
{
"answer_id": 45261,
"author": "Curt Hagenlocher",
"author_id": 533,
"author_profile": "https://Stackoverflow.com/users/533",
"pm_score": 3,
"selected": true,
"text": "<p>You haven't described how you're trying to use the method, so I apologize in advance if this is stuff you already kn... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45253",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
] | I'm working on a Rails app and am looking to include some functionality from "[Getting the Hostname or IP in Ruby on Rails](https://stackoverflow.com/questions/42566/getting-the-hostname-or-ip-in-ruby-on-rails)" that I asked.
I'm having problems getting it to work. I was under the impression that I should just make a file in the lib directory, so I named it 'get\_ip.rb', with the contents:
```
require 'socket'
module GetIP
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
end
```
I had also tried defining GetIP as a class but when I do the usual `ruby script/console`, I'm not able to use the `local_ip` method at all. Any ideas? | You haven't described how you're trying to use the method, so I apologize in advance if this is stuff you already know.
The methods on a module never come into use unless the module is included into a class. Instance methods on a class require there to be an instance of the class. You probably want a class method instead. And the file itself should be loaded, generally through the require statement.
If the following code is in the file getip.rb,
```
require 'socket'
class GetIP
def self.local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true
UDPSocket.open do |s|
s.connect '64.233.187.99', 1
s.addr.last
end
ensure
Socket.do_not_reverse_lookup = orig
end
end
```
Then you should be able to run it by saying,
```
require 'getip'
GetIP.local_ip
``` |
45,267 | <p>When an <code>AutoCompleteExtender</code> is displayed in IE6 it seems to ignore z-index and renders below any select controls (like <strong>dropdownlists</strong>) in IE6.</p>
<pre><code><asp:TextBox ID="TextBox1" runat="server" />
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="TextBox1" EnableCaching="true" CompletionSetCount="5"
FirstRowSelected="true" ServicePath="~/Services/Service1.asmx" ServiceMethod="GetSuggestion" />
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="Item 1" Value="0" />
<asp:ListItem Text="Item 2" Value="1" />
</asp:DropDownList>
</code></pre>
<p>How do I make it render above <strong>dropdownlists</strong>?</p>
| [
{
"answer_id": 45284,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 1,
"selected": false,
"text": "<p>Nothing renders below select controls in IE6. It's one of the many \"features\" microsoft bestowed upon us when they g... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4582/"
] | When an `AutoCompleteExtender` is displayed in IE6 it seems to ignore z-index and renders below any select controls (like **dropdownlists**) in IE6.
```
<asp:TextBox ID="TextBox1" runat="server" />
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
TargetControlID="TextBox1" EnableCaching="true" CompletionSetCount="5"
FirstRowSelected="true" ServicePath="~/Services/Service1.asmx" ServiceMethod="GetSuggestion" />
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Text="Item 1" Value="0" />
<asp:ListItem Text="Item 2" Value="1" />
</asp:DropDownList>
```
How do I make it render above **dropdownlists**? | [**@Orion**](https://stackoverflow.com/questions/45267/how-do-i-make-autocompleteextender-render-above-select-controls-in-ie6#45284) has this *partially* correct - there is *one other way* to deal with these, and that is to cover the offending select lists with an iframe. This technique is used in [**Cody Lindley's ThickBox**](http://jquery.com/demo/thickbox/) (written for jQuery). See the code for details on how to do it. |
45,340 | <p>Python frameworks always provide ways to handle URLs that convey the data of the request in an elegant way, like for example <a href="http://somewhere.overtherainbow.com/userid/123424/" rel="noreferrer">http://somewhere.overtherainbow.com/userid/123424/</a></p>
<p>I want you to notice the ending path <strong>/userid/123424/</strong></p>
<p>How do you do this in ASP.NET?</p>
| [
{
"answer_id": 45347,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 0,
"selected": false,
"text": "<p>Also, check out ASP.NET MVC or if you're set on webforms, the new System.Web.Routing namespace in ASP.NET 3.5 SP1</p>... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45340",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] | Python frameworks always provide ways to handle URLs that convey the data of the request in an elegant way, like for example <http://somewhere.overtherainbow.com/userid/123424/>
I want you to notice the ending path **/userid/123424/**
How do you do this in ASP.NET? | This example uses ASP.NET Routing to implement friendly URLs.
Examples of the mappings that the application handles are:
<http://samplesite/userid/1234> - <http://samplesite/users.aspx?userid=1234>
<http://samplesite/userid/1235> - <http://samplesite/users.aspx?userid=1235>
This example uses querystrings and avoids any requirement to modify the code on the aspx page.
Step 1 - add the necessary entries to web.config
================================================
```
<system.web>
<compilation debug="true">
<assemblies>
…
<add assembly="System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</assemblies>
</compilation>
…
<httpModules>
…
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</httpModules>
</system.web>
<system.webServer>
…
<modules>
…
<add name="UrlRoutingModule" type="System.Web.Routing.UrlRoutingModule, System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
</modules>
<handlers
…
<add name="UrlRoutingHandler" preCondition="integratedMode" verb="*" path="UrlRouting.axd" type="System.Web.HttpForbiddenHandler, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</handlers>
</system.webServer>
```
Step 2 - add a routing table in global.asax
===========================================
Define the mapping from the friendly URL to the aspx page, saving the requested userid for later use.
```
void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.Add("UseridRoute", new Route
(
"userid/{userid}",
new CustomRouteHandler("~/users.aspx")
));
}
```
Step 3 - implement the route handler
====================================
Add the querystring to the current context before the routing takes place.
```
using System.Web.Compilation;
using System.Web.UI;
using System.Web;
using System.Web.Routing;
public class CustomRouteHandler : IRouteHandler
{
public CustomRouteHandler(string virtualPath)
{
this.VirtualPath = virtualPath;
}
public string VirtualPath { get; private set; }
public IHttpHandler GetHttpHandler(RequestContext
requestContext)
{
// Add the querystring to the URL in the current context
string queryString = "?userid=" + requestContext.RouteData.Values["userid"];
HttpContext.Current.RewritePath(
string.Concat(
VirtualPath,
queryString));
var page = BuildManager.CreateInstanceFromVirtualPath
(VirtualPath, typeof(Page)) as IHttpHandler;
return page;
}
}
```
Code from users.aspx
====================
The code on the aspx page for reference.
```
protected void Page_Load(object sender, EventArgs e)
{
string id = Page.Request.QueryString["userid"];
switch (id)
{
case "1234":
lblUserId.Text = id;
lblUserName.Text = "Bill";
break;
case "1235":
lblUserId.Text = id;
lblUserName.Text = "Claire";
break;
case "1236":
lblUserId.Text = id;
lblUserName.Text = "David";
break;
default:
lblUserId.Text = "0000";
lblUserName.Text = "Unknown";
break;
}
``` |
45,372 | <p>Let's say that I want to have a table that logs the date and the number of columns in some other table (or really any sort of math / string concat etc).</p>
<pre><code>CREATE TABLE `log` (
`id` INTEGER NOT NULL AUTO_INCREMENT ,
`date` DATETIME NOT NULL ,
`count` INTEGER NOT NULL ,
PRIMARY KEY (`id`)
);
</code></pre>
<p>Is it possible to have the count column calculated for me whenever I do an insert?</p>
<p>e.g. do something like:</p>
<pre><code>INSERT INTO log (date='foo');
</code></pre>
<p>and have count calculated by mysql.</p>
<p>Obviously I could do it myself by doing a query to get the count and inserting it, but this would be better.</p>
| [
{
"answer_id": 45382,
"author": "Thomas Watnedal",
"author_id": 4059,
"author_profile": "https://Stackoverflow.com/users/4059",
"pm_score": 0,
"selected": false,
"text": "<p>You definitly have to declare what to insert. This should be possible by using the <a href=\"http://dev.mysql.com/... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45372",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1666/"
] | Let's say that I want to have a table that logs the date and the number of columns in some other table (or really any sort of math / string concat etc).
```
CREATE TABLE `log` (
`id` INTEGER NOT NULL AUTO_INCREMENT ,
`date` DATETIME NOT NULL ,
`count` INTEGER NOT NULL ,
PRIMARY KEY (`id`)
);
```
Is it possible to have the count column calculated for me whenever I do an insert?
e.g. do something like:
```
INSERT INTO log (date='foo');
```
and have count calculated by mysql.
Obviously I could do it myself by doing a query to get the count and inserting it, but this would be better. | Triggers are the best tool for annotating data when a table is changed by insert, update or delete.
To automatically set the date column of a new row in the log with the current date, you'd create a trigger that looked something like this:
```
create trigger log_date before insert on log
for each row begin
set new.date = current_date()
end;
``` |
45,414 | <p>I'm using Eclipse 3.4 and have configured the Java code formatter with all of the options on the <em>Comments</em> tab enabled. The problem is that when I format a document comment that contains:</p>
<pre><code>* @see <a href="test.html">test</a>
</code></pre>
<p>the code formatter inserts a space in the closing HTML, breaking it:</p>
<pre><code>* @see <a href="test.html">test< /a>
</code></pre>
<p>Why? How do I stop this happening?</p>
<p>This is not fixed by disabling any of the options on the <em>Comments</em> tab, such as <em>Format HTML tags</em>. The only work-around I found is to disable Javadoc formatting completely by disabling both the <em>Enable Javadoc comment formatting</em> and <em>Enable block comment formatting</em> options, which means I then have to format comment blocks manually.</p>
| [
{
"answer_id": 45550,
"author": "Bart Schuller",
"author_id": 4711,
"author_profile": "https://Stackoverflow.com/users/4711",
"pm_score": 3,
"selected": true,
"text": "<p>I can only assume it's a bug in Eclipse. It only happens with <em>@see</em> tags, it happens also for all 3 builtin c... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45414",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2670/"
] | I'm using Eclipse 3.4 and have configured the Java code formatter with all of the options on the *Comments* tab enabled. The problem is that when I format a document comment that contains:
```
* @see <a href="test.html">test</a>
```
the code formatter inserts a space in the closing HTML, breaking it:
```
* @see <a href="test.html">test< /a>
```
Why? How do I stop this happening?
This is not fixed by disabling any of the options on the *Comments* tab, such as *Format HTML tags*. The only work-around I found is to disable Javadoc formatting completely by disabling both the *Enable Javadoc comment formatting* and *Enable block comment formatting* options, which means I then have to format comment blocks manually. | I can only assume it's a bug in Eclipse. It only happens with *@see* tags, it happens also for all 3 builtin code formatter settings.
There are some interesting bugs reported already in the neighbourhood, but I couldn't find this specific one. See for example a search for *@see* in the [Eclipse Bugzilla](https://bugs.eclipse.org/bugs/buglist.cgi?query_format=specific&order=relevance+desc&bug_status=__all__&product=JDT&content=%40see). |
45,424 | <p>I'm using <b>Struts 2</b>.</p>
<p>I'd like to return from an Action to the page which invoked it.</p>
<p>Say I'm in page <strong>x.jsp</strong>, I invoke Visual action to change CSS preferences in the session; I want to return to <strong>x.jsp</strong> rather than to a fixed page (i.e. <strong>home.jsp</strong>)<br/></p>
<p>Here's the relevant <strong>struts.xml</strong> fragment:
<br/></p>
<pre>
<action
name="Visual"
class="it.___.web.actions.VisualizationAction">
<result name="home">/pages/home.jsp</result>
</action>
</pre>
<p>Of course my <code>VisualizationAction.execute()</code> returns <strong>home</strong>.</p>
<p>Is there any "magic" constant (like, say, INPUT_PAGE) that I may return to do the trick?<br/></p>
<p>Must I use a more involved method (i.e. extracting the request page and forwarding to it)?<br/></p>
<p>T.I.A.</p>
| [
{
"answer_id": 45595,
"author": "nikhilbelsare",
"author_id": 4705,
"author_profile": "https://Stackoverflow.com/users/4705",
"pm_score": 1,
"selected": false,
"text": "<pre><code>return INPUT;\n</code></pre>\n\n<p>will do the trick. INPUT constant is defined in Action interface itself. ... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4690/"
] | I'm using **Struts 2**.
I'd like to return from an Action to the page which invoked it.
Say I'm in page **x.jsp**, I invoke Visual action to change CSS preferences in the session; I want to return to **x.jsp** rather than to a fixed page (i.e. **home.jsp**)
Here's the relevant **struts.xml** fragment:
```
<action
name="Visual"
class="it.___.web.actions.VisualizationAction">
<result name="home">/pages/home.jsp</result>
</action>
```
Of course my `VisualizationAction.execute()` returns **home**.
Is there any "magic" constant (like, say, INPUT\_PAGE) that I may return to do the trick?
Must I use a more involved method (i.e. extracting the request page and forwarding to it)?
T.I.A. | You can use a dynamic result in struts.xml. For instance:
```
<action
name="Visual"
class="it.___.web.actions.VisualizationAction">
<result name="next">${next}</result>
</action>
```
Then in your action, you create a field called next. So to invoke the action you will pass the name of the page that you want to forward to next. The action then returns "next" and struts will know which page to go to.
There is a nicer explanation on this post: [Stack Overflow](https://stackoverflow.com/questions/173846/struts2-how-to-do-dynamic-url-redirects) |
45,437 | <p>I wondered whether anybody knows how to obtain membership of local groups on a remote server programmatically via C#. Would this require administrator permissions? And if so is there any way to confirm the currently logged in user's membership (or not) of these groups?</p>
| [
{
"answer_id": 45439,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps this is something that can be done via WMI?</p>\n"
},
{
"answer_id": 45458,
"author": "Espo",
... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45437",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3394/"
] | I wondered whether anybody knows how to obtain membership of local groups on a remote server programmatically via C#. Would this require administrator permissions? And if so is there any way to confirm the currently logged in user's membership (or not) of these groups? | [Howto: (Almost) Everything In Active Directory via C#](http://www.codeproject.com/KB/system/everythingInAD.aspx) is very helpfull and also includes instructions on how to iterate AD members in a group.
```
public ArrayList Groups(string userDn, bool recursive)
{
ArrayList groupMemberships = new ArrayList();
return AttributeValuesMultiString("memberOf", userDn,
groupMemberships, recursive);
}
```
You will also need this function:
```
public ArrayList AttributeValuesMultiString(string attributeName,
string objectDn, ArrayList valuesCollection, bool recursive)
{
DirectoryEntry ent = new DirectoryEntry(objectDn);
PropertyValueCollection ValueCollection = ent.Properties[attributeName];
IEnumerator en = ValueCollection.GetEnumerator();
while (en.MoveNext())
{
if (en.Current != null)
{
if (!valuesCollection.Contains(en.Current.ToString()))
{
valuesCollection.Add(en.Current.ToString());
if (recursive)
{
AttributeValuesMultiString(attributeName, "LDAP://" +
en.Current.ToString(), valuesCollection, true);
}
}
}
}
ent.Close();
ent.Dispose();
return valuesCollection;
}
```
If you do now want to use this AD-method, you could use the info in this article, but it uses unmanaged code:
<http://www.codeproject.com/KB/cs/groupandmembers.aspx>
The sample application that they made:
 |
45,453 | <p>I'm generating ICalendar (.ics) files.</p>
<p>Using the UID and SEQUENCE fields I can update existing events in Google Calendar and in Windows Calendar <strong><em>BUT NOT</em></strong> in MS Outlook 2007 - it just creates a second event</p>
<p>How do I get them to work for Outlook ?</p>
<p>Thanks</p>
<p>Tom</p>
| [
{
"answer_id": 45703,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 0,
"selected": false,
"text": "<p>I'm using Entourage, so this may not match up exactly with the behavior you're seeing, but I hope it helps.</p>\n\n<p>Usi... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45453",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2839/"
] | I'm generating ICalendar (.ics) files.
Using the UID and SEQUENCE fields I can update existing events in Google Calendar and in Windows Calendar ***BUT NOT*** in MS Outlook 2007 - it just creates a second event
How do I get them to work for Outlook ?
Thanks
Tom | I've continued to do some testing and have now managed to get Outlook to update and cancel events based on the .cs file.
Outlook in fact seems to respond to the rules defined in [RFC 2446](https://www.rfc-editor.org/rfc/rfc2446#page-19)
In summary you have to specify
`METHOD:REQUEST` and `ORGANIZER:xxxxxxxx`
in addition to `UID`: and `SEQUENCE:`
For a cancellation you have to specify `METHOD:CANCEL`
Request/Update Example
```
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//SYFADIS//PORTAIL FORMATION//FR
METHOD:REQUEST
BEGIN:VEVENT
UID:TS_229377_MS_262145@syfadis.com
SEQUENCE:5
DTSTAMP:20081106T154911Z
ORGANIZER:catalog@syfadis.com
DTSTART:20081113T164907
DTEND:20081115T170000
SUMMARY:TestTraining
STATUS:CONFIRMED
END:VEVENT
END:VCALENDAR
```
Cancel Example;
```
BEGIN:VCALENDAR
VERSION:2.0
PRODID:-//SYFADIS//PORTAIL FORMATION//FR
METHOD:CANCEL
BEGIN:VEVENT
UID:TS_229377_MS_262145@syfadis.com
SEQUENCE:7
DTSTAMP:20081106T154916Z
ORGANIZER:catalog@syfadis.com
DTSTART:20081113T164907
SUMMARY:TestTraining
STATUS:CANCELLED
END:VEVENT
END:VCALENDAR
``` |
45,475 | <p>I'm presenting information from a DataTable on my page and would like to add some sorting functionality which goes a bit beyond a straight forward column sort. As such I have been trying to place LinkButtons in the HeaderItems of my GridView which post-back to functions that change session information before reloading the page.</p>
<p>Clicking my links <em>DOES</em> cause a post-back but they don't seem to generate any <em>OnClick</em> events as my <em>OnClick</em> functions don't get executed. I have <code>AutoEventWireup</code> set to true and if I move the links out of the GridView they work fine.</p>
<p>I've got around the problem by creating regular anchors, appending queries to their <strong>hrefs</strong> and checking for them at page load but I'd prefer C# to be doing the grunt work. Any ideas?</p>
<p><strong>Update:</strong> To clarify the IDs of the controls match their <em>OnClick</em> function names.</p>
| [
{
"answer_id": 45477,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 0,
"selected": false,
"text": "<p>Two things to keep in mind when using events on dynamically generated controls in ASP.Net:</p>\n\n<ul>\n<li>Firstly, the... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45475",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4431/"
] | I'm presenting information from a DataTable on my page and would like to add some sorting functionality which goes a bit beyond a straight forward column sort. As such I have been trying to place LinkButtons in the HeaderItems of my GridView which post-back to functions that change session information before reloading the page.
Clicking my links *DOES* cause a post-back but they don't seem to generate any *OnClick* events as my *OnClick* functions don't get executed. I have `AutoEventWireup` set to true and if I move the links out of the GridView they work fine.
I've got around the problem by creating regular anchors, appending queries to their **hrefs** and checking for them at page load but I'd prefer C# to be doing the grunt work. Any ideas?
**Update:** To clarify the IDs of the controls match their *OnClick* function names. | You're on the right track but try working with the Command Name/Argument of the LinkButton. Try something like this:
In the HeaderTemplate of the the TemplateField, add a LinkButton and set the CommandName and CommandArgument
```
<HeaderTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="sort" CommandArgument="Products" Text="<%# Bind('ProductName")' />
</HeaderTemplate>
```
Next, set the RowCommand event of the GridView
```
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "sort")
{
//Now sort by e.CommandArgument
}
}
```
This way, you have a lot of control of your LinkButtons and you don't need to do much work to keep track of them. |
45,481 | <p>How can you do a streaming read on a large XML file that contains a xs:sequence just below root element, without loading the whole file into a XDocument instance in memory?</p>
| [
{
"answer_id": 45484,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>I think it's not possible if you want to use object model (i.e. XElement\\XDocument) to query XML. Obviously, you can't build ... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45481",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4685/"
] | How can you do a streaming read on a large XML file that contains a xs:sequence just below root element, without loading the whole file into a XDocument instance in memory? | Going with a SAX-style element parser and the [XmlTextReader](http://msdn.microsoft.com/en-us/library/system.xml.xmltextreader.aspx) class created with [XmlReader.Create](http://msdn.microsoft.com/en-us/library/system.xml.xmlreader.create.aspx) would be a good idea, yes. Here's a slightly-modified code example from [CodeGuru](http://www.codeguru.com/csharp/csharp/cs_data/xml/article.php/c4221/):
```
void ParseURL(string strUrl)
{
try
{
using (var reader = XmlReader.Create(strUrl))
{
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
var attributes = new Hashtable();
var strURI = reader.NamespaceURI;
var strName = reader.Name;
if (reader.HasAttributes)
{
for (int i = 0; i < reader.AttributeCount; i++)
{
reader.MoveToAttribute(i);
attributes.Add(reader.Name,reader.Value);
}
}
StartElement(strURI,strName,strName,attributes);
break;
//
//you can handle other cases here
//
//case XmlNodeType.EndElement:
// Todo
//case XmlNodeType.Text:
// Todo
default:
break;
}
}
}
catch (XmlException e)
{
Console.WriteLine("error occured: " + e.Message);
}
}
}
}
``` |
45,485 | <p>Are there conventions for function names when using the Perl Test::More or Test::Simple modules?</p>
<p>I'm specifically asking about the names of functions that are used to set up a test environment before the test and to tear down the environment after successful completion of the test(s).</p>
<p>cheers,</p>
<p>Rob</p>
| [
{
"answer_id": 45491,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 1,
"selected": false,
"text": "<p>I do not think there is a official set of conventions, so I would recommend looking at the examples at <a href=\"http://perld... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2974/"
] | Are there conventions for function names when using the Perl Test::More or Test::Simple modules?
I'm specifically asking about the names of functions that are used to set up a test environment before the test and to tear down the environment after successful completion of the test(s).
cheers,
Rob | I dont think there are any such conventions out there.
The only way you can do it is perhaps use BEGIN/END blocks, if the resources are to be used over the whole file.
The general approach I take is to put related tests in one code block and then initialize the variables/resource etc there. You can perhaps keep an easy count of how many tests you have for each function.
Something like ...
```
BEGIN {
# If you want to set some global db setting/file setting/INC changes etc
}
# Tests functionality 1...
{
# have fun ....
}
# Tests functionality 2...
{
# have more fun ....
}
END {
# Clean up the BEGIN changes
}
```
On other note, you may want to read this for testing in perl ... <http://perlandmac.blogspot.com/2007/08/using-perl-testsimple-and-testmore.html> |
45,494 | <p>I have a table <code>story_category</code> in my database with corrupt entries. The next query returns the corrupt entries:</p>
<pre><code>SELECT *
FROM story_category
WHERE category_id NOT IN (
SELECT DISTINCT category.id
FROM category INNER JOIN
story_category ON category_id=category.id);
</code></pre>
<p>I tried to delete them executing:</p>
<pre><code>DELETE FROM story_category
WHERE category_id NOT IN (
SELECT DISTINCT category.id
FROM category
INNER JOIN story_category ON category_id=category.id);
</code></pre>
<p>But I get the next error: </p>
<blockquote>
<p>#1093 - You can't specify target table 'story_category' for update in FROM clause </p>
</blockquote>
<p>How can I overcome this?</p>
| [
{
"answer_id": 45498,
"author": "Cheekysoft",
"author_id": 1820,
"author_profile": "https://Stackoverflow.com/users/1820",
"pm_score": 11,
"selected": true,
"text": "<p><em>Update: This answer covers the general error classification. For a more specific answer about how to best handle th... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] | I have a table `story_category` in my database with corrupt entries. The next query returns the corrupt entries:
```
SELECT *
FROM story_category
WHERE category_id NOT IN (
SELECT DISTINCT category.id
FROM category INNER JOIN
story_category ON category_id=category.id);
```
I tried to delete them executing:
```
DELETE FROM story_category
WHERE category_id NOT IN (
SELECT DISTINCT category.id
FROM category
INNER JOIN story_category ON category_id=category.id);
```
But I get the next error:
>
> #1093 - You can't specify target table 'story\_category' for update in FROM clause
>
>
>
How can I overcome this? | *Update: This answer covers the general error classification. For a more specific answer about how to best handle the OP's exact query, please see other answers to this question*
In MySQL, you can't modify the same table which you use in the SELECT part.
This behaviour is documented at:
<http://dev.mysql.com/doc/refman/5.6/en/update.html>
**Maybe you can just join the table to itself**
If the logic is simple enough to re-shape the query, lose the subquery and join the table to itself, employing appropriate selection criteria. This will cause MySQL to see the table as two different things, allowing destructive changes to go ahead.
```
UPDATE tbl AS a
INNER JOIN tbl AS b ON ....
SET a.col = b.col
```
**Alternatively, try nesting the subquery deeper into a from clause ...**
If you absolutely need the subquery, there's a workaround, but it's
ugly for several reasons, including performance:
```
UPDATE tbl SET col = (
SELECT ... FROM (SELECT.... FROM) AS x);
```
The nested subquery in the FROM clause creates an *implicit temporary
table*, so it doesn't count as the same table you're updating.
**... but watch out for the query optimiser**
However, beware that from [MySQL 5.7.6](http://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-6.html) and onward, the optimiser may optimise out the subquery, and still give you the error. Luckily, the `optimizer_switch` variable can be used to switch off this behaviour; although I couldn't recommend doing this as anything more than a short term fix, or for small one-off tasks.
```
SET optimizer_switch = 'derived_merge=off';
```
*Thanks to [Peter V. Mørch](https://stackoverflow.com/users/345716/peter-v-m%C3%B8rch) for this advice in the comments.*
Example technique was from Baron Schwartz, [originally published at Nabble](http://grokbase.com/t/mysql/mysql/08259dm24b/error-you-cant-specify-target-table-for-update-in-from-clause), paraphrased and extended here. |
45,535 | <p>I need the month+year from the datetime in SQL Server like 'Jan 2008'. I'm grouping the query by month, year. I've searched and found functions like datepart, convert, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this?</p>
| [
{
"answer_id": 45543,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 3,
"selected": false,
"text": "<p>That format doesn't exist. You need to do a combination of two things,</p>\n\n<pre><code>select convert(varchar(4),getdate... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45535",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1688440/"
] | I need the month+year from the datetime in SQL Server like 'Jan 2008'. I'm grouping the query by month, year. I've searched and found functions like datepart, convert, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this? | If you mean you want them back as a string, in that format;
```
SELECT
CONVERT(CHAR(4), date_of_birth, 100) + CONVERT(CHAR(4), date_of_birth, 120)
FROM customers
```
[Here are the other format options](http://msdn.microsoft.com/en-us/library/ms187928.aspx) |
45,540 | <p>I’ve writen a little python script that just pops up a message box containing the text passed on the command line. I want to pop it up only when the window —resulting from a previous call— is not open.</p>
<pre><code>from Tkinter import *
import tkMessageBox
root = Tk()
root.withdraw()
# TODO not if a window with this title exists
tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:]))
</code></pre>
<p>Any idea how to check that?</p>
| [
{
"answer_id": 46205,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I believe you want:</p>\n\n<pre><code>if 'normal' != root.state():\n tkMessageBox.showinfo(\"Key you!\", \" \".join(sys.a... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4717/"
] | I’ve writen a little python script that just pops up a message box containing the text passed on the command line. I want to pop it up only when the window —resulting from a previous call— is not open.
```
from Tkinter import *
import tkMessageBox
root = Tk()
root.withdraw()
# TODO not if a window with this title exists
tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:]))
```
Any idea how to check that? | I believe you want:
```
if 'normal' != root.state():
tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:]))
``` |
45,545 | <p>How can I add horizontal scroll capabilities to the asp.net listbox control?</p>
| [
{
"answer_id": 45549,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 1,
"selected": false,
"text": "<p>If you really, really need it, one idea would be to create a custom\nListBox class whose HTML looks like this: sets the width... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360/"
] | How can I add horizontal scroll capabilities to the asp.net listbox control? | Example to add horizontal scroll:
```
<asp:ListBox ID="List" runat="server" Height="320px" Width="100%" style="overflow-x:auto;"SelectionMode="Multiple">
</asp:ListBox>
```
CSS3 overflow-x Property: <http://www.w3schools.com/cssref/css3_pr_overflow-x.asp> |
45,546 | <p>I want my controller to return the right HTTP response code when the user lacks permission to view a particular page.</p>
| [
{
"answer_id": 45568,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 3,
"selected": false,
"text": "<p>Use this:\n<code>response.setStatus(403)</code>.</p>\n"
},
{
"answer_id": 45585,
"author": "Cheekysoft",
... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4702/"
] | I want my controller to return the right HTTP response code when the user lacks permission to view a particular page. | **Quickie**
If you are using plain JSP views (as is most common), then simply add
```
<% response.setStatus( 403 ); %>
```
somewhere in your view file. At the top is a nice place.
**Detail**
In MVC, i would always set this in the view, and in most cases with Spring-MVC, use the `SimpleMappingExceptionResolver` to present the correct view in response to a thrown runtime Exception.
For example: create and throw a `PermissionDeniedException` in your controller or service layer and have the exception resolver point to a view file `permissionDenied.jsp`. This view file sets the 403 status and shows the user an appropriate message.
In your Spring bean XML file:
```
<bean id="exceptionResolver"
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="PermissionDeniedException">
rescues/permissionDenied
</prop>
... set other exception/view mappings as <prop>s here ...
</props>
</property>
<property name="defaultErrorView" value="rescues/general" />
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
```
If you need to implement a user login mechanism, take a look at [Spring Security](http://static.springframework.org/spring-security/site/index.html) (formerly Acegi Security). |
45,572 | <p>I'm just wondering if it exists better solution for this.</p>
<pre><code>BitConverter.ToInt32(sample_guid.ToByteArray(), 0)
</code></pre>
| [
{
"answer_id": 45581,
"author": "Ishmaeel",
"author_id": 227,
"author_profile": "https://Stackoverflow.com/users/227",
"pm_score": 0,
"selected": false,
"text": "<p>Dunno about a better solution, but I hope you don't intend to use that Int32 as a random (or unique) value. </p>\n\n<p>You ... | 2008/09/05 | [
"https://Stackoverflow.com/questions/45572",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3182/"
] | I'm just wondering if it exists better solution for this.
```
BitConverter.ToInt32(sample_guid.ToByteArray(), 0)
``` | I don't think there's a better solution than this. |