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 |
|---|---|---|---|---|---|---|
49,267 | <p>Embedded custom-tag in dynamic content (nested tag) not rendering.</p>
<p>I have a page that pulls dynamic content from a javabean and passes the list of objects to a custom tag for processing into html. Within each object is a bunch of html to be output that contains a second custom tag that I would like to also be rendered. The problem is that the tag invocation is rendered as plaintext.</p>
<p>An example might serve me better.</p>
<p>1 Pull information from a database and return it to the page via a javabean. Send this info to a custom tag for outputting.</p>
<pre><code><jsp:useBean id="ImportantNoticeBean" scope="page" class="com.mysite.beans.ImportantNoticeProcessBean"/> <%-- Declare the bean --%>
<c:forEach var="noticeBean" items="${ImportantNoticeBean.importantNotices}"> <%-- Get the info --%>
<mysite:notice importantNotice="${noticeBean}"/> <%-- give it to the tag for processing --%>
</c:forEach>
</code></pre>
<p>this tag should output a box div like so</p>
<pre><code>*SNIP* class for custom tag def and method setup etc
out.println("<div class=\"importantNotice\">");
out.println(" " + importantNotice.getMessage());
out.println(" <div class=\"importantnoticedates\">Posted: " + importantNotice.getDateFrom() + " End: " + importantNotice.getDateTo()</div>");
out.println(" <div class=\"noticeAuthor\">- " + importantNotice.getAuthor() + "</div>");
out.println("</div>");
*SNIP*
</code></pre>
<p>This renders fine and as expected</p>
<pre><code><div class="importantNotice">
<p>This is a very important message. Everyone should pay attenton to it.</p>
<div class="importantnoticedates">Posted: 2008-09-08 End: 2008-09-08</div>
<div class="noticeAuthor">- The author</div>
</div>
</code></pre>
<p>2 If, in the above example, for instance, I were to have a custom tag in the importantNotice.getMessage() String:</p>
<pre><code>*SNIP* "This is a very important message. Everyone should pay attenton to it. <mysite:quote author="Some Guy">Quote this</mysite:quote>" *SNIP*
</code></pre>
<p>The important notice renders fine but the quote tag will not be processed and simply inserted into the string and put as plain text/html tag.</p>
<pre><code><div class="importantNotice">
<p>This is a very important message. Everyone should pay attenton to it. <mysite:quote author="Some Guy">Quote this</mysite:quote></p>
<div class="importantnoticedates">Posted: 2008-09-08 End: 2008-09-08</div>
<div class="noticeAuthor">- The author</div>
</div>
</code></pre>
<p>Rather than </p>
<pre><code><div class="importantNotice">
<p>This is a very important message. Everyone should pay attenton to it. <div class="quote">Quote this <span class="authorofquote">Some Guy</span></div></p> // or wahtever I choose as the output
<div class="importantnoticedates">Posted: 2008-09-08 End: 2008-09-08</div>
<div class="noticeAuthor">- The author</div>
</div>
</code></pre>
<p>I know this has to do with processors and pre-processors but I am not to sure about how to make this work.</p>
| [
{
"answer_id": 49410,
"author": "Georgy Bolyuba",
"author_id": 4052,
"author_profile": "https://Stackoverflow.com/users/4052",
"pm_score": 2,
"selected": true,
"text": "<p>Just using </p>\n\n<pre><code><bodycontent>JSP</bodycontent>\n</code></pre>\n\n<p>is not enough. You sho... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3431280/"
] | Embedded custom-tag in dynamic content (nested tag) not rendering.
I have a page that pulls dynamic content from a javabean and passes the list of objects to a custom tag for processing into html. Within each object is a bunch of html to be output that contains a second custom tag that I would like to also be rendered. The problem is that the tag invocation is rendered as plaintext.
An example might serve me better.
1 Pull information from a database and return it to the page via a javabean. Send this info to a custom tag for outputting.
```
<jsp:useBean id="ImportantNoticeBean" scope="page" class="com.mysite.beans.ImportantNoticeProcessBean"/> <%-- Declare the bean --%>
<c:forEach var="noticeBean" items="${ImportantNoticeBean.importantNotices}"> <%-- Get the info --%>
<mysite:notice importantNotice="${noticeBean}"/> <%-- give it to the tag for processing --%>
</c:forEach>
```
this tag should output a box div like so
```
*SNIP* class for custom tag def and method setup etc
out.println("<div class=\"importantNotice\">");
out.println(" " + importantNotice.getMessage());
out.println(" <div class=\"importantnoticedates\">Posted: " + importantNotice.getDateFrom() + " End: " + importantNotice.getDateTo()</div>");
out.println(" <div class=\"noticeAuthor\">- " + importantNotice.getAuthor() + "</div>");
out.println("</div>");
*SNIP*
```
This renders fine and as expected
```
<div class="importantNotice">
<p>This is a very important message. Everyone should pay attenton to it.</p>
<div class="importantnoticedates">Posted: 2008-09-08 End: 2008-09-08</div>
<div class="noticeAuthor">- The author</div>
</div>
```
2 If, in the above example, for instance, I were to have a custom tag in the importantNotice.getMessage() String:
```
*SNIP* "This is a very important message. Everyone should pay attenton to it. <mysite:quote author="Some Guy">Quote this</mysite:quote>" *SNIP*
```
The important notice renders fine but the quote tag will not be processed and simply inserted into the string and put as plain text/html tag.
```
<div class="importantNotice">
<p>This is a very important message. Everyone should pay attenton to it. <mysite:quote author="Some Guy">Quote this</mysite:quote></p>
<div class="importantnoticedates">Posted: 2008-09-08 End: 2008-09-08</div>
<div class="noticeAuthor">- The author</div>
</div>
```
Rather than
```
<div class="importantNotice">
<p>This is a very important message. Everyone should pay attenton to it. <div class="quote">Quote this <span class="authorofquote">Some Guy</span></div></p> // or wahtever I choose as the output
<div class="importantnoticedates">Posted: 2008-09-08 End: 2008-09-08</div>
<div class="noticeAuthor">- The author</div>
</div>
```
I know this has to do with processors and pre-processors but I am not to sure about how to make this work. | Just using
```
<bodycontent>JSP</bodycontent>
```
is not enough. You should do soimething like
```
JspFragment body = getJspBody();
StringWriter stringWriter = new StringWriter();
StringBuffer buff = stringWriter.getBuffer();
buff.append("<h1>");
body.invoke(stringWriter);
buff.append("</h1>");
out.println(stringWriter);
```
to get inner tags rendered (example is for SimpleTag doTag method).
However, in the question's code I see that inner tag is comming from a string which is not rendered as a part of JSP, but just some random string. I do not think you can force JSP translator to parse it.
You can use regexp in your case or try to redesign your code in a way to have a jsp like this:
```
<jsp:useBean id="ImportantNoticeBean" scope="page class="com.mysite.beans.ImportantNoticeProcessBean"/>
<c:forEach var="noticeBean" items="${ImportantNoticeBean.importantNotices}">
<mysite:notice importantNotice="${noticeBean}">
<mysite:quote author="Some Guy">Quote this</mysite:quote>
<mysite:messagebody author="Some Guy" />
</mysite:notice>
</c:forEach>
```
I whould go with regexp. |
49,269 | <p>I have a number of application settings (in user scope) for my custom grid control. Most of them are color settings. I have a form where the user can customize these colors and I want to add a button for reverting to default color settings. How can I read the default settings?</p>
<p>For example:</p>
<ol>
<li>I have a user setting named <code>CellBackgroundColor</code> in <code>Properties.Settings</code>.</li>
<li>At design time I set the value of <code>CellBackgroundColor</code> to <code>Color.White</code> using the IDE.</li>
<li>User sets <code>CellBackgroundColor</code> to <code>Color.Black</code> in my program.</li>
<li>I save the settings with <code>Properties.Settings.Default.Save()</code>.</li>
<li>User clicks on the <code>Restore Default Colors</code> button.</li>
</ol>
<p>Now, <code>Properties.Settings.Default.CellBackgroundColor</code> returns <code>Color.Black</code>. How do I go back to <code>Color.White</code>?</p>
| [
{
"answer_id": 49288,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>How do I go back to Color.White?</p>\n</blockquote>\n\n<p>Two ways you can do:</p>\n\n<ul>\n<li>Save a copy of t... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49269",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/976/"
] | I have a number of application settings (in user scope) for my custom grid control. Most of them are color settings. I have a form where the user can customize these colors and I want to add a button for reverting to default color settings. How can I read the default settings?
For example:
1. I have a user setting named `CellBackgroundColor` in `Properties.Settings`.
2. At design time I set the value of `CellBackgroundColor` to `Color.White` using the IDE.
3. User sets `CellBackgroundColor` to `Color.Black` in my program.
4. I save the settings with `Properties.Settings.Default.Save()`.
5. User clicks on the `Restore Default Colors` button.
Now, `Properties.Settings.Default.CellBackgroundColor` returns `Color.Black`. How do I go back to `Color.White`? | @ozgur,
```
Settings.Default.Properties["property"].DefaultValue // initial value from config file
```
Example:
```
string foo = Settings.Default.Foo; // Foo = "Foo" by default
Settings.Default.Foo = "Boo";
Settings.Default.Save();
string modifiedValue = Settings.Default.Foo; // modifiedValue = "Boo"
string originalValue = Settings.Default.Properties["Foo"].DefaultValue as string; // originalValue = "Foo"
``` |
49,274 | <p>I have a string, say <code>'123'</code>, and I want to convert it to the integer <code>123</code>.</p>
<p>I know you can simply do <code>some_string.to_i</code>, but that converts <code>'lolipops'</code> to <code>0</code>, which is not the effect I have in mind. I want it to blow up in my face when I try to convert something invalid, with a nice and painful <code>Exception</code>. Otherwise, I can't distinguish between a valid <code>0</code> and something that just isn't a number at all.</p>
<p><strong>EDIT:</strong> I was looking for the standard way of doing it, without regex trickery.</p>
| [
{
"answer_id": 49282,
"author": "Slartibartfast",
"author_id": 4433,
"author_profile": "https://Stackoverflow.com/users/4433",
"pm_score": 9,
"selected": true,
"text": "<p>Ruby has this functionality built in:</p>\n\n<pre><code>Integer('1001') # => 1... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2018/"
] | I have a string, say `'123'`, and I want to convert it to the integer `123`.
I know you can simply do `some_string.to_i`, but that converts `'lolipops'` to `0`, which is not the effect I have in mind. I want it to blow up in my face when I try to convert something invalid, with a nice and painful `Exception`. Otherwise, I can't distinguish between a valid `0` and something that just isn't a number at all.
**EDIT:** I was looking for the standard way of doing it, without regex trickery. | Ruby has this functionality built in:
```
Integer('1001') # => 1001
Integer('1001 nights')
# ArgumentError: invalid value for Integer: "1001 nights"
```
As noted in answer by [Joseph Pecoraro](https://stackoverflow.com/questions/49274/safe-integer-parsing-in-ruby/53359#53359), you might want to watch for strings that are valid non-decimal numbers, such as those starting with `0x` for hex and `0b` for binary, and potentially more tricky numbers starting with zero that will be parsed as octal.
Ruby 1.9.2 added optional second argument for radix so above issue can be avoided:
```
Integer('23') # => 23
Integer('0x23') # => 35
Integer('023') # => 19
Integer('0x23', 10)
# => #<ArgumentError: invalid value for Integer: "0x23">
Integer('023', 10) # => 23
``` |
49,284 | <p>I've come across a rather interesing (and frustrating) problem with IE6. We are serving up some server generated pdfs and then simply setting headers in PHP to force a browser download of the file. Works fine and all, except in IE6 but <strong>only</strong> if the windows user account is set to standard user (ie. not administrator).</p>
<p>Since this is for a corporate environment, of course all their accounts are setup this way. Weird thing is, that in the download dialog, the Content-Type is not recognized:</p>
<pre><code>header( 'Pragma: public' );
header( 'Expires: 0' );
header( 'Cache-Control: must-revalidate, pre-check=0, post-check=0' );
header( 'Cache-Control: public' );
header( 'Content-Description: File Transfer' );
header( 'Content-Type: application/pdf' );
header( 'Content-Disposition: attachment; filename="xxx.pdf"' );
header( 'Content-Transfer-Encoding: binary' );
echo $content;
exit;
</code></pre>
<p>I also tried writing the file content to a temporary file first so I could also set the <code>Content-Length</code> in the header but that didn't help.</p>
| [
{
"answer_id": 49306,
"author": "Stu Thompson",
"author_id": 2961,
"author_profile": "https://Stackoverflow.com/users/2961",
"pm_score": 1,
"selected": false,
"text": "<p>I have had the exact same problem about a year ago, and after much googling and research, my headers (from Java code)... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3196/"
] | I've come across a rather interesing (and frustrating) problem with IE6. We are serving up some server generated pdfs and then simply setting headers in PHP to force a browser download of the file. Works fine and all, except in IE6 but **only** if the windows user account is set to standard user (ie. not administrator).
Since this is for a corporate environment, of course all their accounts are setup this way. Weird thing is, that in the download dialog, the Content-Type is not recognized:
```
header( 'Pragma: public' );
header( 'Expires: 0' );
header( 'Cache-Control: must-revalidate, pre-check=0, post-check=0' );
header( 'Cache-Control: public' );
header( 'Content-Description: File Transfer' );
header( 'Content-Type: application/pdf' );
header( 'Content-Disposition: attachment; filename="xxx.pdf"' );
header( 'Content-Transfer-Encoding: binary' );
echo $content;
exit;
```
I also tried writing the file content to a temporary file first so I could also set the `Content-Length` in the header but that didn't help. | some versions of IE seem to take
```
header( 'Expires: 0' );
header( 'Cache-Control: must-revalidate, pre-check=0, post-check=0' );
```
way too seriously and remove the downloaded content before it's passed to the plugin to display it.
Remove these two and you should be fine.
And make sure you are not using any server-side GZIP compression when working with PDFs because some versions of Acrobat seem to struggle with this.
I know I'm vague here, but above tips are based on real-world experience I got using a web application serving dynamically built PDFs containing barcodes. I don't know what versions are affected, I only know that using the two "tricks" above made the support calls go away :p |
49,302 | <p>We have some legacy code that needs to identify in the Page_Load which event caused the postback.
At the moment this is implemented by checking the Request data like this...</p>
<p>if (Request.Form["__EVENTTARGET"] != null<br>
&& (Request.Form["__EVENTTARGET"].IndexOf("BaseGrid") > -1 // BaseGrid event ( e.g. sort)<br>
|| Request.Form["btnSave"] != null // Save button </p>
<p>This is pretty ugly and breaks if someone renames a control. Is there a better way of doing this?</p>
<p>Rewriting each page so that it does not need to check this in Page_Load is not an option at the moment.</p>
| [
{
"answer_id": 49311,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 4,
"selected": true,
"text": "<p>This should get you the control that caused the postback:</p>\n\n<pre><code>public static Control GetPostBackControl(Page page... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1127460/"
] | We have some legacy code that needs to identify in the Page\_Load which event caused the postback.
At the moment this is implemented by checking the Request data like this...
if (Request.Form["\_\_EVENTTARGET"] != null
&& (Request.Form["\_\_EVENTTARGET"].IndexOf("BaseGrid") > -1 // BaseGrid event ( e.g. sort)
|| Request.Form["btnSave"] != null // Save button
This is pretty ugly and breaks if someone renames a control. Is there a better way of doing this?
Rewriting each page so that it does not need to check this in Page\_Load is not an option at the moment. | This should get you the control that caused the postback:
```
public static Control GetPostBackControl(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
return control;
}
```
Read more about this on this page:
<http://ryanfarley.com/blog/archive/2005/03/11/1886.aspx> |
49,307 | <p>Using the <code>zip</code> function, Python allows for loops to traverse multiple sequences in parallel. </p>
<p><code>for (x,y) in zip(List1, List2):</code></p>
<p>Does MATLAB have an equivalent syntax? If not, what is the best way to iterate over two parallel arrays at the same time using MATLAB?</p>
| [
{
"answer_id": 49514,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 3,
"selected": false,
"text": "<p>If I'm not mistaken the zip function you use in python <a href=\"http://groups.google.com/group/comp.lang.python/browse_thread/th... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49307",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5148/"
] | Using the `zip` function, Python allows for loops to traverse multiple sequences in parallel.
`for (x,y) in zip(List1, List2):`
Does MATLAB have an equivalent syntax? If not, what is the best way to iterate over two parallel arrays at the same time using MATLAB? | If x and y are column vectors, you can do:
```
for i=[x';y']
# do stuff with i(1) and i(2)
end
```
(with row vectors, just use `x` and `y`).
Here is an example run:
```matlab
>> x=[1 ; 2; 3;]
x =
1
2
3
>> y=[10 ; 20; 30;]
y =
10
20
30
>> for i=[x';y']
disp(['size of i = ' num2str(size(i)) ', i(1) = ' num2str(i(1)) ', i(2) = ' num2str(i(2))])
end
size of i = 2 1, i(1) = 1, i(2) = 10
size of i = 2 1, i(1) = 2, i(2) = 20
size of i = 2 1, i(1) = 3, i(2) = 30
>>
``` |
49,334 | <p>In my database, I have an entity table (let's call it Entity). Each entity can have a number of entity types, and the set of entity types is static. Therefore, there is a connecting table that contains rows of the entity id and the name of the entity type. In my code, EntityType is an enum, and Entity is a Hibernate-mapped class.<br>
in the Entity code, the mapping looks like this:</p>
<pre><code>@CollectionOfElements
@JoinTable(
name = "ENTITY-ENTITY-TYPE",
joinColumns = @JoinColumn(name = "ENTITY-ID")
)
@Column(name="ENTITY-TYPE")
public Set<EntityType> getEntityTypes() {
return entityTypes;
}
</code></pre>
<p>Oh, did I mention I'm using annotations?<br>
Now, what I'd like to do is create an HQL query or search using a Criteria for all Entity objects of a specific entity type.<p>
<a href="http://opensource.atlassian.com/projects/hibernate/browse/HHH-869?page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel" rel="nofollow noreferrer">This</a> page in the Hibernate forum says this is impossible, but then this page is 18 months old. Can anyone tell me if this feature has been implemented in one of the latest releases of Hibernate, or planned for the coming release?</p>
| [
{
"answer_id": 50402,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": 0,
"selected": false,
"text": "<p>Is your relationship bidirectional, i.e., does <code>EntityType</code> have an <code>Entity</code> property? If so, you c... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2819/"
] | In my database, I have an entity table (let's call it Entity). Each entity can have a number of entity types, and the set of entity types is static. Therefore, there is a connecting table that contains rows of the entity id and the name of the entity type. In my code, EntityType is an enum, and Entity is a Hibernate-mapped class.
in the Entity code, the mapping looks like this:
```
@CollectionOfElements
@JoinTable(
name = "ENTITY-ENTITY-TYPE",
joinColumns = @JoinColumn(name = "ENTITY-ID")
)
@Column(name="ENTITY-TYPE")
public Set<EntityType> getEntityTypes() {
return entityTypes;
}
```
Oh, did I mention I'm using annotations?
Now, what I'd like to do is create an HQL query or search using a Criteria for all Entity objects of a specific entity type.
[This](http://opensource.atlassian.com/projects/hibernate/browse/HHH-869?page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel) page in the Hibernate forum says this is impossible, but then this page is 18 months old. Can anyone tell me if this feature has been implemented in one of the latest releases of Hibernate, or planned for the coming release? | HQL:
```
select entity from Entity entity where :type = some elements(entity.types)
```
I think that you can also write it like:
```
select entity from Entity entity where :type in(entity.types)
``` |
49,346 | <p>Is it possible to prevent an asp.net Hyperlink control from linking, i.e. so that it appears as a label, without actually having to replace the control with a label? Maybe using CSS or setting an attribute?</p>
<p>I know that marking it as disabled works but then it gets displayed differently (greyed out).</p>
<p>To clarify my point, I have a list of user names at the top of my page which are built dynamically using a user control. Most of the time these names are linkable to an email page. However if the user has been disabled the name is displayed in grey but currently still links to the email page. I want these disabled users to not link.</p>
<p>I know that really I should be replacing them with a label but this does not seem quite as elegant as just removing the linking ability usings CSS say (if thats possible). They are already displayed in a different colour so its obvious that they are disabled users. I just need to switch off the link.</p>
| [
{
"answer_id": 49358,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 2,
"selected": false,
"text": "<p>If you merely want to modify the appearance of the link so as not to look like a link, you can set the CSS for your \"a\"... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49346",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1127460/"
] | Is it possible to prevent an asp.net Hyperlink control from linking, i.e. so that it appears as a label, without actually having to replace the control with a label? Maybe using CSS or setting an attribute?
I know that marking it as disabled works but then it gets displayed differently (greyed out).
To clarify my point, I have a list of user names at the top of my page which are built dynamically using a user control. Most of the time these names are linkable to an email page. However if the user has been disabled the name is displayed in grey but currently still links to the email page. I want these disabled users to not link.
I know that really I should be replacing them with a label but this does not seem quite as elegant as just removing the linking ability usings CSS say (if thats possible). They are already displayed in a different colour so its obvious that they are disabled users. I just need to switch off the link. | This sounds like a job for JQuery. Just give a specific class name to all of the HyperLink controls that you want the URLs removed and then apply the following JQuery snippet to the bottom of your page:
```
$(document).ready(function() {
$('a.NoLink').removeAttr('href')
});
```
All of the HyperLink controls with the class name "NoLink" will automatically have all of their URLs removed and the link will appear to be nothing more than text.
A single line of JQuery can solve your problem. |
49,350 | <p>What can be a practical solution to center vertically and horizontally content in HTML that works in Firefox, IE6 and IE7?</p>
<p>Some details:</p>
<ul>
<li><p>I am looking for solution for the entire page.</p></li>
<li><p>You need to specify only width of the element to be centered. Height of the element is not known in design time.</p></li>
<li><p>When minimizing window, scrolling should appear only when all white space is gone.
In other words, width of screen should be represented as: </p></li>
</ul>
<p>"leftSpace width=(screenWidth-widthOfCenteredElement)/2"+<br>
"centeredElement width=widthOfCenteredElement"+<br>
"rightSpace width=(screenWidth-widthOfCenteredElement)/2" </p>
<p>And the same for the height:</p>
<p>"topSpace height=(screenHeight-heightOfCenteredElement)/2"+<br>
"centeredElement height=heightOfCenteredElement"+<br>
"bottomSpace height=(screenWidth-heightOfCenteredElement)/2"</p>
<ul>
<li>By practical I mean that use of tables is OK. I intend to use this layout mostly for special pages like login. So CSS purity is not so important here, while following standards is desirable for future compatibility.</li>
</ul>
| [
{
"answer_id": 49353,
"author": "Oleksandr Yanovets",
"author_id": 5139,
"author_profile": "https://Stackoverflow.com/users/5139",
"pm_score": 2,
"selected": false,
"text": "<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5139/"
] | What can be a practical solution to center vertically and horizontally content in HTML that works in Firefox, IE6 and IE7?
Some details:
* I am looking for solution for the entire page.
* You need to specify only width of the element to be centered. Height of the element is not known in design time.
* When minimizing window, scrolling should appear only when all white space is gone.
In other words, width of screen should be represented as:
"leftSpace width=(screenWidth-widthOfCenteredElement)/2"+
"centeredElement width=widthOfCenteredElement"+
"rightSpace width=(screenWidth-widthOfCenteredElement)/2"
And the same for the height:
"topSpace height=(screenHeight-heightOfCenteredElement)/2"+
"centeredElement height=heightOfCenteredElement"+
"bottomSpace height=(screenWidth-heightOfCenteredElement)/2"
* By practical I mean that use of tables is OK. I intend to use this layout mostly for special pages like login. So CSS purity is not so important here, while following standards is desirable for future compatibility. | ```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Centering</title>
<style type="text/css" media="screen">
body, html {height: 100%; padding: 0px; margin: 0px;}
#outer {width: 100%; height: 100%; overflow: visible; padding: 0px; margin: 0px;}
#middle {vertical-align: middle}
#centered {width: 280px; margin-left: auto; margin-right: auto; text-align:center;}
</style>
</head>
<body>
<table id="outer" cellpadding="0" cellspacing="0">
<tr><td id="middle">
<div id="centered" style="border: 1px solid green;">
Centered content
</div>
</td></tr>
</table>
</body>
</html>
```
Solution from [community.contractwebdevelopment.com](http://community.contractwebdevelopment.com/css-vertically-horizontally-center) also is a good one. And if you know height of your content that needs to be centered seems to be better. |
49,356 | <p>We have the standard Subversion trunk/branches/tags layout. We have several branches for medium- and long-term projects, but none so far for a release. This is approaching fast.</p>
<p>Should we:</p>
<ol>
<li>Mix release branches and project branches together?</li>
<li>Create a releases folder? If so, is there a better name than releases?</li>
<li>Create a projects folder and move the current branches there? If so, is there a better name than projects? I've seen "sandbox" and "spike" in other repositories.</li>
<li>Something else altogether?</li>
</ol>
| [
{
"answer_id": 49366,
"author": "Polsonby",
"author_id": 137,
"author_profile": "https://Stackoverflow.com/users/137",
"pm_score": -1,
"selected": false,
"text": "<p>Releases is the same as tags... Have you got multiple projects inside your trunk? In that case, I would copy the same fold... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49356",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3984/"
] | We have the standard Subversion trunk/branches/tags layout. We have several branches for medium- and long-term projects, but none so far for a release. This is approaching fast.
Should we:
1. Mix release branches and project branches together?
2. Create a releases folder? If so, is there a better name than releases?
3. Create a projects folder and move the current branches there? If so, is there a better name than projects? I've seen "sandbox" and "spike" in other repositories.
4. Something else altogether? | I recommend the following layout, for two reasons:
- all stuff related to a given project is within the same part of the tree; makes
it easier for people to grasp
- permissions handling may be easier this way
And by the way: It's a good idea with few repositories, instead of many, because change history normally is better preserved that way (change history is gone if you move files between repositories, unless you take special and somewhat complicated action). In most setups, there should only be two repositories: the main repository, and a sandbox repository for people experimenting with Subversion.
```
project1
trunk
branches
1.0
1.1
joes-experimental-feature-branch
tags
1.0.0
1.0.1
1.0.2
project2
trunk
branches
1.0
1.1
tags
1.0.0
1.0.1
1.0.2
``` |
49,368 | <p><a href="http://www.w3.org/TR/REC-CSS2/selector.html#attribute-selectors" rel="noreferrer">CSS Attribute selectors</a> allow the selection of elements based on attribute values. Unfortunately, I've not used them in years (mainly because they're not supported by all modern browsers). However, I remember distinctly that I was able to use them to adorn all external links with an icon, by using a code similar to the following:</p>
<pre><code>a[href=http] {
background: url(external-uri);
padding-left: 12px;
}
</code></pre>
<p>The above code doesn't work. My question is: <strong>How does it work?</strong> How do I select all <code><a></code> tags whose <code>href</code> attribute starts with <code>"http"</code>? The official CSS spec (linked above) doesn't even mention that this is possible. But I do remember doing this.</p>
<p>(<em>Note</em>: The obvious solution would be to use <code>class</code> attributes for distinction. I want to avoid this because I have little influence of the way the HTML code is built. All I can edit is the CSS code.)</p>
| [
{
"answer_id": 49373,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 6,
"selected": true,
"text": "<p>As for CSS 2.1, see <a href=\"http://www.w3.org/TR/CSS21/selector.html#attribute-selectors\" rel=\"noreferrer\">ht... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49368",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1968/"
] | [CSS Attribute selectors](http://www.w3.org/TR/REC-CSS2/selector.html#attribute-selectors) allow the selection of elements based on attribute values. Unfortunately, I've not used them in years (mainly because they're not supported by all modern browsers). However, I remember distinctly that I was able to use them to adorn all external links with an icon, by using a code similar to the following:
```
a[href=http] {
background: url(external-uri);
padding-left: 12px;
}
```
The above code doesn't work. My question is: **How does it work?** How do I select all `<a>` tags whose `href` attribute starts with `"http"`? The official CSS spec (linked above) doesn't even mention that this is possible. But I do remember doing this.
(*Note*: The obvious solution would be to use `class` attributes for distinction. I want to avoid this because I have little influence of the way the HTML code is built. All I can edit is the CSS code.) | As for CSS 2.1, see <http://www.w3.org/TR/CSS21/selector.html#attribute-selectors>
Executive summary:
```
Attribute selectors may match in four ways:
[att]
Match when the element sets the "att" attribute, whatever the value of the attribute.
[att=val]
Match when the element's "att" attribute value is exactly "val".
[att~=val]
Match when the element's "att" attribute value is a space-separated list of
"words", one of which is exactly "val". If this selector is used, the words in the
value must not contain spaces (since they are separated by spaces).
[att|=val]
Match when the element's "att" attribute value is a hyphen-separated list of
"words", beginning with "val". The match always starts at the beginning of the
attribute value. This is primarily intended to allow language subcode matches
(e.g., the "lang" attribute in HTML) as described in RFC 3066 ([RFC3066]).
```
[CSS3 also defines a list of selectors](http://www.w3.org/TR/css3-selectors/#selectors), but [the compatibility varies hugely](http://rakaz.nl/item/how_well_do_browsers_support_css_selectors).
There's also [a nifty test suite](http://tools.css3.info/selectors-test/test.html) that that shows which selectors work in your browser.
As for your example,
```
a[href^=http]
{
background: url(external-uri);
padding-left: 12px;
}
```
should do the trick. Unfortunately, it is not supported by IE. |
49,402 | <p>Imagine a DOS style .cmd file which is used to launch interdependent windowed applications in the right order.</p>
<p>Example:<br>
1) Launch a server application by calling an exe with parameters.<br>
2) Wait for the server to become initialized (or a fixed amount of time).<br>
3) Launch client application by calling an exe with parameters.</p>
<p>What is the simplest way of accomplishing this kind of batch job in PowerShell?</p>
| [
{
"answer_id": 49520,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 0,
"selected": false,
"text": "<p>To wait 10 seconds between launching the applications, try</p>\n\n<pre><code>launch-server-application serverparam1 s... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49402",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5085/"
] | Imagine a DOS style .cmd file which is used to launch interdependent windowed applications in the right order.
Example:
1) Launch a server application by calling an exe with parameters.
2) Wait for the server to become initialized (or a fixed amount of time).
3) Launch client application by calling an exe with parameters.
What is the simplest way of accomplishing this kind of batch job in PowerShell? | Remember that PowerShell can access .Net objects. The Start-Sleep as suggested by [Blair Conrad](https://stackoverflow.com/questions/49402/creating-batch-jobs-in-powershell#49520) can be replaced by a call to [WaitForInputIdle](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.waitforinputidle.aspx) of the server process so you know when the server is ready before starting the client.
```
$sp = get-process server-application
$sp.WaitForInputIdle()
```
You could also use [Process.Start](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx) to start the process and have it return the exact Process. Then you don't need the get-process.
```
$sp = [diagnostics.process]::start("server-application", "params")
$sp.WaitForInputIdle()
$cp = [diagnostics.process]::start("client-application", "params")
``` |
49,403 | <p>I have a filename in a format like:</p>
<blockquote>
<p><code>system-source-yyyymmdd.dat</code></p>
</blockquote>
<p>I'd like to be able to parse out the different bits of the filename using the "-" as a delimiter.</p>
| [
{
"answer_id": 49406,
"author": "David",
"author_id": 381,
"author_profile": "https://Stackoverflow.com/users/381",
"pm_score": 3,
"selected": false,
"text": "<p>Use the <code>cut</code> command.</p>\n\n<p>e.g.</p>\n\n<pre><code>echo \"system-source-yyyymmdd.dat\" | cut -f1 -d'-'\n</code... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4003/"
] | I have a filename in a format like:
>
> `system-source-yyyymmdd.dat`
>
>
>
I'd like to be able to parse out the different bits of the filename using the "-" as a delimiter. | You can use the [cut command](http://en.wikipedia.org/wiki/Cut_(Unix)) to get at each of the 3 'fields', e.g.:
```
$ echo "system-source-yyyymmdd.dat" | cut -d'-' -f2
source
```
"-d" specifies the delimiter, "-f" specifies the number of the field you require |
49,404 | <p>I have a table containing prices for a lot of different "things" in a MS SQL 2005 table. There are hundreds of records per thing per day and the different things gets price updates at different times.</p>
<pre><code>ID uniqueidentifier not null,
ThingID int NOT NULL,
PriceDateTime datetime NOT NULL,
Price decimal(18,4) NOT NULL
</code></pre>
<p>I need to get today's latest prices for a group of things. The below query works but I'm getting hundreds of rows back and I have to loop trough them and only extract the latest one per ThingID. How can I (e.g. via a GROUP BY) say that I want the latest one per ThingID? Or will I have to use subqueries?</p>
<pre><code>SELECT *
FROM Thing
WHERE ThingID IN (1,2,3,4,5,6)
AND PriceDate > cast( convert(varchar(20), getdate(), 106) as DateTime)
</code></pre>
<p><strong>UPDATE:</strong> In an attempt to hide complexity I put the ID column in a an int. In real life it is GUID (and not the sequential kind). I have updated the table def above to use uniqueidentifier.</p>
| [
{
"answer_id": 49414,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 5,
"selected": true,
"text": "<p>I think the only solution with your table structure is to work with a subquery:</p>\n\n<pre><code>SELECT *\n FROM Thing\n WH... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49404",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008/"
] | I have a table containing prices for a lot of different "things" in a MS SQL 2005 table. There are hundreds of records per thing per day and the different things gets price updates at different times.
```
ID uniqueidentifier not null,
ThingID int NOT NULL,
PriceDateTime datetime NOT NULL,
Price decimal(18,4) NOT NULL
```
I need to get today's latest prices for a group of things. The below query works but I'm getting hundreds of rows back and I have to loop trough them and only extract the latest one per ThingID. How can I (e.g. via a GROUP BY) say that I want the latest one per ThingID? Or will I have to use subqueries?
```
SELECT *
FROM Thing
WHERE ThingID IN (1,2,3,4,5,6)
AND PriceDate > cast( convert(varchar(20), getdate(), 106) as DateTime)
```
**UPDATE:** In an attempt to hide complexity I put the ID column in a an int. In real life it is GUID (and not the sequential kind). I have updated the table def above to use uniqueidentifier. | I think the only solution with your table structure is to work with a subquery:
```
SELECT *
FROM Thing
WHERE ID IN (SELECT max(ID) FROM Thing
WHERE ThingID IN (1,2,3,4)
GROUP BY ThingID)
```
(Given the highest ID also means the newest price)
However I suggest you add a "IsCurrent" column that is 0 if it's not the latest price or 1 if it is the latest. This will add the possible risk of inconsistent data, but it will speed up the whole process a lot when the table gets bigger (if it is in an index). Then all you need to do is to...
```
SELECT *
FROM Thing
WHERE ThingID IN (1,2,3,4)
AND IsCurrent = 1
```
**UPDATE**
Okay, Markus updated the question to show that ID is a uniqueid, not an int. That makes writing the query even more complex.
```
SELECT T.*
FROM Thing T
JOIN (SELECT ThingID, max(PriceDateTime)
WHERE ThingID IN (1,2,3,4)
GROUP BY ThingID) X ON X.ThingID = T.ThingID
AND X.PriceDateTime = T.PriceDateTime
WHERE ThingID IN (1,2,3,4)
```
I'd really suggest using either a "IsCurrent" column or go with the other suggestion found in the answers and use "current price" table and a separate "price history" table (which would ultimately be the fastest, because it keeps the price table itself small).
(I know that the ThingID at the bottom is redundant. Just try if it is faster with or without that "WHERE". Not sure which version will be faster after the optimizer did its work.) |
49,430 | <p>I have just started working with the <code>AnimationExtender</code>. I am using it to show a new div with a list gathered from a database when a button is pressed. The problem is the button needs to do a postback to get this list as I don't want to make the call to the database unless it's needed. The postback however stops the animation mid flow and resets it. The button is within an update panel.</p>
<p>Ideally I would want the animation to start once the postback is complete and the list has been gathered. I have looked into using the <code>ScriptManager</code> to detect when the postback is complete and have made some progress. I have added two javascript methods to the page.</p>
<pre><code>function linkPostback() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(playAnimation)
}
function playAnimation() {
var onclkBehavior = $find("ctl00_btnOpenList").get_OnClickBehavior().get_animation();
onclkBehavior.play();
}
</code></pre>
<p>And I’ve changed the <code>btnOpenList.OnClientClick=”linkPostback();”</code></p>
<p>This almost solves the problem. I’m still get some animation stutter. The animation starts to play before the postback and then plays properly after postback. Using the <code>onclkBehavior.pause()</code> has no effect. I can get around this by setting the <code>AnimationExtender.Enabled = false</code> and setting it to true in the buttons postback event. This however works only once as now the AnimationExtender is enabled again. I have also tried disabling the <code>AnimationExtender</code> via javascript but this has no effect.</p>
<p>Is there a way of playing the animations only via javascript calls? I need to decouple the automatic link to the
buttons click event so I can control when the animation is fired.</p>
<p>Hope that makes sense.</p>
<p>Thanks</p>
<p>DG</p>
| [
{
"answer_id": 57774,
"author": "Andrew Johnson",
"author_id": 5109,
"author_profile": "https://Stackoverflow.com/users/5109",
"pm_score": 2,
"selected": true,
"text": "<p>The flow you are seeing is something like this:</p>\n\n<ol>\n<li>Click on button</li>\n<li>AnimationExtender catches... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5170/"
] | I have just started working with the `AnimationExtender`. I am using it to show a new div with a list gathered from a database when a button is pressed. The problem is the button needs to do a postback to get this list as I don't want to make the call to the database unless it's needed. The postback however stops the animation mid flow and resets it. The button is within an update panel.
Ideally I would want the animation to start once the postback is complete and the list has been gathered. I have looked into using the `ScriptManager` to detect when the postback is complete and have made some progress. I have added two javascript methods to the page.
```
function linkPostback() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(playAnimation)
}
function playAnimation() {
var onclkBehavior = $find("ctl00_btnOpenList").get_OnClickBehavior().get_animation();
onclkBehavior.play();
}
```
And I’ve changed the `btnOpenList.OnClientClick=”linkPostback();”`
This almost solves the problem. I’m still get some animation stutter. The animation starts to play before the postback and then plays properly after postback. Using the `onclkBehavior.pause()` has no effect. I can get around this by setting the `AnimationExtender.Enabled = false` and setting it to true in the buttons postback event. This however works only once as now the AnimationExtender is enabled again. I have also tried disabling the `AnimationExtender` via javascript but this has no effect.
Is there a way of playing the animations only via javascript calls? I need to decouple the automatic link to the
buttons click event so I can control when the animation is fired.
Hope that makes sense.
Thanks
DG | The flow you are seeing is something like this:
1. Click on button
2. AnimationExtender catches action and call clickOn callback
3. linkPostback starts asynchronous request for page and then returns flow to AnimationExtender
4. Animation begins
5. pageRequest returns and calls playAnimation, which starts the animation again
I think there are at least two ways around this issue. It seems you have almost all the javascript you need, you just need to work around AnimationExtender starting the animation on a click.
Option 1: Hide the AnimationExtender button and add a new button of your own that plays the animation. This should be as simple as setting the AE button's style to "display: none;" and having your own button call linkPostback().
Option 2: Re-disable the Animation Extender once the animation has finished with. This should work, as long as the playAnimation call is blocking, which it probably is:
```
function linkPostback() {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(playAnimation)
}
function playAnimation() {
AnimationExtender.Enabled = true;
var onclkBehavior = $find("ctl00_btnOpenList").get_OnClickBehavior().get_animation();
onclkBehavior.play();
AnimationExtender.Enabled = false;
}
```
As an aside, it seems your general approach may face issues if there is a delay in receiving the pageRequest. It may be a bit weird to click a button and several seconds later have the animation happen. It may be better to either pre-load the data, or to pre-fill the div with some "Loading..." thing, make it about the right size, and then populate the actual contents when it arrives. |
49,461 | <p>Is there a C# equivalent for the VB.NET <code>FormatNumber</code> function? </p>
<p>I.e.:</p>
<pre><code>JSArrayString += "^" + (String)FormatNumber(inv.RRP * oCountry.ExchangeRate, 2);
</code></pre>
| [
{
"answer_id": 49476,
"author": "d91-jal",
"author_id": 5085,
"author_profile": "https://Stackoverflow.com/users/5085",
"pm_score": 1,
"selected": false,
"text": "<p>You can use string formatters to accomplish the same thing.</p>\n\n<pre><code>double MyNumber = inv.RRP * oCountry.Exchang... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49461",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1583/"
] | Is there a C# equivalent for the VB.NET `FormatNumber` function?
I.e.:
```
JSArrayString += "^" + (String)FormatNumber(inv.RRP * oCountry.ExchangeRate, 2);
``` | In both C# and VB.NET you can use either the [.ToString()](http://www.java2s.com/Code/CSharp/Development-Class/UseToStringtoformatvalues.htm) function or the [String.Format()](http://www.java2s.com/Code/CSharp/Development-Class/UseStringFormattoformatavalue.htm) method to format the text.
Using the .ToString() method your example could be written as:
```
JSArrayString += "^" + (inv.RRP * oCountry.ExchangeRate).ToString("#0.00")
```
Alternatively using the String.Format() it could written as:
```
JSArrayString = String.Format("{0}^{1:#0.00}",JSArrayString,(inv.RRP * oCountry.ExchangeRate))
```
In both of the above cases I have used custom formatting for the currency with # representing an optional place holder and 0 representing a 0 or value if one exists.
Other formatting characters can be used to help with formatting such as D2 for 2 decimal places or C to display as currency. In this case you would not want to use the C formatter as this would have inserted the currency symbol and further separators which were not required.
See "[String.Format("{0}", "formatting string"};](http://idunno.org/archive/2004/14/01/122.aspx)" or "[String Format for Int](http://www.csharp-examples.net/string-format-int/)" for more information and examples on how to use String.Format and the different formatting options. |
49,473 | <p>Is <a href="http://bouncycastle.org/java.html" rel="nofollow noreferrer">Bouncy Castle API</a> Thread Safe ? Especially,</p>
<pre><code>org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher
org.bouncycastle.crypto.paddings.PKCS7Padding
org.bouncycastle.crypto.engines.AESFastEngine
org.bouncycastle.crypto.modes.CBCBlockCipher
</code></pre>
<p>I am planning to write a singleton Spring bean for basic level cryptography support in my app. Since it is a web application, there are greater chances of multiple threads accessing this component at a time. So tread safety is essential here.</p>
<p>Please let me know if you have come across such situations using Bouncy Castle.</p>
| [
{
"answer_id": 49498,
"author": "Tnilsson",
"author_id": 4165,
"author_profile": "https://Stackoverflow.com/users/4165",
"pm_score": 5,
"selected": true,
"text": "<p>It really does not matter if the API/Code is thread safe. CBC encryption in itself is not thread safe. \nSome terminology ... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/959/"
] | Is [Bouncy Castle API](http://bouncycastle.org/java.html) Thread Safe ? Especially,
```
org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher
org.bouncycastle.crypto.paddings.PKCS7Padding
org.bouncycastle.crypto.engines.AESFastEngine
org.bouncycastle.crypto.modes.CBCBlockCipher
```
I am planning to write a singleton Spring bean for basic level cryptography support in my app. Since it is a web application, there are greater chances of multiple threads accessing this component at a time. So tread safety is essential here.
Please let me know if you have come across such situations using Bouncy Castle. | It really does not matter if the API/Code is thread safe. CBC encryption in itself is not thread safe.
Some terminology -
```
E(X) = Enctrypt message X
D(X) = Dectrypt X. (Note that D(E(X)) = X)
IV = Initialization vector. A random sequence to bootstrap the CBC algorithm
CBC = Cipher block chaining.
```
A really simple CBC implementation can look like:
P1, P2, P3 = Plain text messages
```
1. Generate an IV, just random bits.
2. Calculate E( P1 xor IV) call this C1
3. Calculate E( P2 xor C1) call this C2
4. Calculate E( P3 xor C2) call this C3.
```
As you can see, the result of encrypting P1, P2 and P3 (in that order) is different from encrypting P2, P1 and P3 (in that order).
So, in a CBC implementation, order is important. Any algorithm where order is important can not, by definition, be thread safe.
You can make a Singleton factory that delivers encryption objects, but you cant trust them to be thread safe. |
49,478 | <p>Which files should I include in <code>.gitignore</code> when using <em>Git</em> in conjunction with <em>Xcode</em>?</p>
| [
{
"answer_id": 49488,
"author": "Hagelin",
"author_id": 5156,
"author_profile": "https://Stackoverflow.com/users/5156",
"pm_score": 8,
"selected": false,
"text": "<p>Based on <a href=\"http://boredzo.org/blog/archives/2008-03-20/hgignore-for-mac-os-x-applications\" rel=\"noreferrer\" tit... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49478",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5156/"
] | Which files should I include in `.gitignore` when using *Git* in conjunction with *Xcode*? | I was previously using the top-voted answer, but it needs a bit of cleanup, so here it is redone for Xcode 4, with some improvements.
I've researched *every* file in this list, but several of them do not exist in Apple's official Xcode documentation, so I had to go on Apple mailing lists.
Apple continues to add undocumented files, potentially corrupting our live projects. This IMHO is unacceptable, and I've now started logging bugs against it each time they do so. I know they don't care, but maybe it'll shame one of them into treating developers more fairly.
---
If you need to customize, here's a gist you can fork: <https://gist.github.com/3786883>
---
```
#########################
# .gitignore file for Xcode4 and Xcode5 Source projects
#
# Apple bugs, waiting for Apple to fix/respond:
#
# 15564624 - what does the xccheckout file in Xcode5 do? Where's the documentation?
#
# Version 2.6
# For latest version, see: http://stackoverflow.com/questions/49478/git-ignore-file-for-xcode-projects
#
# 2015 updates:
# - Fixed typo in "xccheckout" line - thanks to @lyck for pointing it out!
# - Fixed the .idea optional ignore. Thanks to @hashier for pointing this out
# - Finally added "xccheckout" to the ignore. Apple still refuses to answer support requests about this, but in practice it seems you should ignore it.
# - minor tweaks from Jona and Coeur (slightly more precise xc* filtering/names)
# 2014 updates:
# - appended non-standard items DISABLED by default (uncomment if you use those tools)
# - removed the edit that an SO.com moderator made without bothering to ask me
# - researched CocoaPods .lock more carefully, thanks to Gokhan Celiker
# 2013 updates:
# - fixed the broken "save personal Schemes"
# - added line-by-line explanations for EVERYTHING (some were missing)
#
# NB: if you are storing "built" products, this WILL NOT WORK,
# and you should use a different .gitignore (or none at all)
# This file is for SOURCE projects, where there are many extra
# files that we want to exclude
#
#########################
#####
# OS X temporary files that should never be committed
#
# c.f. http://www.westwind.com/reference/os-x/invisibles.html
.DS_Store
# c.f. http://www.westwind.com/reference/os-x/invisibles.html
.Trashes
# c.f. http://www.westwind.com/reference/os-x/invisibles.html
*.swp
#
# *.lock - this is used and abused by many editors for many different things.
# For the main ones I use (e.g. Eclipse), it should be excluded
# from source-control, but YMMV.
# (lock files are usually local-only file-synchronization on the local FS that should NOT go in git)
# c.f. the "OPTIONAL" section at bottom though, for tool-specific variations!
#
# In particular, if you're using CocoaPods, you'll want to comment-out this line:
*.lock
#
# profile - REMOVED temporarily (on double-checking, I can't find it in OS X docs?)
#profile
####
# Xcode temporary files that should never be committed
#
# NB: NIB/XIB files still exist even on Storyboard projects, so we want this...
*~.nib
####
# Xcode build files -
#
# NB: slash on the end, so we only remove the FOLDER, not any files that were badly named "DerivedData"
DerivedData/
# NB: slash on the end, so we only remove the FOLDER, not any files that were badly named "build"
build/
#####
# Xcode private settings (window sizes, bookmarks, breakpoints, custom executables, smart groups)
#
# This is complicated:
#
# SOMETIMES you need to put this file in version control.
# Apple designed it poorly - if you use "custom executables", they are
# saved in this file.
# 99% of projects do NOT use those, so they do NOT want to version control this file.
# ..but if you're in the 1%, comment out the line "*.pbxuser"
# .pbxuser: http://lists.apple.com/archives/xcode-users/2004/Jan/msg00193.html
*.pbxuser
# .mode1v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html
*.mode1v3
# .mode2v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html
*.mode2v3
# .perspectivev3: http://stackoverflow.com/questions/5223297/xcode-projects-what-is-a-perspectivev3-file
*.perspectivev3
# NB: also, whitelist the default ones, some projects need to use these
!default.pbxuser
!default.mode1v3
!default.mode2v3
!default.perspectivev3
####
# Xcode 4 - semi-personal settings
#
# Apple Shared data that Apple put in the wrong folder
# c.f. http://stackoverflow.com/a/19260712/153422
# FROM ANSWER: Apple says "don't ignore it"
# FROM COMMENTS: Apple is wrong; Apple code is too buggy to trust; there are no known negative side-effects to ignoring Apple's unofficial advice and instead doing the thing that actively fixes bugs in Xcode
# Up to you, but ... current advice: ignore it.
*.xccheckout
#
#
# OPTION 1: ---------------------------------
# throw away ALL personal settings (including custom schemes!
# - unless they are "shared")
# As per build/ and DerivedData/, this ought to have a trailing slash
#
# NB: this is exclusive with OPTION 2 below
xcuserdata/
# OPTION 2: ---------------------------------
# get rid of ALL personal settings, but KEEP SOME OF THEM
# - NB: you must manually uncomment the bits you want to keep
#
# NB: this *requires* git v1.8.2 or above; you may need to upgrade to latest OS X,
# or manually install git over the top of the OS X version
# NB: this is exclusive with OPTION 1 above
#
#xcuserdata/**/*
# (requires option 2 above): Personal Schemes
#
#!xcuserdata/**/xcschemes/*
####
# Xcode 4 workspaces - more detailed
#
# Workspaces are important! They are a core feature of Xcode - don't exclude them :)
#
# Workspace layout is quite spammy. For reference:
#
# /(root)/
# /(project-name).xcodeproj/
# project.pbxproj
# /project.xcworkspace/
# contents.xcworkspacedata
# /xcuserdata/
# /(your name)/xcuserdatad/
# UserInterfaceState.xcuserstate
# /xcshareddata/
# /xcschemes/
# (shared scheme name).xcscheme
# /xcuserdata/
# /(your name)/xcuserdatad/
# (private scheme).xcscheme
# xcschememanagement.plist
#
#
####
# Xcode 4 - Deprecated classes
#
# Allegedly, if you manually "deprecate" your classes, they get moved here.
#
# We're using source-control, so this is a "feature" that we do not want!
*.moved-aside
####
# OPTIONAL: Some well-known tools that people use side-by-side with Xcode / iOS development
#
# NB: I'd rather not include these here, but gitignore's design is weak and doesn't allow
# modular gitignore: you have to put EVERYTHING in one file.
#
# COCOAPODS:
#
# c.f. http://guides.cocoapods.org/using/using-cocoapods.html#what-is-a-podfilelock
# c.f. http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control
#
#!Podfile.lock
#
# RUBY:
#
# c.f. http://yehudakatz.com/2010/12/16/clarifying-the-roles-of-the-gemspec-and-gemfile/
#
#!Gemfile.lock
#
# IDEA:
#
# c.f. https://www.jetbrains.com/objc/help/managing-projects-under-version-control.html?search=workspace.xml
#
#.idea/workspace.xml
#
# TEXTMATE:
#
# -- UNVERIFIED: c.f. http://stackoverflow.com/a/50283/153422
#
#tm_build_errors
####
# UNKNOWN: recommended by others, but I can't discover what these files are
#
``` |
49,500 | <p>I'm trying to redirect requests for a wildcard domain to a sub-directory.<br />
ie. <code>something.blah.example.com</code> --> <code>blah.example.com/something</code></p>
<p>I don't know how to get the subdomain name to use in the rewrite rule.</p>
<p><strong>Final Solution:</strong></p>
<pre><code>RewriteCond %{HTTP_HOST} !^blah\.example\.com
RewriteCond %{HTTP_HOST} ^([^.]+)
RewriteRule ^(.*) /%1/$1 [L]
</code></pre>
<p>Or as pointed out by pilif</p>
<pre><code>RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.example\.com$
</code></pre>
| [
{
"answer_id": 49504,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 6,
"selected": true,
"text": "<p>You should have a look at the <a href=\"http://httpd.apache.org/docs/2.2/rewrite/\" rel=\"noreferrer\" title=\"URL Rewriting ... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428/"
] | I'm trying to redirect requests for a wildcard domain to a sub-directory.
ie. `something.blah.example.com` --> `blah.example.com/something`
I don't know how to get the subdomain name to use in the rewrite rule.
**Final Solution:**
```
RewriteCond %{HTTP_HOST} !^blah\.example\.com
RewriteCond %{HTTP_HOST} ^([^.]+)
RewriteRule ^(.*) /%1/$1 [L]
```
Or as pointed out by pilif
```
RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.example\.com$
``` | You should have a look at the [URL Rewriting Guide](http://httpd.apache.org/docs/2.2/rewrite/ "URL Rewriting Guide") from the apache documentation.
The following is untested, but it should to the trick:
```
RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.domain\.com$
RewriteRule ^/(.*)$ http://blah.domain.com/%1/$1 [L,R]
```
This only works if the subdomain contains no dots. Otherwise, you'd have to alter the Regexp in RewriteCond to match any character which should still work due to the anchoring, but this certainly feels safer. |
49,507 | <p>The system I'm currently working on consists of a controller PC running XP with .Net 2 connected to a set of embedded systems. All these components communicate with each other over an ethernet network. I'm currently using TcpClient.Connect on the XP computer to open a connection to the embedded systems to send TCP/IP messages. </p>
<p>I now have to connect the XP computer to an external network to send processing data to, so there are now two network cards on the XP computer. However, the messages sent to the external network mustn't appear on the network connecting the embedded systems together (don't want to consume the bandwidth) and the messages to the embedded systems mustn't appear on the external network.</p>
<p>So, the assertion I'm making is that messages sent to a defined IP address are sent out on both network cards when using the TcpClient.Connect method.</p>
<p>How do I specify which physical network card messages are sent via, ideally using the .Net networking API. If no such method exists in .Net, then I can always P/Invoke the Win32 API.</p>
<p>Skizz</p>
| [
{
"answer_id": 49518,
"author": "samjudson",
"author_id": 1908,
"author_profile": "https://Stackoverflow.com/users/1908",
"pm_score": 1,
"selected": false,
"text": "<p>Basically, once the TcpClient.Connect method has been successful, it will have created a mapping between the physical MA... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1898/"
] | The system I'm currently working on consists of a controller PC running XP with .Net 2 connected to a set of embedded systems. All these components communicate with each other over an ethernet network. I'm currently using TcpClient.Connect on the XP computer to open a connection to the embedded systems to send TCP/IP messages.
I now have to connect the XP computer to an external network to send processing data to, so there are now two network cards on the XP computer. However, the messages sent to the external network mustn't appear on the network connecting the embedded systems together (don't want to consume the bandwidth) and the messages to the embedded systems mustn't appear on the external network.
So, the assertion I'm making is that messages sent to a defined IP address are sent out on both network cards when using the TcpClient.Connect method.
How do I specify which physical network card messages are sent via, ideally using the .Net networking API. If no such method exists in .Net, then I can always P/Invoke the Win32 API.
Skizz | Try using a Socket for your client instead of the TcpClient Class.
Then you can use Socket.Bind to target your local network adapter
```
int port = 1234;
IPHostEntry entry = Dns.GetHostEntry(Dns.GetHostName());
//find ip address for your adapter here
IPAddress localAddress = entry.AddressList.FirstOrDefault();
IPEndPoint localEndPoint = new IPEndPoint(localAddress, port);
//use socket instead of a TcpClient
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//binds client to the local end point
client.Bind(localEndPoint);
```
<http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.bind.aspx> |
49,510 | <p>How do you set your Cocoa application as the default web browser?</p>
<p>I want to create an application that is launched by default when the user clicks on an HTTP or HTTPS link in other applications (Mail, iChat etc.).</p>
| [
{
"answer_id": 49512,
"author": "georgebrock",
"author_id": 5168,
"author_profile": "https://Stackoverflow.com/users/5168",
"pm_score": 7,
"selected": true,
"text": "<p>There are four steps to making an app that can act as the default web browser. The first three steps allow your app to ... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5168/"
] | How do you set your Cocoa application as the default web browser?
I want to create an application that is launched by default when the user clicks on an HTTP or HTTPS link in other applications (Mail, iChat etc.). | There are four steps to making an app that can act as the default web browser. The first three steps allow your app to act as a role handler for the relevant URL schemes (HTTP and HTTPS) and the final step makes it the default role handler for those schemes.
**1) Add the URL schemes your app can handle to your application's info.plist file**
To add support for `http://` and `https://` you'd need to add the following to your application's info.plist file. This tells the OS that your application is capable of handling HTTP and HTTP URLs.
```xml
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>http URL</string>
<key>CFBundleURLSchemes</key>
<array>
<string>http</string>
</array>
</dict>
<dict>
<key>CFBundleURLName</key>
<string>Secure http URL</string>
<key>CFBundleURLSchemes</key>
<array>
<string>https</string>
</array>
</dict>
</array>
```
**2) Write an URL handler method**
This method will be called by the OS when it wants to use your application to open a URL. It doesn't matter which object you add this method to, that'll be explicitly passed to the Event Manager in the next step. The URL handler method should look something like this:
```
- (void)getUrl:(NSAppleEventDescriptor *)event
withReplyEvent:(NSAppleEventDescriptor *)replyEvent
{
// Get the URL
NSString *urlStr = [[event paramDescriptorForKeyword:keyDirectObject]
stringValue];
//TODO: Your custom URL handling code here
}
```
**3) Register the URL handler method**
Next, tell the event manager which object and method to call when it wants to use your app to load an URL. In the code here I'm passed `self` as the event handler, assuming that we're calling `setEventHandler` from the same object that defines the `getUrl:withReplyEvent:` method.
You should add this code somewhere in your application's initialisation code.
```
NSAppleEventManager *em = [NSAppleEventManager sharedAppleEventManager];
[em
setEventHandler:self
andSelector:@selector(getUrl:withReplyEvent:)
forEventClass:kInternetEventClass
andEventID:kAEGetURL];
```
Some applications, including early versions of Adobe AIR, use the alternative WWW!/OURL AppleEvent to request that an application opens URLs, so to be compatible with those applications you should also add the following:
```
[em
setEventHandler:self
andSelector:@selector(getUrl:withReplyEvent:)
forEventClass:'WWW!'
andEventID:'OURL'];
```
**4) Set your app as the default browser**
Everything we've done so far as told the OS that your application is *a browser*, now we need to make it *the default browser*.
We've got to use the Launch Services API to do this. In this case we're setting our app to be the default role handler for HTTP and HTTPS links:
```
CFStringRef bundleID = (CFStringRef)[[NSBundle mainBundle] bundleIdentifier];
OSStatus httpResult = LSSetDefaultHandlerForURLScheme(CFSTR("http"), bundleID);
OSStatus httpsResult = LSSetDefaultHandlerForURLScheme(CFSTR("https"), bundleID);
//TODO: Check httpResult and httpsResult for errors
```
(It's probably best to ask the user's permission before changing their default browser.)
**Custom URL schemes**
It's worth noting that you can also use these same steps to handle your own custom URL schemes. If you're creating a custom URL scheme it's a good idea to base it on your app's bundle identifier to avoid clashes with other apps. So if your bundle ID is `com.example.MyApp` you should consider using `x-com-example-myapp://` URLs. |
49,511 | <p>I have played with the idea of using a wiki (MediaWiki) to centralize all project information for a development project. This was done using extensions that pull information from SVN (using <a href="http://svnkit.com/" rel="nofollow noreferrer">SVNKit</a>) and by linking to Bugzilla to extract work assigned to a developer or work remaining for a release.</p>
<p>Examples:</p>
<pre><code><bugzilla type="summary" user="richard.tasker@gmail.com" />
</code></pre>
<p>would return a summary</p>
<p><img src="https://i.stack.imgur.com/rfJjy.png" alt="Bugzilla Summary"></p>
<pre><code><bugzilla type="status" status="ASSIGNED" product="SCM BEPPI" />
</code></pre>
<p>would return</p>
<p><img src="https://i.stack.imgur.com/YSV0t.png" alt="Bugzilla Status"></p>
<p>Do you think that this would be useful? If so then what other integrations would you think would be valuable?</p>
| [
{
"answer_id": 49523,
"author": "Andreas Kraft",
"author_id": 4799,
"author_profile": "https://Stackoverflow.com/users/4799",
"pm_score": 3,
"selected": true,
"text": "<p>I think this would be extremly useful. Depending on the size of a project team members come and go. And a wiki is a g... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2939/"
] | I have played with the idea of using a wiki (MediaWiki) to centralize all project information for a development project. This was done using extensions that pull information from SVN (using [SVNKit](http://svnkit.com/)) and by linking to Bugzilla to extract work assigned to a developer or work remaining for a release.
Examples:
```
<bugzilla type="summary" user="richard.tasker@gmail.com" />
```
would return a summary

```
<bugzilla type="status" status="ASSIGNED" product="SCM BEPPI" />
```
would return

Do you think that this would be useful? If so then what other integrations would you think would be valuable? | I think this would be extremly useful. Depending on the size of a project team members come and go. And a wiki is a good tool to keep the history and the "spirit" of a project available to new team members. I did that in many projects, and though the projects were already finished, all the informations are available.
One more idea: also try to integrate meeting schedules, minutes etc. If your team communicates via IM, try to integrate a log of the conversations. |
49,536 | <p>You find plenty of tutorials on menu bars in HTML, but for this specific (though IMHO generic) case, I haven't found any decent solution:</p>
<pre><code># THE MENU ITEMS SHOULD BE JUSTIFIED JUST AS PLAIN TEXT WOULD BE #
# ^ ^ #
</code></pre>
<ul>
<li>There's an varying number of text-only menu items and the page layout is fluid.</li>
<li>The first menu item should be left-aligned, the last menu item should be right-aligned.</li>
<li>The remaining items should be spread optimally on the menu bar.</li>
<li>The number is varying,so there's no chance to pre-calculate the optimal widths.</li>
</ul>
<p>Note that a TABLE won't work here as well:</p>
<ul>
<li>If you center all TDs, the first and the last item aren’t aligned correctly.</li>
<li>If you left-align and right-align the first resp. the last items, the spacing will be sub-optimal.</li>
</ul>
<p>Isn’t it strange that there is no obvious way to implement this in a clean way by using HTML and CSS?</p>
| [
{
"answer_id": 49538,
"author": "Jordi Bunster",
"author_id": 4272,
"author_profile": "https://Stackoverflow.com/users/4272",
"pm_score": 2,
"selected": false,
"text": "<p>Make it a <code><p></code> with <code>text-align: justify</code> ?</p>\n\n<p><strong>Update</strong>: Nevermin... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49536",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3377/"
] | You find plenty of tutorials on menu bars in HTML, but for this specific (though IMHO generic) case, I haven't found any decent solution:
```
# THE MENU ITEMS SHOULD BE JUSTIFIED JUST AS PLAIN TEXT WOULD BE #
# ^ ^ #
```
* There's an varying number of text-only menu items and the page layout is fluid.
* The first menu item should be left-aligned, the last menu item should be right-aligned.
* The remaining items should be spread optimally on the menu bar.
* The number is varying,so there's no chance to pre-calculate the optimal widths.
Note that a TABLE won't work here as well:
* If you center all TDs, the first and the last item aren’t aligned correctly.
* If you left-align and right-align the first resp. the last items, the spacing will be sub-optimal.
Isn’t it strange that there is no obvious way to implement this in a clean way by using HTML and CSS? | ### Modern Approach - [Flexboxes](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes)!
Now that [CSS3 flexboxes](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Flexible_boxes) have [better browser support](http://caniuse.com/#feat=flexbox), some of us can finally start using them. Just add additional vendor prefixes for [more browser coverage](http://caniuse.com/#feat=flexbox).
In this instance, you would just set the parent element's `display` to `flex` and then change the [`justify-content` property](https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content) to either [`space-between`](http://jsfiddle.net/vomckkpc/) or [`space-around`](http://jsfiddle.net/putpyo16/) in order to add space between or around the children flexbox items.
**Using `justify-content: space-between`** - [(**example here)**](http://jsfiddle.net/vomckkpc/):
```css
ul {
list-style: none;
padding: 0;
margin: 0;
}
.menu {
display: flex;
justify-content: space-between;
}
```
```html
<ul class="menu">
<li>Item One</li>
<li>Item Two</li>
<li>Item Three Longer</li>
<li>Item Four</li>
</ul>
```
---
**Using `justify-content: space-around`** - [**(example here)**](http://jsfiddle.net/putpyo16/):
```css
ul {
list-style: none;
padding: 0;
margin: 0;
}
.menu {
display: flex;
justify-content: space-around;
}
```
```html
<ul class="menu">
<li>Item One</li>
<li>Item Two</li>
<li>Item Three Longer</li>
<li>Item Four</li>
</ul>
``` |
49,547 | <p>Our investigations have shown us that not all browsers respect the HTTP cache directives in a uniform manner.</p>
<p>For security reasons we do not want certain pages in our application to be cached, <strong>ever,</strong> by the web browser. This must work for at least the following browsers:</p>
<ul>
<li>Internet Explorer 6+</li>
<li>Firefox 1.5+</li>
<li>Safari 3+</li>
<li>Opera 9+</li>
<li>Chrome</li>
</ul>
<p>Our requirement came from a security test. After logging out from our website you could press the back button and view cached pages.</p>
| [
{
"answer_id": 49548,
"author": "Anders Sandvig",
"author_id": 1709,
"author_profile": "https://Stackoverflow.com/users/1709",
"pm_score": 3,
"selected": false,
"text": "<p>Setting the modified http header to some date in 1995 usually does the trick.</p>\n\n<p>Here's an example:</p>\n\n<... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5182/"
] | Our investigations have shown us that not all browsers respect the HTTP cache directives in a uniform manner.
For security reasons we do not want certain pages in our application to be cached, **ever,** by the web browser. This must work for at least the following browsers:
* Internet Explorer 6+
* Firefox 1.5+
* Safari 3+
* Opera 9+
* Chrome
Our requirement came from a security test. After logging out from our website you could press the back button and view cached pages. | Introduction
============
The correct minimum set of headers that works across all mentioned clients (and proxies):
```
Cache-Control: no-cache, no-store, must-revalidate
Pragma: no-cache
Expires: 0
```
The [`Cache-Control`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9) is per the HTTP 1.1 spec for clients and proxies (and implicitly required by some clients next to `Expires`). The [`Pragma`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32) is per the HTTP 1.0 spec for prehistoric clients. The [`Expires`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.21) is per the HTTP 1.0 and 1.1 specs for clients and proxies. In HTTP 1.1, the `Cache-Control` takes precedence over `Expires`, so it's after all for HTTP 1.0 proxies only.
If you don't care about IE6 and its broken caching when serving pages over HTTPS with only `no-store`, then you could omit `Cache-Control: no-cache`.
```
Cache-Control: no-store, must-revalidate
Pragma: no-cache
Expires: 0
```
If you don't care about IE6 nor HTTP 1.0 clients (HTTP 1.1 was introduced in 1997), then you could omit `Pragma`.
```
Cache-Control: no-store, must-revalidate
Expires: 0
```
If you don't care about HTTP 1.0 proxies either, then you could omit `Expires`.
```
Cache-Control: no-store, must-revalidate
```
On the other hand, if the server auto-includes a valid `Date` header, then you could theoretically omit `Cache-Control` too and rely on `Expires` only.
```
Date: Wed, 24 Aug 2016 18:32:02 GMT
Expires: 0
```
But that may fail if e.g. the end-user manipulates the operating system date and the client software is relying on it.
Other `Cache-Control` parameters such as `max-age` are irrelevant if the abovementioned `Cache-Control` parameters are specified. The [`Last-Modified`](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.29) header as included in most other answers here is *only* interesting if you **actually want** to cache the request, so you don't need to specify it at all.
How to set it?
==============
Using PHP:
```php
header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1.
header("Pragma: no-cache"); // HTTP 1.0.
header("Expires: 0"); // Proxies.
```
Using Java Servlet, or Node.js:
```java
response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setHeader("Expires", "0"); // Proxies.
```
Using ASP.NET-MVC
```cs
Response.Cache.SetCacheability(HttpCacheability.NoCache); // HTTP 1.1.
Response.Cache.AppendCacheExtension("no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.
```
Using ASP.NET Web API:
```cs
// `response` is an instance of System.Net.Http.HttpResponseMessage
response.Headers.CacheControl = new CacheControlHeaderValue
{
NoCache = true,
NoStore = true,
MustRevalidate = true
};
response.Headers.Pragma.ParseAdd("no-cache");
// We can't use `response.Content.Headers.Expires` directly
// since it allows only `DateTimeOffset?` values.
response.Content?.Headers.TryAddWithoutValidation("Expires", 0.ToString());
```
Using ASP.NET:
```cs
Response.AppendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.0.
Response.AppendHeader("Expires", "0"); // Proxies.
```
Using ASP.NET Core v3
```c#
// using Microsoft.Net.Http.Headers
Response.Headers[HeaderNames.CacheControl] = "no-cache, no-store, must-revalidate";
Response.Headers[HeaderNames.Expires] = "0";
Response.Headers[HeaderNames.Pragma] = "no-cache";
```
Using ASP:
```vb
Response.addHeader "Cache-Control", "no-cache, no-store, must-revalidate" ' HTTP 1.1.
Response.addHeader "Pragma", "no-cache" ' HTTP 1.0.
Response.addHeader "Expires", "0" ' Proxies.
```
Using Ruby on Rails:
```ruby
headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.
headers["Pragma"] = "no-cache" # HTTP 1.0.
headers["Expires"] = "0" # Proxies.
```
Using Python/Flask:
```python
response = make_response(render_template(...))
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.
response.headers["Pragma"] = "no-cache" # HTTP 1.0.
response.headers["Expires"] = "0" # Proxies.
```
Using Python/Django:
```python
response["Cache-Control"] = "no-cache, no-store, must-revalidate" # HTTP 1.1.
response["Pragma"] = "no-cache" # HTTP 1.0.
response["Expires"] = "0" # Proxies.
```
Using Python/Pyramid:
```python
request.response.headerlist.extend(
(
('Cache-Control', 'no-cache, no-store, must-revalidate'),
('Pragma', 'no-cache'),
('Expires', '0')
)
)
```
Using Go:
```default
responseWriter.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1.
responseWriter.Header().Set("Pragma", "no-cache") // HTTP 1.0.
responseWriter.Header().Set("Expires", "0") // Proxies.
```
Using Clojure (require Ring utils):
```clj
(require '[ring.util.response :as r])
(-> response
(r/header "Cache-Control" "no-cache, no-store, must-revalidate")
(r/header "Pragma" "no-cache")
(r/header "Expires" 0))
```
Using Apache `.htaccess` file:
```xml
<IfModule mod_headers.c>
Header set Cache-Control "no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires 0
</IfModule>
```
Using HTML:
```html
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
```
HTML meta tags vs HTTP response headers
=======================================
Important to know is that when an HTML page is served over an HTTP connection, and a header is present in **both** the HTTP response headers and the HTML `<meta http-equiv>` tags, then the one specified in the HTTP response header will get precedence over the HTML meta tag. The HTML meta tag will only be used when the page is viewed from a local disk file system via a `file://` URL. See also [W3 HTML spec chapter 5.2.2](http://www.w3.org/TR/html4/charset.html#h-5.2.2). Take care with this when you don't specify them programmatically because the webserver can namely include some default values.
Generally, you'd better just **not** specify the HTML meta tags to avoid confusion by starters and rely on hard HTTP response headers. Moreover, specifically those `<meta http-equiv>` tags are [**invalid**](http://validator.w3.org) in HTML5. Only the `http-equiv` values listed in [HTML5 specification](http://w3c.github.io/html/document-metadata.html#pragma-directives) are allowed.
Verifying the actual HTTP response headers
==========================================
To verify the one and the other, you can see/debug them in the HTTP traffic monitor of the web browser's developer toolset. You can get there by pressing F12 in Chrome/Firefox23+/IE9+, and then opening the "Network" or "Net" tab panel, and then clicking the HTTP request of interest to uncover all detail about the HTTP request and response. The [below screenshot](https://i.stack.imgur.com/fSnXH.png) is from Chrome:

I want to set those headers on file downloads too
=================================================
First of all, this question and answer are targeted on "web pages" (HTML pages), not "file downloads" (PDF, zip, Excel, etc). You'd better have them cached and make use of some file version identifier somewhere in the URI path or query string to force a redownload on a changed file. When applying those no-cache headers on file downloads anyway, then beware of the IE7/8 bug when serving a file download over HTTPS instead of HTTP. For detail, see [IE cannot download foo.jsf. IE was not able to open this internet site. The requested site is either unavailable or cannot be found](https://stackoverflow.com/q/5034454). |
49,562 | <p>I think this is a fun engineering-level question.</p>
<p>I need to design a control which displays a line chart. What I want to be able to do is use a designer to add multiple <code>Pens</code> which actually describe the data and presentation so that it ends up with Xaml something along these lines:</p>
<pre><code><Chart>
<Pen Name="SalesData" Color="Green" Data="..."/>
<Pen Name="CostData" Color="Red" Data="..." />
...
</chart>
</code></pre>
<p>My first thought is to extend <code>ItemsControl</code> for the <code>Chart</code> class. Will that get me where I want to go or should I be looking at it from a different direction such as extending <code>Panel</code>?</p>
<p>The major requirement is to be able to use it in a designer without adding any C# code. In order for that to even be feasible, it needs to retain its structure in the tree-view model. In other words, if I were working with this in Expression Blend or Mobiform Aurora, I would be able to select the chart from the logical tree or select any of the individual pens to edit their properties.</p>
| [
{
"answer_id": 51997,
"author": "NotDan",
"author_id": 3291,
"author_profile": "https://Stackoverflow.com/users/3291",
"pm_score": 0,
"selected": false,
"text": "<p>Another option is to extend Canvas for the chart and extend Shape for the Pens. Then dynamically draw the shape based on t... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93/"
] | I think this is a fun engineering-level question.
I need to design a control which displays a line chart. What I want to be able to do is use a designer to add multiple `Pens` which actually describe the data and presentation so that it ends up with Xaml something along these lines:
```
<Chart>
<Pen Name="SalesData" Color="Green" Data="..."/>
<Pen Name="CostData" Color="Red" Data="..." />
...
</chart>
```
My first thought is to extend `ItemsControl` for the `Chart` class. Will that get me where I want to go or should I be looking at it from a different direction such as extending `Panel`?
The major requirement is to be able to use it in a designer without adding any C# code. In order for that to even be feasible, it needs to retain its structure in the tree-view model. In other words, if I were working with this in Expression Blend or Mobiform Aurora, I would be able to select the chart from the logical tree or select any of the individual pens to edit their properties. | I would go with Chart as an ItemsControl and its ItemsPanel be a Canvas(For some light use I would go with Grid as ItemsPanel). And each Pen will be a CustomControl derived from PolyLine class. Does that make any sense? |
49,596 | <p>What is the difference between</p>
<pre><code>char str1[32] = "\0";
</code></pre>
<p>and </p>
<pre><code>char str2[32] = "";
</code></pre>
| [
{
"answer_id": 49620,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 6,
"selected": true,
"text": "<p>Since you already declared the sizes, the two declarations are exactly equal. However, if you do not specify the sizes, y... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49596",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123/"
] | What is the difference between
```
char str1[32] = "\0";
```
and
```
char str2[32] = "";
``` | Since you already declared the sizes, the two declarations are exactly equal. However, if you do not specify the sizes, you can see that the first declaration makes a larger string:
```
char a[] = "a\0";
char b[] = "a";
printf("%i %i\n", sizeof(a), sizeof(b));
```
prints
```
3 2
```
This is because a ends with two nulls (the explicit one and the implicit one) while b ends only with the implicit one. |
49,599 | <p>Jquery has a great language construct that looks like this:</p>
<pre><code>$(document).ready(function() {
$("a").click(function() {
alert("Hello world!");
});
});
</code></pre>
<p>As you might guess this, once the document has loaded, binds a custom function to the onClick event of all <strong><em>a</em></strong> tags.</p>
<p>The question is, how can I achieve this same kind of behavior in Prototype?</p>
| [
{
"answer_id": 49618,
"author": "David McLaughlin",
"author_id": 3404,
"author_profile": "https://Stackoverflow.com/users/3404",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Event.observe(window, 'load', function() { \n Event.observe(element, 'click', function() { \n ... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/305/"
] | Jquery has a great language construct that looks like this:
```
$(document).ready(function() {
$("a").click(function() {
alert("Hello world!");
});
});
```
As you might guess this, once the document has loaded, binds a custom function to the onClick event of all ***a*** tags.
The question is, how can I achieve this same kind of behavior in Prototype? | Prototype 1.6 provides the ["dom:loaded"](http://prototypejs.org/api/document/observe) event on document:
```
document.observe("dom:loaded", function() {
$$('a').each(function(elem) {
elem.observe("click", function() { alert("Hello World"); });
});
});
```
I also use the [each](http://prototypejs.org/api/enumerable/each) iterator on the array returned by [$$](http://prototypejs.org/api/utility/dollar-dollar)(). |
49,602 | <p>In Oracle, the number of rows returned in an arbitrary query can be limited by filtering on the "virtual" <code>rownum</code> column. Consider the following example, which will return, at most, 10 rows.</p>
<pre>SELECT * FROM all_tables WHERE rownum <= 10</pre>
<p>Is there a simple, generic way to do something similar in Ingres?</p>
| [
{
"answer_id": 49604,
"author": "Tnilsson",
"author_id": 4165,
"author_profile": "https://Stackoverflow.com/users/4165",
"pm_score": 4,
"selected": true,
"text": "<p>Blatantly changing my answer. \"Limit 10\" works for MySql and others, Ingres uses</p>\n\n<pre><code>Select First 10 * fro... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49602",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5193/"
] | In Oracle, the number of rows returned in an arbitrary query can be limited by filtering on the "virtual" `rownum` column. Consider the following example, which will return, at most, 10 rows.
```
SELECT * FROM all_tables WHERE rownum <= 10
```
Is there a simple, generic way to do something similar in Ingres? | Blatantly changing my answer. "Limit 10" works for MySql and others, Ingres uses
```
Select First 10 * from myTable
```
[Ref](http://docs.ingres.com/sqlref/Selectinteractive) |
49,630 | <p>I'm using JavaScript to hide an image and show some text thats hidden under it. But, when the text is shown if you scroll over it, it fires the mouseout event on the container, that then hides the text and shows the image again, and it just goes into a weird loop.</p>
<p>The html looks like this:</p>
<pre><code><div onmouseover="jsHoverIn('1')"
onmouseout="jsHoverOut('1')">
<div id="image1" />
<div id="text1" style="display: none;">
<p>some content</p>
<p>some more content</p>
</div>
</div>
</code></pre>
<p>And the javascript (It uses scriptaculous):</p>
<pre><code>function jsHoverIn(id) {
if(!visible[id]) {
new Effect.Fade ("image" + id, {queue: { position: 'end', scope: id } });
new Effect.Appear ("text" + id, {queue: { position: 'end', scope: id } });
visible[id] = true;
}
}
function jsHoverOut (id) {
var scope = Effect.Queues.get(id);
scope.each(function(effect) { effect.cancel(); });
new Effect.Fade ("text" + id, {queue: { position: 'end', scope: id } });
new Effect.Appear ("image" + id, {queue: { position: 'end', scope: id } });
visible[id] = false;
}
</code></pre>
<p>This seems really simple, but i just cant wrap my head around it.</p>
| [
{
"answer_id": 49645,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": -1,
"selected": false,
"text": "<p>This may not be the best solution but you could set a global boolean variable that would be accessible to bot... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/550/"
] | I'm using JavaScript to hide an image and show some text thats hidden under it. But, when the text is shown if you scroll over it, it fires the mouseout event on the container, that then hides the text and shows the image again, and it just goes into a weird loop.
The html looks like this:
```
<div onmouseover="jsHoverIn('1')"
onmouseout="jsHoverOut('1')">
<div id="image1" />
<div id="text1" style="display: none;">
<p>some content</p>
<p>some more content</p>
</div>
</div>
```
And the javascript (It uses scriptaculous):
```
function jsHoverIn(id) {
if(!visible[id]) {
new Effect.Fade ("image" + id, {queue: { position: 'end', scope: id } });
new Effect.Appear ("text" + id, {queue: { position: 'end', scope: id } });
visible[id] = true;
}
}
function jsHoverOut (id) {
var scope = Effect.Queues.get(id);
scope.each(function(effect) { effect.cancel(); });
new Effect.Fade ("text" + id, {queue: { position: 'end', scope: id } });
new Effect.Appear ("image" + id, {queue: { position: 'end', scope: id } });
visible[id] = false;
}
```
This seems really simple, but i just cant wrap my head around it. | I'd give the container div:
```
position: relative;
```
and add a third div in the container (should be the last child of the container) with:
```
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
```
and catch the mouseover and mouseout events on this div instead.
Because it has no child elements, you shouldn't get spurious mouseover and mouseout events propagating to it.
*Edit:*
What I believe happens, is that when the cursor moves from a parent element onto a child element, a mouseout event occurs on the parent element, and a mouseover event occurs on the child element. However, if the mouseover handler on the child element does not catch the event and stop it propagating, the parent element will also receive the mouseover event. |
49,652 | <p>Can someone suggest some good automated test suite framework for Perl?</p>
| [
{
"answer_id": 49694,
"author": "Leon Timmermans",
"author_id": 4727,
"author_profile": "https://Stackoverflow.com/users/4727",
"pm_score": 0,
"selected": false,
"text": "<p>I'd go for Test::More, or in general, anything that outputs <a href=\"http://en.wikipedia.org/wiki/Test_Anything_P... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49652",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4406/"
] | Can someone suggest some good automated test suite framework for Perl? | It really depends on what you're trying to do, but here's some background for much of this.
First, you would generally write your test programs with Test::More or Test::Simple as the core testing program:
```
use Test::More tests => 2;
is 3, 3, 'basic equality should work';
ok !0, '... and zero should be false';
```
Internally, Test::Builder is called to output those test results as TAP ([Test Anything Protocol](http://testanything.org/wiki/index.php/Main_Page)). Test::Harness (a thin wrapper around TAP::Harness), reads and interprets the TAP, telling you if your tests passed or failed. The "prove" tool mentioned above is bundled with Test::Harness, so let's say that save the above in the t/ directory (the standard Perl testing directory) as "numbers.t", then you can run it with this command:
```
prove --verbose t/numbers.t
```
Or to run all tests in that directory (recursively, assuming you want to descend into subdirectories):
```
prove --verbose -r t/
```
(--verbose, of course, is optional).
As a side note, don't use TestUnit. Many people recommend it, but it was abandoned a long time ago and doesn't integrate with modern testing tools. |
49,662 | <p>My company is looking to start distributing some software we developed and would like to be able to let people try the software out before buying. We'd also like to make sure it can't be copied and distributed to our customers' customers.</p>
<p>One model we've seen is tying a license to a MAC address so the software will only work on one machine.</p>
<p>What I'm wondering is, what's a good way to generate a license key with different information embedded in it such as license expiration date, MAC address, and different software restrictions?</p>
| [
{
"answer_id": 49666,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 4,
"selected": true,
"text": "<p>I'd suggest you take the pieces of information you want in the key, and hash it with md5, and then just take the first ... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5106/"
] | My company is looking to start distributing some software we developed and would like to be able to let people try the software out before buying. We'd also like to make sure it can't be copied and distributed to our customers' customers.
One model we've seen is tying a license to a MAC address so the software will only work on one machine.
What I'm wondering is, what's a good way to generate a license key with different information embedded in it such as license expiration date, MAC address, and different software restrictions? | I'd suggest you take the pieces of information you want in the key, and hash it with md5, and then just take the first X characters (where X is a key length you think is manageable).
Cryptographically, it's far from perfect, but this is the sort of area where you want to put in the minimum amount of effort which will stop a casual attacker - anything more quickly becomes a black hole.
Oh, I should also point out, you will want to provide the expiration date (and any other information you might want to read out yourself) in plain text (or slightly obfuscated) as part of the key as well if you go down this path - The md5 is just to stop the end user from changing he expiration date to extend the license.
The easiest thing would be a key file like this...
```
# License key for XYZZY
expiry-date=2009-01-01
other-info=blah
key=[md5 has of MAC address, expiry date, other-info]
``` |
49,668 | <p>I need to find out time taken by a function in my application. Application is a MS VIsual Studio 2005 solution, all C code. </p>
<p>I used thw windows API GetLocalTime(SYSTEMTIME *) to get the current system time before and after the function call which I want to measure time of.
But this has shortcoming that it lowest resolution is only 1msec. Nothing below that. So I cannot get any time granularity in micro seconds. </p>
<p>I know that time() which gives the time elapsed since the epoch time, also has resolution of 1msec (No microseconds) </p>
<p>1.) Is there any other Windows API which gives time in microseconds which I can use to measure the time consumed by my function?</p>
<p>-AD</p>
| [
{
"answer_id": 49673,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 2,
"selected": false,
"text": "<p>You can try to use <a href=\"http://www.cplusplus.com/reference/clibrary/ctime/clock.html\" rel=\"nofollow noreferrer\">... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49668",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2759376/"
] | I need to find out time taken by a function in my application. Application is a MS VIsual Studio 2005 solution, all C code.
I used thw windows API GetLocalTime(SYSTEMTIME \*) to get the current system time before and after the function call which I want to measure time of.
But this has shortcoming that it lowest resolution is only 1msec. Nothing below that. So I cannot get any time granularity in micro seconds.
I know that time() which gives the time elapsed since the epoch time, also has resolution of 1msec (No microseconds)
1.) Is there any other Windows API which gives time in microseconds which I can use to measure the time consumed by my function?
-AD | There are some other possibilities.
QueryPerformanceCounter and QueryPerformanceFrequency
-----------------------------------------------------
[QueryPerformanceCounter](http://msdn.microsoft.com/en-us/library/ms644904.aspx) will return a "performance counter" which is actually a CPU-managed 64-bit counter that increments from 0 starting with the computer power-on. The frequency of this counter is returned by the [QueryPerformanceFrequency](http://msdn.microsoft.com/en-us/library/ms644905.aspx). To get the time reference in **seconds**, divide performance counter by performance frequency. In Delphi:
```
function QueryPerfCounterAsUS: int64;
begin
if QueryPerformanceCounter(Result) and
QueryPerformanceFrequency(perfFreq)
then
Result := Round(Result / perfFreq * 1000000);
else
Result := 0;
end;
```
On multiprocessor platforms, QueryPerformanceCounter **should** return consistent results regardless of the CPU the thread is currently running on. There are occasional problems, though, usually caused by bugs in hardware chips or BIOSes. Usually, patches are provided by motherboard manufacturers. Two examples from the MSDN:
* [Programs that use the QueryPerformanceCounter function may perform poorly in Windows Server 2003 and in Windows XP](http://support.microsoft.com/kb/895980)
* [Performance counter value may unexpectedly leap forward](http://support.microsoft.com/kb/274323)
Another problem with QueryPerformanceCounter is that it is quite slow.
RDTSC instruction
-----------------
If you can limit your code to one CPU (SetThreadAffinity), you can use [RDTSC](http://en.wikipedia.org/wiki/RDTSC) assembler instruction to query performance counter directly from the processor.
```
function CPUGetTick: int64;
asm
dw 310Fh // rdtsc
end;
```
RDTSC result is incremented with same frequency as QueryPerformanceCounter. Divide it by QueryPerformanceFrequency to get time in seconds.
QueryPerformanceCounter is much slower thatn RDTSC because it must take into account multiple CPUs and CPUs with variable frequency. From [Raymon Chen's blog](http://blogs.msdn.com/oldnewthing/archive/2008/09/08/8931563.aspx):
>
> (QueryPerformanceCounter) counts elapsed time. It has to, since its value is
> governed by the QueryPerformanceFrequency function, which returns a number
> specifying the number of units per second, and the frequency is spec'd as not
> changing while the system is running.
>
>
> For CPUs that can run at variable speed, this means that the HAL cannot
> use an instruction like RDTSC, since that does not correlate with elapsed time.
>
>
>
timeGetTime
-----------
[TimeGetTime](http://msdn.microsoft.com/en-us/library/ms713418.aspx) belongs to the Win32 multimedia Win32 functions. It returns time in milliseconds with 1 ms resolution, at least on a modern hardware. It doesn't hurt if you run timeBeginPeriod(1) before you start measuring time and timeEndPeriod(1) when you're done.
GetLocalTime and GetSystemTime
------------------------------
Before Vista, both [GetLocalTime](http://msdn.microsoft.com/en-us/library/ms713418.aspx) and [GetSystemTime](http://msdn.microsoft.com/en-us/library/ms724390.aspx) return current time with millisecond precision, but they are not accurate to a millisecond. Their accuracy is typically in the range of 10 to 55 milliseconds. ([Precision is not the same as accuracy](http://blogs.msdn.com/oldnewthing/archive/2005/09/02/459952.aspx))
On Vista, GetLocalTime and GetSystemTime both work with 1 ms resolution. |
49,724 | <p>Is it possible to extract all of the VBA code from a Word 2007 "docm" document using the API?</p>
<p>I have found how to insert VBA code at runtime, and how to delete all VBA code, but not pull the actual code out into a stream or string that I can store (and insert into other documents in the future).</p>
<p>Any tips or resources would be appreciated.</p>
<p><strong>Edit</strong>: thanks to everyone, <a href="https://stackoverflow.com/users/3655/aardvark">Aardvark</a>'s answer was exactly what I was looking for. I have converted his code to C#, and was able to call it from a class library using Visual Studio 2008.</p>
<pre><code>using Microsoft.Office.Interop.Word;
using Microsoft.Vbe.Interop;
...
public List<string> GetMacrosFromDoc()
{
Document doc = GetWordDoc(@"C:\Temp\test.docm");
List<string> macros = new List<string>();
VBProject prj;
CodeModule code;
string composedFile;
prj = doc.VBProject;
foreach (VBComponent comp in prj.VBComponents)
{
code = comp.CodeModule;
// Put the name of the code module at the top
composedFile = comp.Name + Environment.NewLine;
// Loop through the (1-indexed) lines
for (int i = 0; i < code.CountOfLines; i++)
{
composedFile += code.get_Lines(i + 1, 1) + Environment.NewLine;
}
// Add the macro to the list
macros.Add(composedFile);
}
CloseDoc(doc);
return macros;
}
</code></pre>
| [
{
"answer_id": 49773,
"author": "Aardvark",
"author_id": 3655,
"author_profile": "https://Stackoverflow.com/users/3655",
"pm_score": 5,
"selected": true,
"text": "<p>You'll have to add a reference to Microsoft Visual Basic for Applications Extensibility 5.3 (or whatever version you have)... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2194/"
] | Is it possible to extract all of the VBA code from a Word 2007 "docm" document using the API?
I have found how to insert VBA code at runtime, and how to delete all VBA code, but not pull the actual code out into a stream or string that I can store (and insert into other documents in the future).
Any tips or resources would be appreciated.
**Edit**: thanks to everyone, [Aardvark](https://stackoverflow.com/users/3655/aardvark)'s answer was exactly what I was looking for. I have converted his code to C#, and was able to call it from a class library using Visual Studio 2008.
```
using Microsoft.Office.Interop.Word;
using Microsoft.Vbe.Interop;
...
public List<string> GetMacrosFromDoc()
{
Document doc = GetWordDoc(@"C:\Temp\test.docm");
List<string> macros = new List<string>();
VBProject prj;
CodeModule code;
string composedFile;
prj = doc.VBProject;
foreach (VBComponent comp in prj.VBComponents)
{
code = comp.CodeModule;
// Put the name of the code module at the top
composedFile = comp.Name + Environment.NewLine;
// Loop through the (1-indexed) lines
for (int i = 0; i < code.CountOfLines; i++)
{
composedFile += code.get_Lines(i + 1, 1) + Environment.NewLine;
}
// Add the macro to the list
macros.Add(composedFile);
}
CloseDoc(doc);
return macros;
}
``` | You'll have to add a reference to Microsoft Visual Basic for Applications Extensibility 5.3 (or whatever version you have). I have the VBA SDK and such on my box - so this may not be exactly what office ships with.
Also you have to enable access to the VBA Object Model specifically - see the "Trust Center" in Word options. This is in addition to all the other Macro security settings Office provides.
This example will extract code from the current document it lives in - it itself is a VBA macro (and will display itself and any other code as well). There is also a Application.vbe.VBProjects collection to access other documents. While I've never done it, I assume an external application could get to open files using this VBProjects collection as well. Security is funny with this stuff so it may be tricky.
I also wonder what the docm file format is now - XML like the docx? Would that be a better approach?
```
Sub GetCode()
Dim prj As VBProject
Dim comp As VBComponent
Dim code As CodeModule
Dim composedFile As String
Dim i As Integer
Set prj = ThisDocument.VBProject
For Each comp In prj.VBComponents
Set code = comp.CodeModule
composedFile = comp.Name & vbNewLine
For i = 1 To code.CountOfLines
composedFile = composedFile & code.Lines(i, 1) & vbNewLine
Next
MsgBox composedFile
Next
End Sub
``` |
49,757 | <p>So if I have a method of parsing a text file and returning a <strong>list</strong> <em>of a</em> <strong>list</strong> <em>of</em> <strong>key value pairs</strong>, and want to create objects from the kvps returned (each list of kvps represents a different object), what would be the best method?</p>
<p>The first method that pops into mind is pretty simple, just keep a list of keywords:</p>
<pre><code>private const string NAME = "name";
private const string PREFIX = "prefix";
</code></pre>
<p>and check against the keys I get for the constants I want, defined above. This is a fairly core piece of the project I'm working on though, so I want to do it well; does anyone have any more robust suggestions (not saying there's anything inherently un-robust about the above method - I'm just asking around)?</p>
<h1>Edit:</h1>
<p>More details have been asked for. I'm working on a little game in my spare time, and I am building up the game world with configuration files. There are four - one defines all creatures, another defines all areas (and their locations in a map), another all objects, and a final one defines various configuration options and things that don't fit else where. With the first three configuration files, I will be creating objects based on the content of the files - it will be quite text-heavy, so there will be a lot of strings, things like names, plurals, prefixes - that sort of thing. The configuration values are all like so:</p>
<pre><code>-
key: value
key: value
-
key: value
key: value
-
</code></pre>
<p>Where the '-' line denotes a new section/object.</p>
| [
{
"answer_id": 49772,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 1,
"selected": false,
"text": "<p>You could create an interface that matched the column names, and then use the Reflection.Emit API to create a type at... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49757",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] | So if I have a method of parsing a text file and returning a **list** *of a* **list** *of* **key value pairs**, and want to create objects from the kvps returned (each list of kvps represents a different object), what would be the best method?
The first method that pops into mind is pretty simple, just keep a list of keywords:
```
private const string NAME = "name";
private const string PREFIX = "prefix";
```
and check against the keys I get for the constants I want, defined above. This is a fairly core piece of the project I'm working on though, so I want to do it well; does anyone have any more robust suggestions (not saying there's anything inherently un-robust about the above method - I'm just asking around)?
Edit:
=====
More details have been asked for. I'm working on a little game in my spare time, and I am building up the game world with configuration files. There are four - one defines all creatures, another defines all areas (and their locations in a map), another all objects, and a final one defines various configuration options and things that don't fit else where. With the first three configuration files, I will be creating objects based on the content of the files - it will be quite text-heavy, so there will be a lot of strings, things like names, plurals, prefixes - that sort of thing. The configuration values are all like so:
```
-
key: value
key: value
-
key: value
key: value
-
```
Where the '-' line denotes a new section/object. | Take a deep look at the [XmlSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx). Even if you are constrained to not use XML on-disk, you might want to copy some of its features. This could then look like this:
```
public class DataObject {
[Column("name")]
public string Name { get; set; }
[Column("prefix")]
public string Prefix { get; set; }
}
```
Be careful though to include some kind of format version in your files, or you will be in hell's kitchen come the next format change. |
49,790 | <p>In my specific example, I'm dealing with a drop-down, e.g.:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="foo" id="bar">
<option disabled="disabled" selected="selected">Select an item:</option>
<option>an item</option>
<option>another item</option>
</select></code></pre>
</div>
</div>
</p>
<p>Of course, that's pretty nonsensical, but I'm wondering whether any strict behaviour is defined. Opera effectively rejects the 'selected' attribute and selects the next item in the list. All other browsers appear to allow it, and it remains selected.</p>
<p><strong>Update:</strong> To clarify, I'm specifically interested in the initial selection. I'm dealing with one of those 'Select an item:'-type drop-downs, in which case the first option is really a label, and an action occurs <code>onchange()</code>. This is <em>fairly</em> well 'progressively enhanced', in that a submit button is present, and only removed via JavaScript. If the "select..." option were removed, whatever then were to become the first item would not be selectable. Are we just ruling out <code>onchange</code> drop downs altogether, or should the "select..." option be selectable, just with no effect?</p>
| [
{
"answer_id": 49802,
"author": "David Heggie",
"author_id": 4309,
"author_profile": "https://Stackoverflow.com/users/4309",
"pm_score": 3,
"selected": false,
"text": "<p>The HTML specs are a bit vague (ie. completely lacking) with regard to this odd combination. They do say that a form ... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5058/"
] | In my specific example, I'm dealing with a drop-down, e.g.:
```html
<select name="foo" id="bar">
<option disabled="disabled" selected="selected">Select an item:</option>
<option>an item</option>
<option>another item</option>
</select>
```
Of course, that's pretty nonsensical, but I'm wondering whether any strict behaviour is defined. Opera effectively rejects the 'selected' attribute and selects the next item in the list. All other browsers appear to allow it, and it remains selected.
**Update:** To clarify, I'm specifically interested in the initial selection. I'm dealing with one of those 'Select an item:'-type drop-downs, in which case the first option is really a label, and an action occurs `onchange()`. This is *fairly* well 'progressively enhanced', in that a submit button is present, and only removed via JavaScript. If the "select..." option were removed, whatever then were to become the first item would not be selectable. Are we just ruling out `onchange` drop downs altogether, or should the "select..." option be selectable, just with no effect? | In reply to the update in the question, I would say that the 'label' option should be selectable but either make it do nothing on submission or via JavaScript, don't allow the form to be submitted without a value being selected (assuming it's a required field).
From a usablilty point of view I'd suggest doing both, that way all bases are covered. |
49,883 | <p>Say I have this given XML file:</p>
<pre><code><root>
<node>x</node>
<node>y</node>
<node>a</node>
</root>
</code></pre>
<p>And I want the following to be displayed:</p>
<pre><code>ayx
</code></pre>
<p>Using something similar to:</p>
<pre><code><xsl:template match="/">
<xsl:apply-templates select="root/node"/>
</xsl:template>
<xsl:template match="node">
<xsl:value-of select="."/>
</xsl:template>
</code></pre>
| [
{
"answer_id": 49887,
"author": "Pierre Spring",
"author_id": 1532,
"author_profile": "https://Stackoverflow.com/users/1532",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this, using <code>xsl:sort</code>. It is important to set the <code>data-type=\"number\"</code> because e... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1532/"
] | Say I have this given XML file:
```
<root>
<node>x</node>
<node>y</node>
<node>a</node>
</root>
```
And I want the following to be displayed:
```
ayx
```
Using something similar to:
```
<xsl:template match="/">
<xsl:apply-templates select="root/node"/>
</xsl:template>
<xsl:template match="node">
<xsl:value-of select="."/>
</xsl:template>
``` | Easy!
```
<xsl:template match="/">
<xsl:apply-templates select="root/node">
<xsl:sort select="position()" data-type="number" order="descending"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="node">
<xsl:value-of select="."/>
</xsl:template>
``` |
49,890 | <p>I created a few mediawiki custom tags, using the guide found here</p>
<p><a href="http://www.mediawiki.org/wiki/Manual:Tag_extensions" rel="nofollow noreferrer">http://www.mediawiki.org/wiki/Manual:Tag_extensions</a></p>
<p>I will post my code below, but the problem is after it hits the first custom tag in the page, it calls it, and prints the response, but does not get anything that comes after it in the wikitext. It seems it just stops parsing the page.</p>
<p>Any Ideas?</p>
<pre><code>if ( defined( 'MW_SUPPORTS_PARSERFIRSTCALLINIT' ) ) {
$wgHooks['ParserFirstCallInit'][] = 'tagregister';
} else { // Otherwise do things the old fashioned way
$wgExtensionFunctions[] = 'tagregister';
}
function tagregister(){
global $wgParser;
$wgParser->setHook('tag1','tag1func');
$wgParser->setHook('tag2','tag2func');
return true;
}
function tag1func($input,$params)
{
return "It called me";
}
function tag2func($input,$params)
{
return "It called me -- 2";
}
</code></pre>
<p>Update: @George Mauer -- I have seen that as well, but this does not stop the page from rendering, just the Mediawiki engine from parsing the rest of the wikitext. Its as if hitting the custom function is signaling mediawiki that processing is done. I am in the process of diving into the rabbit hole but was hoping someone else has seen this behavior.</p>
| [
{
"answer_id": 49887,
"author": "Pierre Spring",
"author_id": 1532,
"author_profile": "https://Stackoverflow.com/users/1532",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this, using <code>xsl:sort</code>. It is important to set the <code>data-type=\"number\"</code> because e... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/673/"
] | I created a few mediawiki custom tags, using the guide found here
<http://www.mediawiki.org/wiki/Manual:Tag_extensions>
I will post my code below, but the problem is after it hits the first custom tag in the page, it calls it, and prints the response, but does not get anything that comes after it in the wikitext. It seems it just stops parsing the page.
Any Ideas?
```
if ( defined( 'MW_SUPPORTS_PARSERFIRSTCALLINIT' ) ) {
$wgHooks['ParserFirstCallInit'][] = 'tagregister';
} else { // Otherwise do things the old fashioned way
$wgExtensionFunctions[] = 'tagregister';
}
function tagregister(){
global $wgParser;
$wgParser->setHook('tag1','tag1func');
$wgParser->setHook('tag2','tag2func');
return true;
}
function tag1func($input,$params)
{
return "It called me";
}
function tag2func($input,$params)
{
return "It called me -- 2";
}
```
Update: @George Mauer -- I have seen that as well, but this does not stop the page from rendering, just the Mediawiki engine from parsing the rest of the wikitext. Its as if hitting the custom function is signaling mediawiki that processing is done. I am in the process of diving into the rabbit hole but was hoping someone else has seen this behavior. | Easy!
```
<xsl:template match="/">
<xsl:apply-templates select="root/node">
<xsl:sort select="position()" data-type="number" order="descending"/>
</xsl:apply-templates>
</xsl:template>
<xsl:template match="node">
<xsl:value-of select="."/>
</xsl:template>
``` |
49,896 | <p>When connecting to remote hosts via ssh, I frequently want to bring a file on that system to the local system for viewing or processing. Is there a way to copy the file over without (a) opening a new terminal/pausing the ssh session (b) authenticating again to either the local or remote hosts which works (c) even when one or both of the hosts is behind a NAT router?</p>
<p>The goal is to take advantage of as much of the current state as possible: that there is a connection between the two machines, that I'm authenticated on both, that I'm in the working directory of the file---so I don't have to open another terminal and copy and paste the remote host and path in, which is what I do now. The best solution also wouldn't require any setup before the session began, but if the setup was a one-time or able to be automated, than that's perfectly acceptable. </p>
| [
{
"answer_id": 49913,
"author": "chris",
"author_id": 4782,
"author_profile": "https://Stackoverflow.com/users/4782",
"pm_score": -1,
"selected": false,
"text": "<p>You should be able to set up public & private keys so that no auth is needed. </p>\n\n<p>Which way you do it depends on... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5222/"
] | When connecting to remote hosts via ssh, I frequently want to bring a file on that system to the local system for viewing or processing. Is there a way to copy the file over without (a) opening a new terminal/pausing the ssh session (b) authenticating again to either the local or remote hosts which works (c) even when one or both of the hosts is behind a NAT router?
The goal is to take advantage of as much of the current state as possible: that there is a connection between the two machines, that I'm authenticated on both, that I'm in the working directory of the file---so I don't have to open another terminal and copy and paste the remote host and path in, which is what I do now. The best solution also wouldn't require any setup before the session began, but if the setup was a one-time or able to be automated, than that's perfectly acceptable. | Here is my preferred solution to this problem. Set up a reverse ssh tunnel upon creating the ssh session. This is made easy by two bash function: grabfrom() needs to be defined on the local host, while grab() should be defined on the remote host. You can add any other ssh variables you use (e.g. -X or -Y) as you see fit.
```
function grabfrom() { ssh -R 2202:127.0.0.1:22 ${@}; };
function grab() { scp -P 2202 $@ localuser@127.0.0.1:~; };
```
Usage:
```
localhost% grabfrom remoteuser@remotehost
password: <remote password goes here>
remotehost% grab somefile1 somefile2 *.txt
password: <local password goes here>
```
Positives:
* It works without special software on either host beyond OpenSSH
* It works when local host is behind a NAT router
* It can be implemented as a pair of two one-line bash function
Negatives:
* It uses a fixed port number so:
+ won't work with multiple connections to remote host
+ might conflict with a process using that port on the remote host
* It requires localhost accept ssh connections
* It requires a special command on initiation the session
* It doesn't implicitly handle authentication to the localhost
* It doesn't allow one to specify the destination directory on localhost
* If you grab from multiple localhosts to the same remote host, ssh won't like the keys changing
Future work:
This is still pretty kludgy. Obviously, it would be possible to handle the authentication issue by setting up ssh keys appropriately and it's even easier to allow the specification of a remote directory by adding a parameter to grab()
More difficult is addressing the other negatives. It would be nice to pick a dynamic port but as far as I can tell there is no elegant way to pass that port to the shell on the remote host; As best as I can tell, OpenSSH doesn't allow you to set arbitrary environment variables on the remote host and bash can't take environment variables from a command line argument. Even if you could pick a dynamic port, there is no way to ensure it isn't used on the remote host without connecting first. |
49,900 | <p>We have an Apache ANT script to build our application, then check in the resulting JAR file into version control (VSS in this case). However, now we have a change that requires us to build 2 JAR files for this project, then check both into VSS.</p>
<p>The current target that checks the original JAR file into VSS discovers the name of the JAR file through some property. Is there an easy way to "generalize" this target so that I can reuse it to check in a JAR file with any name? In a normal language this would obviously call for a function parameter but, to my knowledge, there really isn't an equivalent concept in ANT.</p>
| [
{
"answer_id": 49920,
"author": "Chris Dail",
"author_id": 5077,
"author_profile": "https://Stackoverflow.com/users/5077",
"pm_score": 4,
"selected": false,
"text": "<p>It is generally considered a bad idea to version control your binaries and I do not recommend doing so. But if you abso... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1471/"
] | We have an Apache ANT script to build our application, then check in the resulting JAR file into version control (VSS in this case). However, now we have a change that requires us to build 2 JAR files for this project, then check both into VSS.
The current target that checks the original JAR file into VSS discovers the name of the JAR file through some property. Is there an easy way to "generalize" this target so that I can reuse it to check in a JAR file with any name? In a normal language this would obviously call for a function parameter but, to my knowledge, there really isn't an equivalent concept in ANT. | I would suggest to work with [macros](http://ant.apache.org/manual/Tasks/macrodef.html) over subant/antcall because the main advantage I found with macros is that you're in complete control over the properties that are passed to the macro (especially if you want to add new properties).
You simply refactor your Ant script starting with your target:
```
<target name="vss.check">
<vssadd localpath="D:\build\build.00012.zip"
comment="Added by automatic build"/>
</target>
```
creating a macro (notice the copy/paste and replacement with the @{file}):
```
<macrodef name="private-vssadd">
<attribute name="file"/>
<sequential>
<vssadd localpath="@{file}"
comment="Added by automatic build"/>
</sequential>
</macrodef>
```
and invoke the macros with your files:
```
<target name="vss.check">
<private-vssadd file="D:\build\File1.zip"/>
<private-vssadd file="D:\build\File2.zip"/>
</target>
```
Refactoring, "the Ant way" |
49,908 | <p>I know I've seen this in the past, but I can't seem to find it now.</p>
<p>Basically I want to create a page that I can host on a <a href="http://www.codeplex.com/dasblog" rel="nofollow noreferrer">dasBlog</a> instance that contains the layout from my theme, but the content of the page I control.</p>
<p>Ideally the content is a user control or ASPX that I write. Anybody know how I can accomplish this?</p>
| [
{
"answer_id": 49973,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>I did something similar setting up a handler to stream video files from the blog on my home server. I ended up ditc... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3381/"
] | I know I've seen this in the past, but I can't seem to find it now.
Basically I want to create a page that I can host on a [dasBlog](http://www.codeplex.com/dasblog) instance that contains the layout from my theme, but the content of the page I control.
Ideally the content is a user control or ASPX that I write. Anybody know how I can accomplish this? | The easist way to do this is to "hijack" the FormatPage functionality.
First add the following to your web.config in the newtelligence.DasBlog.UrlMapper section:
```
<add matchExpression="(?<basedir>.*?)/Static\.aspx\?=(?<value>.+)" mapTo="{basedir}/FormatPage.aspx?path=content/static/{value}.format.html" />
```
Now you can create a directory in your content directory called static. From there, you can create html files and the file name will map to the url like this:
<http://BASEURL/Static.aspx?=FILENAME>
will map to a file called:
/content/static/FILENAME.format.html
You can place anything in that file that you would normally place in itemTemplate.blogtemplate, except it obviously won't have any post data. But you can essentially use this to put other macros, and still have it use the hometemplate.blogtemplate to keep the rest of your theme wrapped around the page. |
49,919 | <p>I am looking for a Regular expression to match only if a date is in the first 28 days of the month. This is for my validator control in ASP.NET</p>
| [
{
"answer_id": 49923,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think this is a task very well-suited for a regexp.</p>\n\n<p>I'd try and use the library functions (DateTime.Parse ... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] | I am looking for a Regular expression to match only if a date is in the first 28 days of the month. This is for my validator control in ASP.NET | Don't do this with Regex. Dates are formatted differently in different countries. Use the DateTime.TryParse routine instead:
```
DateTime parsedDate;
if ( DateTime.TryParse( dateString, out parsedDate) && parsedDate.Day <= 28 )
{
// logic goes here.
}
```
Regex is nearly the [golden hammer](http://en.wikipedia.org/wiki/Golden_hammer) of input validation, but in this instance, it's the wrong choice. |
49,925 | <p>What is the difference between <code>UNION</code> and <code>UNION ALL</code>?</p>
| [
{
"answer_id": 49927,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 5,
"selected": false,
"text": "<blockquote>\n <p>The basic difference between UNION and UNION ALL is union operation eliminates the duplicated rows fr... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3208/"
] | What is the difference between `UNION` and `UNION ALL`? | `UNION` removes duplicate records (where all columns in the results are the same), `UNION ALL` does not.
There is a performance hit when using `UNION` instead of `UNION ALL`, since the database server must do additional work to remove the duplicate rows, but usually you do not want the duplicates (especially when developing reports).
To identify duplicates, records must be comparable types as well as compatible types. This will depend on the SQL system. For example the system may truncate all long text fields to make short text fields for comparison (MS Jet), or may refuse to compare binary fields (ORACLE)
### UNION Example:
```
SELECT 'foo' AS bar UNION SELECT 'foo' AS bar
```
**Result:**
```
+-----+
| bar |
+-----+
| foo |
+-----+
1 row in set (0.00 sec)
```
### UNION ALL example:
```
SELECT 'foo' AS bar UNION ALL SELECT 'foo' AS bar
```
**Result:**
```
+-----+
| bar |
+-----+
| foo |
| foo |
+-----+
2 rows in set (0.00 sec)
``` |
49,934 | <p>On my OS X box, the kernel is a 32-bit binary and yet it can run a 64-bit binary.
How does this work?</p>
<pre><code>cristi:~ diciu$ file ./a.out
./a.out: Mach-O 64-bit executable x86_64
cristi:~ diciu$ file /mach_kernel
/mach_kernel: Mach-O universal binary with 2 architectures
/mach_kernel (for architecture i386): Mach-O executable i386
/mach_kernel (for architecture ppc): Mach-O executable ppc
cristi:~ diciu$ ./a.out
cristi:~ diciu$ echo $?
1
</code></pre>
| [
{
"answer_id": 49939,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 3,
"selected": false,
"text": "<p>It's not the kernel that runs the binary. It's the processor.</p>\n\n<p>The binary does call library functions and those nee... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2811/"
] | On my OS X box, the kernel is a 32-bit binary and yet it can run a 64-bit binary.
How does this work?
```
cristi:~ diciu$ file ./a.out
./a.out: Mach-O 64-bit executable x86_64
cristi:~ diciu$ file /mach_kernel
/mach_kernel: Mach-O universal binary with 2 architectures
/mach_kernel (for architecture i386): Mach-O executable i386
/mach_kernel (for architecture ppc): Mach-O executable ppc
cristi:~ diciu$ ./a.out
cristi:~ diciu$ echo $?
1
``` | The CPU can be switched from 64 bit execution mode to 32 bit when it traps into kernel context, and a 32 bit kernel can still be constructed to understand the structures passed in from 64 bit user-space apps.
The MacOS X kernel does not directly dereference pointers from the user app anyway, as it resides its own separate address space. A user-space pointer in an ioctl call, for example, must first be resolved to its physical address and then a new virtual address created in the kernel address space. It doesn't really matter whether that pointer in the ioctl was 64 bits or 32 bits, the kernel does not dereference it directly in either case.
So mixing a 32 bit kernel and 64 bit binaries can work, and vice-versa. The thing you cannot do is mix 32 bit libraries with a 64 bit application, as pointers passed between them would be truncated. MacOS X supplies more of its frameworks in both 32 and 64 bit versions in each release. |
49,962 | <p>Had an interesting discussion with some colleagues about the best scheduling strategies for realtime tasks, but not everyone had a good understanding of the common or useful scheduling strategies.</p>
<p>For your answer, please choose one strategy and go over it in some detail, rather than giving a little info on several strategies. If you have something to add to someone else's description and it's short, add a comment rather than a new answer (if it's long or useful, or simply a much better description, then please use an answer)</p>
<ul>
<li>What is the strategy - describe the general case (assume people know what a task queue is, semaphores, locks, and other OS fundamentals outside the scheduler itself)</li>
<li>What is this strategy optimized for (task latency, efficiency, realtime, jitter, resource sharing, etc)</li>
<li>Is it realtime, or can it be made realtime</li>
</ul>
<p>Current strategies:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/49962/task-schedulers#74894">Priority Based Preemptive</a></li>
<li><a href="https://stackoverflow.com/questions/49962/task-schedulers#50056">Lowest power slowest clock</a></li>
</ul>
<p>-Adam</p>
| [
{
"answer_id": 50056,
"author": "Sean",
"author_id": 4919,
"author_profile": "https://Stackoverflow.com/users/4919",
"pm_score": 4,
"selected": true,
"text": "<p>As described in a paper titled <a href=\"http://www.ee.duke.edu/~krish/wip.pdf\" rel=\"noreferrer\">Real-Time Task Scheduling ... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49962",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2915/"
] | Had an interesting discussion with some colleagues about the best scheduling strategies for realtime tasks, but not everyone had a good understanding of the common or useful scheduling strategies.
For your answer, please choose one strategy and go over it in some detail, rather than giving a little info on several strategies. If you have something to add to someone else's description and it's short, add a comment rather than a new answer (if it's long or useful, or simply a much better description, then please use an answer)
* What is the strategy - describe the general case (assume people know what a task queue is, semaphores, locks, and other OS fundamentals outside the scheduler itself)
* What is this strategy optimized for (task latency, efficiency, realtime, jitter, resource sharing, etc)
* Is it realtime, or can it be made realtime
Current strategies:
* [Priority Based Preemptive](https://stackoverflow.com/questions/49962/task-schedulers#74894)
* [Lowest power slowest clock](https://stackoverflow.com/questions/49962/task-schedulers#50056)
-Adam | As described in a paper titled [Real-Time Task Scheduling for Energy-Aware Embedded Systems](http://www.ee.duke.edu/~krish/wip.pdf), Swaminathan and Chakrabarty describe the challenges of real-time task scheduling in low-power (embedded) devices with multiple processor speeds and power consumption profiles available. The scheduling algorithm they outline (and is shown to be only about 1% worse than an optimal solution in tests) has an interesting way of scheduling tasks they call the LEDF Heuristic.
From the paper:
>
> *The low-energy earliest deadline first
> heuristic, or simply LEDF, is an
> extension of the well-known earliest
> deadline first (EDF) algorithm. The
> operation of LEDF is as follows: LEDF
> maintains a list of all released
> tasks, called the “ready list”. When
> tasks are released, the task with the
> nearest deadline is chosen to be
> executed. A check is performed to see
> if the task deadline can be met by
> executing it at the lower voltage
> (speed). If the deadline can be met,
> LEDF assigns the lower voltage to the
> task and the task begins execution.
> During the task’s execution, other
> tasks may enter the system. These
> tasks are assumed to be placed
> automatically on the “ready list”.
> LEDF again selects the task with the
> nearest deadline to be executed. As
> long as there are tasks waiting to be
> executed, LEDF does not keep the pro-
> cessor idle. This process is repeated
> until all the tasks have been
> scheduled.*
>
>
>
And in pseudo-code:
```
Repeat forever {
if tasks are waiting to be scheduled {
Sort deadlines in ascending order
Schedule task with earliest deadline
Check if deadline can be met at lower speed (voltage)
If deadline can be met,
schedule task to execute at lower voltage (speed)
If deadline cannot be met,
check if deadline can be met at higher speed (voltage)
If deadline can be met,
schedule task to execute at higher voltage (speed)
If deadline cannot be met,
task cannot be scheduled: run the exception handler!
}
}
```
It seems that real-time scheduling is an interesting and evolving problem as small, low-power devices become more ubiquitous. I think this is an area in which we'll see plenty of further research and I look forward to keeping abreast! |
49,966 | <p>When I turn an image (<code><img></code>) into a hyperlink (by wrapping it in <code><a></code>), Firefox adds a black border around the image. Safari does not display the same border. </p>
<p>What CSS declaration would be best to eliminate the border?</p>
| [
{
"answer_id": 49975,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 2,
"selected": false,
"text": "<pre><code>a img {\n border-width: 0;\n}\n</code></pre>\n"
},
{
"answer_id": 49977,
"author": "pilif",
... | 2008/09/08 | [
"https://Stackoverflow.com/questions/49966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4540/"
] | When I turn an image (`<img>`) into a hyperlink (by wrapping it in `<a>`), Firefox adds a black border around the image. Safari does not display the same border.
What CSS declaration would be best to eliminate the border? | ```
img {
border: 0
}
```
Or old-fashioned:
```
<img border="0" src="..." />
^^^^^^^^^^
``` |
50,005 | <p>I have a weird bug involving Flash text and hyperlinks, htmlText in a TextField with <code><a></code> tags seem to truncate surrounding space:</p>
<p><a href="https://i.stack.imgur.com/FDA7a.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FDA7a.gif" alt="output"></a></p>
<p>Once I place my cursor over the text, it "fixes" itself:</p>
<p><a href="https://i.stack.imgur.com/YFbSR.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YFbSR.gif" alt="output with mouseover"></a></p>
<p>Here is the HTML in the textField:</p>
<pre><code><p>The speeches at both the <a href="http://www.demconvention.com/speeches/" target="_blank">Democratic National Convention</a> last week and the <a href="http://www.gopconvention2008.com/videos" target="_blank">Republican National Convention</a> this week, have been, for me at least, must see TV.</p>
</code></pre>
<p>When I disable the styleSheet attached to it, the effect still occurs, but placing my mouse over it does not fix the spacing. I am using "Anti-alias for readability", and have embedded the all Uppercase, Lowercase, Numerals, and Punctuation. I will also point out that if I change the rendering setting to "Use Device fonts" the bug goes away.</p>
<p>Any thoughts?</p>
| [
{
"answer_id": 51590,
"author": "Jon Cram",
"author_id": 5343,
"author_profile": "https://Stackoverflow.com/users/5343",
"pm_score": 0,
"selected": false,
"text": "<p>Does it make any difference if you put non-breaking spaces immediately before and after the anchor element?</p>\n\n<pre><... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1306/"
] | I have a weird bug involving Flash text and hyperlinks, htmlText in a TextField with `<a>` tags seem to truncate surrounding space:
[](https://i.stack.imgur.com/FDA7a.gif)
Once I place my cursor over the text, it "fixes" itself:
[](https://i.stack.imgur.com/YFbSR.gif)
Here is the HTML in the textField:
```
<p>The speeches at both the <a href="http://www.demconvention.com/speeches/" target="_blank">Democratic National Convention</a> last week and the <a href="http://www.gopconvention2008.com/videos" target="_blank">Republican National Convention</a> this week, have been, for me at least, must see TV.</p>
```
When I disable the styleSheet attached to it, the effect still occurs, but placing my mouse over it does not fix the spacing. I am using "Anti-alias for readability", and have embedded the all Uppercase, Lowercase, Numerals, and Punctuation. I will also point out that if I change the rendering setting to "Use Device fonts" the bug goes away.
Any thoughts? | Make sure you styleSheet declares what it is supposed to do with Anchors. You are obviously using htmlText if your using CSS so soon as it sees < in front of "a href" it immedietly looks for the CSS class definition for a and when it doesn't find one, the result is the different looking text you see.
Add the following to your CSS and make sure that it has the same settings as the regular style of your text as far as style, wieght, and size. The only thing that should differ is the color.
```
a:link
{
font-family: sameAsReg;
font-size: 12px; //Note flash omits things like px and pt.
color:#FF0000; //Red
}
```
Be sure that the fonts you are embedding are in the library and being instantiated into your code. Embedding each textfield through the UI is silly when you can merely load the font from the library at runtime and then you can use it anywhere.
You can also import multiple fonts at compile time and use them in the same textfield with the use of < class span="someCSSClass">Some Text < /span>< class span="someOtherCSSClass">Some Other Text < /span>
Good luck and I hope this helps. |
50,033 | <p>The .Net generated code for a form with the "DefaultButton" attribute set contains poor javascript that allows the functionality to work in IE but not in other browsers (Firefox specifcially). </p>
<p>Hitting enter key does submit the form with all browsers but Firefox cannot disregard the key press when it happens inside of a <textarea> control. The result is a multiline text area control that cannot be multiline in Firefox as the enter key submits the form instead of creating a new line. </p>
<p>For more information on the bug, <a href="http://www.velocityreviews.com/forums/t367383-formdefaultbutton-behaves-incorrectly.html" rel="noreferrer">read it here</a>.</p>
<p>This could be fixed in Asp.Net 3.0+ but a workaround still has to be created for 2.0. </p>
<p>Any ideas for the lightest workaround (a hack that doesn't look like a hack =D)? The solution in the above link scares me a little as it could easily have unintended side-effects.</p>
| [
{
"answer_id": 50039,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 1,
"selected": false,
"text": "<p>For this particular issue, the reason is because javascript generated by \nASP.NET 2.0 has some IE only notation: event.srcEl... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3617/"
] | The .Net generated code for a form with the "DefaultButton" attribute set contains poor javascript that allows the functionality to work in IE but not in other browsers (Firefox specifcially).
Hitting enter key does submit the form with all browsers but Firefox cannot disregard the key press when it happens inside of a <textarea> control. The result is a multiline text area control that cannot be multiline in Firefox as the enter key submits the form instead of creating a new line.
For more information on the bug, [read it here](http://www.velocityreviews.com/forums/t367383-formdefaultbutton-behaves-incorrectly.html).
This could be fixed in Asp.Net 3.0+ but a workaround still has to be created for 2.0.
Any ideas for the lightest workaround (a hack that doesn't look like a hack =D)? The solution in the above link scares me a little as it could easily have unintended side-effects. | I use this function adapted from codesta. [Edit: the very same one, I see, that scares you! Oops. Can't help you then.]
<http://blog.codesta.com/codesta_weblog/2007/12/net-gotchas---p.html>.
You use it by surrounding your code with a div like so. You could subclass the Form to include this automatically. I don't use it that much, so I didn't.
```
<div onkeypress="return FireDefaultButton(event, '<%= aspButtonID.ClientID %>')">
(your form goes here)
</div>
```
Here's the function.
```
function FireDefaultButton(event, target)
{
// srcElement is for IE
var element = event.target || event.srcElement;
if (13 == event.keyCode && !(element && "textarea" == element.tagName.toLowerCase()))
{
var defaultButton;
defaultButton = document.getElementById(target);
if (defaultButton && "undefined" != typeof defaultButton.click)
{
defaultButton.click();
event.cancelBubble = true;
if (event.stopPropagation)
event.stopPropagation();
return false;
}
}
return true;
}
``` |
50,064 | <p>This is pretty simple, I come from a swing/awt background.</p>
<p>I'm just wondering what the proper way to set the background color for a SWT widget is?</p>
<p>I've been trying:</p>
<pre><code>widget.setBackground( );
</code></pre>
<p>Except I have no idea how to create the color Object in SWT?</p>
| [
{
"answer_id": 50128,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 7,
"selected": true,
"text": "<p>To create a color, try this:</p>\n\n<pre><code>Device device = Display.getCurrent ();\nColor red = new Color (device, 255... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3415/"
] | This is pretty simple, I come from a swing/awt background.
I'm just wondering what the proper way to set the background color for a SWT widget is?
I've been trying:
```
widget.setBackground( );
```
Except I have no idea how to create the color Object in SWT? | To create a color, try this:
```
Device device = Display.getCurrent ();
Color red = new Color (device, 255, 0, 0);
``` |
50,097 | <p>I would like to use an add-in like simple-modal or the dialog add-in in the UI kit. However, how do I use these or any other and get a result back. Basically I want the modal to do some AJAX interaction with the server and return the result for the calling code to do some stuff with.</p>
| [
{
"answer_id": 50104,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 0,
"selected": false,
"text": "<p>Since the modal dialog is on the page, you're free to set any document variable you want. However all of the modal ... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5236/"
] | I would like to use an add-in like simple-modal or the dialog add-in in the UI kit. However, how do I use these or any other and get a result back. Basically I want the modal to do some AJAX interaction with the server and return the result for the calling code to do some stuff with. | Here is how the confirm window works on simpleModal:
```
$(document).ready(function () {
$('#confirmDialog input:eq(0)').click(function (e) {
e.preventDefault();
// example of calling the confirm function
// you must use a callback function to perform the "yes" action
confirm("Continue to the SimpleModal Project page?", function () {
window.location.href = 'http://www.ericmmartin.com/projects/simplemodal/';
});
});
});
function confirm(message, callback) {
$('#confirm').modal({
close: false,
overlayId: 'confirmModalOverlay',
containerId: 'confirmModalContainer',
onShow: function (dialog) {
dialog.data.find('.message').append(message);
// if the user clicks "yes"
dialog.data.find('.yes').click(function () {
// call the callback
if ($.isFunction(callback)) {
callback.apply();
}
// close the dialog
$.modal.close();
});
}
});
}
``` |
50,098 | <p>I would like to compare two collections (in C#), but I'm not sure of the best way to implement this efficiently.</p>
<p>I've read the other thread about <a href="https://stackoverflow.com/questions/43500/is-there-a-built-in-method-to-compare-collections-in-c">Enumerable.SequenceEqual</a>, but it's not exactly what I'm looking for.</p>
<p>In my case, two collections would be equal if they both contain the same items (no matter the order).</p>
<p>Example:</p>
<pre><code>collection1 = {1, 2, 3, 4};
collection2 = {2, 4, 1, 3};
collection1 == collection2; // true
</code></pre>
<p>What I usually do is to loop through each item of one collection and see if it exists in the other collection, then loop through each item of the other collection and see if it exists in the first collection. (I start by comparing the lengths).</p>
<pre><code>if (collection1.Count != collection2.Count)
return false; // the collections are not equal
foreach (Item item in collection1)
{
if (!collection2.Contains(item))
return false; // the collections are not equal
}
foreach (Item item in collection2)
{
if (!collection1.Contains(item))
return false; // the collections are not equal
}
return true; // the collections are equal
</code></pre>
<p>However, this is not entirely correct, and it's probably not the most efficient way to do compare two collections for equality.</p>
<p>An example I can think of that would be wrong is:</p>
<pre><code>collection1 = {1, 2, 3, 3, 4}
collection2 = {1, 2, 2, 3, 4}
</code></pre>
<p>Which would be equal with my implementation. Should I just count the number of times each item is found and make sure the counts are equal in both collections?</p>
<hr>
<p>The examples are in some sort of C# (let's call it pseudo-C#), but give your answer in whatever language you wish, it does not matter.</p>
<p><strong>Note:</strong> I used integers in the examples for simplicity, but I want to be able to use reference-type objects too (they do not behave correctly as keys because only the reference of the object is compared, not the content).</p>
| [
{
"answer_id": 50154,
"author": "Daniel Jennings",
"author_id": 3641,
"author_profile": "https://Stackoverflow.com/users/3641",
"pm_score": 5,
"selected": false,
"text": "<p>Create a Dictionary \"dict\" and then for each member in the first collection, do dict[member]++;</p>\n\n<p>Then, ... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50098",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/810/"
] | I would like to compare two collections (in C#), but I'm not sure of the best way to implement this efficiently.
I've read the other thread about [Enumerable.SequenceEqual](https://stackoverflow.com/questions/43500/is-there-a-built-in-method-to-compare-collections-in-c), but it's not exactly what I'm looking for.
In my case, two collections would be equal if they both contain the same items (no matter the order).
Example:
```
collection1 = {1, 2, 3, 4};
collection2 = {2, 4, 1, 3};
collection1 == collection2; // true
```
What I usually do is to loop through each item of one collection and see if it exists in the other collection, then loop through each item of the other collection and see if it exists in the first collection. (I start by comparing the lengths).
```
if (collection1.Count != collection2.Count)
return false; // the collections are not equal
foreach (Item item in collection1)
{
if (!collection2.Contains(item))
return false; // the collections are not equal
}
foreach (Item item in collection2)
{
if (!collection1.Contains(item))
return false; // the collections are not equal
}
return true; // the collections are equal
```
However, this is not entirely correct, and it's probably not the most efficient way to do compare two collections for equality.
An example I can think of that would be wrong is:
```
collection1 = {1, 2, 3, 3, 4}
collection2 = {1, 2, 2, 3, 4}
```
Which would be equal with my implementation. Should I just count the number of times each item is found and make sure the counts are equal in both collections?
---
The examples are in some sort of C# (let's call it pseudo-C#), but give your answer in whatever language you wish, it does not matter.
**Note:** I used integers in the examples for simplicity, but I want to be able to use reference-type objects too (they do not behave correctly as keys because only the reference of the object is compared, not the content). | It turns out Microsoft already has this covered in its testing framework: [CollectionAssert.AreEquivalent](http://msdn.microsoft.com/en-us/library/ms243779.aspx)
>
> Remarks
>
>
> Two collections are equivalent if they
> have the same elements in the same
> quantity, but in any order. Elements
> are equal if their values are equal,
> not if they refer to the same object.
>
>
>
Using reflector, I modified the code behind AreEquivalent() to create a corresponding equality comparer. It is more complete than existing answers, since it takes nulls into account, implements IEqualityComparer and has some efficiency and edge case checks. plus, it's *Microsoft* :)
```
public class MultiSetComparer<T> : IEqualityComparer<IEnumerable<T>>
{
private readonly IEqualityComparer<T> m_comparer;
public MultiSetComparer(IEqualityComparer<T> comparer = null)
{
m_comparer = comparer ?? EqualityComparer<T>.Default;
}
public bool Equals(IEnumerable<T> first, IEnumerable<T> second)
{
if (first == null)
return second == null;
if (second == null)
return false;
if (ReferenceEquals(first, second))
return true;
if (first is ICollection<T> firstCollection && second is ICollection<T> secondCollection)
{
if (firstCollection.Count != secondCollection.Count)
return false;
if (firstCollection.Count == 0)
return true;
}
return !HaveMismatchedElement(first, second);
}
private bool HaveMismatchedElement(IEnumerable<T> first, IEnumerable<T> second)
{
int firstNullCount;
int secondNullCount;
var firstElementCounts = GetElementCounts(first, out firstNullCount);
var secondElementCounts = GetElementCounts(second, out secondNullCount);
if (firstNullCount != secondNullCount || firstElementCounts.Count != secondElementCounts.Count)
return true;
foreach (var kvp in firstElementCounts)
{
var firstElementCount = kvp.Value;
int secondElementCount;
secondElementCounts.TryGetValue(kvp.Key, out secondElementCount);
if (firstElementCount != secondElementCount)
return true;
}
return false;
}
private Dictionary<T, int> GetElementCounts(IEnumerable<T> enumerable, out int nullCount)
{
var dictionary = new Dictionary<T, int>(m_comparer);
nullCount = 0;
foreach (T element in enumerable)
{
if (element == null)
{
nullCount++;
}
else
{
int num;
dictionary.TryGetValue(element, out num);
num++;
dictionary[element] = num;
}
}
return dictionary;
}
public int GetHashCode(IEnumerable<T> enumerable)
{
if (enumerable == null) throw new
ArgumentNullException(nameof(enumerable));
int hash = 17;
foreach (T val in enumerable)
hash ^= (val == null ? 42 : m_comparer.GetHashCode(val));
return hash;
}
}
```
Sample usage:
```
var set = new HashSet<IEnumerable<int>>(new[] {new[]{1,2,3}}, new MultiSetComparer<int>());
Console.WriteLine(set.Contains(new [] {3,2,1})); //true
Console.WriteLine(set.Contains(new [] {1, 2, 3, 3})); //false
```
Or if you just want to compare two collections directly:
```
var comp = new MultiSetComparer<string>();
Console.WriteLine(comp.Equals(new[] {"a","b","c"}, new[] {"a","c","b"})); //true
Console.WriteLine(comp.Equals(new[] {"a","b","c"}, new[] {"a","b"})); //false
```
Finally, you can use your an equality comparer of your choice:
```
var strcomp = new MultiSetComparer<string>(StringComparer.OrdinalIgnoreCase);
Console.WriteLine(strcomp.Equals(new[] {"a", "b"}, new []{"B", "A"})); //true
``` |
50,115 | <p>So my site uses <a href="http://mjijackson.com/shadowbox/" rel="nofollow noreferrer">shadowbox</a> to do display some dynamic text. Problem is I need the user to be able to copy and paste that text. </p>
<p>Right-clicking and selecting copy works but <kbd>Ctrl</kbd>+<kbd>C</kbd> doesn't (no keyboard shortcuts do) and most people use <kbd>Ctrl</kbd>+<kbd>C</kbd>? You can see an example of what I'm talking about <a href="http://mjijackson.com/shadowbox/" rel="nofollow noreferrer">here</a>. </p>
<p>Just go to the "web" examples and click "inline". Notice keyboard shortcuts do work on the "this page" example. The only difference between the two I see is the player js files they use. "Inline" uses the html.js player and "this page" uses iframe.js. Also, I believe it uses the mootools library. Any ideas?</p>
| [
{
"answer_id": 58063,
"author": "Robby Slaughter",
"author_id": 1854,
"author_profile": "https://Stackoverflow.com/users/1854",
"pm_score": 1,
"selected": false,
"text": "<p>This problem is caused by some JavaScript which eats keyboard events. You can hit the escape key, for example, whi... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5234/"
] | So my site uses [shadowbox](http://mjijackson.com/shadowbox/) to do display some dynamic text. Problem is I need the user to be able to copy and paste that text.
Right-clicking and selecting copy works but `Ctrl`+`C` doesn't (no keyboard shortcuts do) and most people use `Ctrl`+`C`? You can see an example of what I'm talking about [here](http://mjijackson.com/shadowbox/).
Just go to the "web" examples and click "inline". Notice keyboard shortcuts do work on the "this page" example. The only difference between the two I see is the player js files they use. "Inline" uses the html.js player and "this page" uses iframe.js. Also, I believe it uses the mootools library. Any ideas? | The best option is to disable keyboard navigation shortcuts in the shadowbox by setting the "enableKeys" option to false (see [this page](http://mjijackson.com/shadowbox/doc/api.html)).
Alternatively you could do what Robby suggests and modify the shadowbox.js file, **but only do this if you need to have the shadowbox keyboard navigation**. I think that you want to search for this block of code and modify it so that it only cancels the default event if one of the shortcuts is used (I've added some line breaks and indention):
```
var handleKey=function(e){
var code=SL.keyCode(e);
SL.preventDefault(e);
if(code==81||code==88||code==27){
SB.close()
}else{
if(code==37){
SB.previous()
}else{
if(code==39){
SB.next()
}else{
if(code==32){
SB[(typeof slide_timer=="number"?"pause":"play")]()
}
}
}
}
};
```
I think you could change it to look more like this:
```
var handleKey=function(e){
switch(SL.keyCode(e)) {
case 81:
case 88:
case 27:
SB.close()
SL.preventDefault(e);
break;
case 37:
SB.previous()
SL.preventDefault(e);
break;
case 39:
SB.next()
SL.preventDefault(e);
break;
case 32:
SB[(typeof slide_timer=="number"?"pause":"play")]()
SL.preventDefault(e);
break;
}
};
```
This should prevent the shadowbox event handler from swallowing any keystrokes that it doesn't care about. |
50,149 | <p>I wrote a SQL function to convert a datetime value in SQL to a friendlier "n Hours Ago" or "n Days Ago" etc type of message. And I was wondering if there was a better way to do it. </p>
<p>(Yes I know "don't do it in SQL" but for design reasons I have to do it this way).</p>
<p>Here is the function I've written:</p>
<pre><code>CREATE FUNCTION dbo.GetFriendlyDateTimeValue
(
@CompareDate DateTime
)
RETURNS nvarchar(48)
AS
BEGIN
DECLARE @Now DateTime
DECLARE @Hours int
DECLARE @Suff nvarchar(256)
DECLARE @Found bit
SET @Found = 0
SET @Now = getDate()
SET @Hours = DATEDIFF(MI, @CompareDate, @Now)/60
IF @Hours <= 1
BEGIN
SET @Suff = 'Just Now'
SET @Found = 1
RETURN @Suff
END
IF @Hours < 24
BEGIN
SET @Suff = ' Hours Ago'
SET @Found = 1
END
IF @Hours >= 8760 AND @Found = 0
BEGIN
SET @Hours = @Hours / 8760
SET @Suff = ' Years Ago'
SET @Found = 1
END
IF @Hours >= 720 AND @Found = 0
BEGIN
SET @Hours = @Hours / 720
SET @Suff = ' Months Ago'
SET @Found = 1
END
IF @Hours >= 168 AND @Found = 0
BEGIN
SET @Hours = @Hours / 168
SET @Suff = ' Weeks Ago'
SET @Found = 1
END
IF @Hours >= 24 AND @Found = 0
BEGIN
SET @Hours = @Hours / 24
SET @Suff = ' Days Ago'
SET @Found = 1
END
RETURN Convert(nvarchar, @Hours) + @Suff
END
</code></pre>
| [
{
"answer_id": 50192,
"author": "Craig",
"author_id": 2894,
"author_profile": "https://Stackoverflow.com/users/2894",
"pm_score": 1,
"selected": false,
"text": "<p>Your code looks functional. As for a better way, that is going to get subjective. You might want to check out this <a href... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50149",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1980/"
] | I wrote a SQL function to convert a datetime value in SQL to a friendlier "n Hours Ago" or "n Days Ago" etc type of message. And I was wondering if there was a better way to do it.
(Yes I know "don't do it in SQL" but for design reasons I have to do it this way).
Here is the function I've written:
```
CREATE FUNCTION dbo.GetFriendlyDateTimeValue
(
@CompareDate DateTime
)
RETURNS nvarchar(48)
AS
BEGIN
DECLARE @Now DateTime
DECLARE @Hours int
DECLARE @Suff nvarchar(256)
DECLARE @Found bit
SET @Found = 0
SET @Now = getDate()
SET @Hours = DATEDIFF(MI, @CompareDate, @Now)/60
IF @Hours <= 1
BEGIN
SET @Suff = 'Just Now'
SET @Found = 1
RETURN @Suff
END
IF @Hours < 24
BEGIN
SET @Suff = ' Hours Ago'
SET @Found = 1
END
IF @Hours >= 8760 AND @Found = 0
BEGIN
SET @Hours = @Hours / 8760
SET @Suff = ' Years Ago'
SET @Found = 1
END
IF @Hours >= 720 AND @Found = 0
BEGIN
SET @Hours = @Hours / 720
SET @Suff = ' Months Ago'
SET @Found = 1
END
IF @Hours >= 168 AND @Found = 0
BEGIN
SET @Hours = @Hours / 168
SET @Suff = ' Weeks Ago'
SET @Found = 1
END
IF @Hours >= 24 AND @Found = 0
BEGIN
SET @Hours = @Hours / 24
SET @Suff = ' Days Ago'
SET @Found = 1
END
RETURN Convert(nvarchar, @Hours) + @Suff
END
``` | As you say, I probably wouldn't do it in SQL, but as a thought exercise have a MySQL implementation:
```
CASE
WHEN compare_date between date_sub(now(), INTERVAL 60 minute) and now()
THEN concat(minute(TIMEDIFF(now(), compare_date)), ' minutes ago')
WHEN datediff(now(), compare_date) = 1
THEN 'Yesterday'
WHEN compare_date between date_sub(now(), INTERVAL 24 hour) and now()
THEN concat(hour(TIMEDIFF(NOW(), compare_date)), ' hours ago')
ELSE concat(datediff(now(), compare_date),' days ago')
END
```
Based on a similar sample seen on the [MySQL Date and Time](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#c9500) manual pages |
50,159 | <p>I'd like to know which libraries are used by executables on my system. More specifically, I'd like to rank which libraries are used the most, along with the binaries that use them. How can I do this?</p>
| [
{
"answer_id": 50166,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 6,
"selected": false,
"text": "<p>to learn what libraries a binary uses, use ldd</p>\n\n<pre><code>ldd path/to/the/tool\n</code></pre>\n\n<p>You'd have to wri... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50159",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3756/"
] | I'd like to know which libraries are used by executables on my system. More specifically, I'd like to rank which libraries are used the most, along with the binaries that use them. How can I do this? | 1. Use `ldd` to list shared libraries for each executable.
2. Cleanup the output
3. Sort, compute counts, sort by count
To find the answer for all executables in the "/bin" directory:
```
find /bin -type f -perm /a+x -exec ldd {} \; \
| grep so \
| sed -e '/^[^\t]/ d' \
| sed -e 's/\t//' \
| sed -e 's/.*=..//' \
| sed -e 's/ (0.*)//' \
| sort \
| uniq -c \
| sort -n
```
Change "/bin" above to "/" to search all directories.
Output (for just the /bin directory) will look something like this:
```
1 /lib64/libexpat.so.0
1 /lib64/libgcc_s.so.1
1 /lib64/libnsl.so.1
1 /lib64/libpcre.so.0
1 /lib64/libproc-3.2.7.so
1 /usr/lib64/libbeecrypt.so.6
1 /usr/lib64/libbz2.so.1
1 /usr/lib64/libelf.so.1
1 /usr/lib64/libpopt.so.0
1 /usr/lib64/librpm-4.4.so
1 /usr/lib64/librpmdb-4.4.so
1 /usr/lib64/librpmio-4.4.so
1 /usr/lib64/libsqlite3.so.0
1 /usr/lib64/libstdc++.so.6
1 /usr/lib64/libz.so.1
2 /lib64/libasound.so.2
2 /lib64/libblkid.so.1
2 /lib64/libdevmapper.so.1.02
2 /lib64/libpam_misc.so.0
2 /lib64/libpam.so.0
2 /lib64/libuuid.so.1
3 /lib64/libaudit.so.0
3 /lib64/libcrypt.so.1
3 /lib64/libdbus-1.so.3
4 /lib64/libresolv.so.2
4 /lib64/libtermcap.so.2
5 /lib64/libacl.so.1
5 /lib64/libattr.so.1
5 /lib64/libcap.so.1
6 /lib64/librt.so.1
7 /lib64/libm.so.6
9 /lib64/libpthread.so.0
13 /lib64/libselinux.so.1
13 /lib64/libsepol.so.1
22 /lib64/libdl.so.2
83 /lib64/ld-linux-x86-64.so.2
83 /lib64/libc.so.6
```
Edit - Removed "grep -P" |
50,169 | <p>I have a query that looks like this:</p>
<pre><code>public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
DatabaseDataContext db = new DatabaseDataContext();
return (from o in db.Orders
orderby o.CreatedDate descending
select o)
.Skip(pageIndex * recordCount)
.Take(recordCount)
.ToList();
}
</code></pre>
<p>I need to print the information of the order and the user who created it:</p>
<pre><code>foreach (var o in FetchLatestOrders(0, 10))
{
Console.WriteLine("{0} {1}", o.Code, o.Customer.Name);
}
</code></pre>
<p>This produces a SQL query to bring the orders and one query for each order to bring the customer. Is it possible to optimize the query so that it brings the orders and it's customer in one SQL query?</p>
<p>Thanks</p>
<p>UDPATE: By suggestion of sirrocco I changed the query like this and it works. Only one select query is generated:</p>
<pre><code>public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
var options = new DataLoadOptions();
options.LoadWith<Post>(o => o.Customer);
using (var db = new DatabaseDataContext())
{
db.LoadOptions = options;
return (from o in db.Orders
orderby o.CreatedDate descending
select o)
.Skip(pageIndex * recordCount)
.Take(recordCount)
.ToList();
}
}
</code></pre>
<p>Thanks sirrocco.</p>
| [
{
"answer_id": 50191,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 0,
"selected": false,
"text": "<p>you might want to look into using compiled queries</p>\n\n<p>have a look at <a href=\"http://www.3devs.com/?p=3\" rel=\... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50169",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4269/"
] | I have a query that looks like this:
```
public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
DatabaseDataContext db = new DatabaseDataContext();
return (from o in db.Orders
orderby o.CreatedDate descending
select o)
.Skip(pageIndex * recordCount)
.Take(recordCount)
.ToList();
}
```
I need to print the information of the order and the user who created it:
```
foreach (var o in FetchLatestOrders(0, 10))
{
Console.WriteLine("{0} {1}", o.Code, o.Customer.Name);
}
```
This produces a SQL query to bring the orders and one query for each order to bring the customer. Is it possible to optimize the query so that it brings the orders and it's customer in one SQL query?
Thanks
UDPATE: By suggestion of sirrocco I changed the query like this and it works. Only one select query is generated:
```
public IList<Post> FetchLatestOrders(int pageIndex, int recordCount)
{
var options = new DataLoadOptions();
options.LoadWith<Post>(o => o.Customer);
using (var db = new DatabaseDataContext())
{
db.LoadOptions = options;
return (from o in db.Orders
orderby o.CreatedDate descending
select o)
.Skip(pageIndex * recordCount)
.Take(recordCount)
.ToList();
}
}
```
Thanks sirrocco. | Something else you can do is EagerLoading. In Linq2SQL you can use LoadOptions : [More on LoadOptions](http://oakleafblog.blogspot.com/2007/08/linq-to-sql-query-execution-with.html)
One VERY weird thing about L2S is that you can set LoadOptions only before the first query is sent to the Database. |
50,170 | <p>I can't be sure if my code is sucking, or if it's just that the browsers haven't caught up with the spec yet.</p>
<p>My goal is to simulate list markers using generated content, so as to get e.g. continuation of the counters from list to list in pure CSS.</p>
<p>So the code below, which I <em>think</em> is correct according to <a href="http://www.w3.org/TR/CSS2/generate.html#markers" rel="nofollow noreferrer">the spec</a>, is like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>html {
counter-reset: myCounter;
}
li {
counter-increment: myCounter;
}
li:before {
content: counter(myCounter)". ";
display: marker;
width: 5em;
text-align: right;
marker-offset: 1em;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><ol>
<li>The<li>
<li>quick</li>
<li>brown</li>
</ol>
<ol>
<li>fox</li>
<li>jumped</li>
<li>over</li>
</ol></code></pre>
</div>
</div>
</p>
<p>But this doesn't seem to generate markers, in either FF3, Chrome, or IE8 beta 2, and if I recall correctly not Opera either (although I've since uninstalled Opera).</p>
<p>So, does anyone know if markers are <em>supposed</em> to work? Quirksmode.org isn't being its usual helpful self in this regard :(.</p>
| [
{
"answer_id": 50201,
"author": "knuton",
"author_id": 4991,
"author_profile": "https://Stackoverflow.com/users/4991",
"pm_score": 3,
"selected": true,
"text": "<p>Apparently marker was introduced as a value in CSS 2 but did not make it to CSS 2.1 because of lacking browser support.\nI s... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3191/"
] | I can't be sure if my code is sucking, or if it's just that the browsers haven't caught up with the spec yet.
My goal is to simulate list markers using generated content, so as to get e.g. continuation of the counters from list to list in pure CSS.
So the code below, which I *think* is correct according to [the spec](http://www.w3.org/TR/CSS2/generate.html#markers), is like this:
```css
html {
counter-reset: myCounter;
}
li {
counter-increment: myCounter;
}
li:before {
content: counter(myCounter)". ";
display: marker;
width: 5em;
text-align: right;
marker-offset: 1em;
}
```
```html
<ol>
<li>The<li>
<li>quick</li>
<li>brown</li>
</ol>
<ol>
<li>fox</li>
<li>jumped</li>
<li>over</li>
</ol>
```
But this doesn't seem to generate markers, in either FF3, Chrome, or IE8 beta 2, and if I recall correctly not Opera either (although I've since uninstalled Opera).
So, does anyone know if markers are *supposed* to work? Quirksmode.org isn't being its usual helpful self in this regard :(. | Apparently marker was introduced as a value in CSS 2 but did not make it to CSS 2.1 because of lacking browser support.
I suppose that didn’t help its popularity …
Source: <http://de.selfhtml.org/css/eigenschaften/positionierung.htm#display> (German) |
50,182 | <p>Is there a good library to use for gathering user input in Linux from the mouse/keyboard/joystick that doesn't force you to create a visible window to do so? SDL lets you get user input in a reasonable way, but seems to force you to create a window, which is troublesome if you have abstracted control so the control machine doesn't have to be the same as the render machine. However, if the control and render machines are the same, this results in an ugly little SDL window on top of your display.</p>
<p><strong>Edit To Clarify</strong>:<br>
The renderer has an output window, in its normal use case, that window is full screen, except when they are both running on the same computer, just so it is possible to give the controller focus. There can actually be multiple renderers displaying a different view of the same data on different computers all controlled by the same controller, hence the total decoupling of the input from the output (Making taking advantage of the built in X11 client/server stuff for display less useable) Also, multiple controller applications for one renderer is also possible. Communication between the controllers and renderers is via sockets.</p>
| [
{
"answer_id": 50220,
"author": "Brian Gianforcaro",
"author_id": 3415,
"author_profile": "https://Stackoverflow.com/users/3415",
"pm_score": 2,
"selected": false,
"text": "<p>For the mouse you can use <a href=\"http://www.linuxjournal.com/article/4600\" rel=\"nofollow noreferrer\">GPM</... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5070/"
] | Is there a good library to use for gathering user input in Linux from the mouse/keyboard/joystick that doesn't force you to create a visible window to do so? SDL lets you get user input in a reasonable way, but seems to force you to create a window, which is troublesome if you have abstracted control so the control machine doesn't have to be the same as the render machine. However, if the control and render machines are the same, this results in an ugly little SDL window on top of your display.
**Edit To Clarify**:
The renderer has an output window, in its normal use case, that window is full screen, except when they are both running on the same computer, just so it is possible to give the controller focus. There can actually be multiple renderers displaying a different view of the same data on different computers all controlled by the same controller, hence the total decoupling of the input from the output (Making taking advantage of the built in X11 client/server stuff for display less useable) Also, multiple controller applications for one renderer is also possible. Communication between the controllers and renderers is via sockets. | OK, if you're under X11 and you want to get the kbd, you need to do a grab.
If you're not, my only good answer is ncurses from a terminal.
Here's how you grab everything from the keyboard and release again:
```
/* Demo code, needs more error checking, compile
* with "gcc nameofthisfile.c -lX11".
/* weird formatting for markdown follows. argh! */
```
`#include <X11/Xlib.h>`
```
int main(int argc, char **argv)
{
Display *dpy;
XEvent ev;
char *s;
unsigned int kc;
int quit = 0;
if (NULL==(dpy=XOpenDisplay(NULL))) {
perror(argv[0]);
exit(1);
}
/*
* You might want to warp the pointer to somewhere that you know
* is not associated with anything that will drain events.
* (void)XWarpPointer(dpy, None, DefaultRootWindow(dpy), 0, 0, 0, 0, x, y);
*/
XGrabKeyboard(dpy, DefaultRootWindow(dpy),
True, GrabModeAsync, GrabModeAsync, CurrentTime);
printf("KEYBOARD GRABBED! Hit 'q' to quit!\n"
"If this job is killed or you get stuck, use Ctrl-Alt-F1\n"
"to switch to a console (if possible) and run something that\n"
"ungrabs the keyboard.\n");
/* A very simple event loop: start at "man XEvent" for more info. */
/* Also see "apropos XGrab" for various ways to lock down access to
* certain types of info. coming out of or going into the server */
for (;!quit;) {
XNextEvent(dpy, &ev);
switch (ev.type) {
case KeyPress:
kc = ((XKeyPressedEvent*)&ev)->keycode;
s = XKeysymToString(XKeycodeToKeysym(dpy, kc, 0));
/* s is NULL or a static no-touchy return string. */
if (s) printf("KEY:%s\n", s);
if (!strcmp(s, "q")) quit=~0;
break;
case Expose:
/* Often, it's a good idea to drain residual exposes to
* avoid visiting Blinky's Fun Club. */
while (XCheckTypedEvent(dpy, Expose, &ev)) /* empty body */ ;
break;
case ButtonPress:
case ButtonRelease:
case KeyRelease:
case MotionNotify:
case ConfigureNotify:
default:
break;
}
}
XUngrabKeyboard(dpy, CurrentTime);
if (XCloseDisplay(dpy)) {
perror(argv[0]);
exit(1);
}
return 0;
}
```
Run this from a terminal and all kbd events should hit it. I'm testing it under Xorg
but it uses venerable, stable Xlib mechanisms.
Hope this helps.
BE CAREFUL with grabs under X. When you're new to them, sometimes it's a good
idea to start a time delay process that will ungrab the server when you're
testing code and let it sit and run and ungrab every couple of minutes.
It saves having to kill or switch away from the server to externally reset state.
From here, I'll leave it to you to decide how to multiplex renderes. Read
the XGrabKeyboard docs and XEvent docs to get started.
If you have small windows exposed at the screen corners, you could jam
the pointer into one corner to select a controller. XWarpPointer can
shove the pointer to one of them as well from code.
One more point: you can grab the pointer as well, and other resources. If you had one controller running on the box in front of which you sit, you could use keyboard and mouse input to switch it between open sockets with different renderers. You shouldn't need to resize the output window to less than full screen anymore with this approach, ever. With more work, you could actually drop alpha-blended overlays on top using the SHAPE and COMPOSITE extensions to get a nice overlay feature in response to user input (which might count as gilding the lily). |
50,223 | <p>We're using Mercurial where I work and I want to have a setup similar to how I used SVN:</p>
<ul>
<li>Trunk</li>
<li>Tags
<ul>
<li>Production</li>
</ul></li>
<li>Branches</li>
</ul>
<p>Since Mercurial supports branches natively, I know how to create a named branch, but I can't find any documentation on how to repeatedly merge 'Trunk' with 'Production'. </p>
<p>Quite simply, I want to have a development branch for normal work and a production branch that I routinely pull changes from the development branch into. How do I do this with Mercurial?</p>
| [
{
"answer_id": 50239,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 2,
"selected": false,
"text": "<p>Something like <a href=\"http://www.selenic.com/mercurial/wiki/index.cgi/TransplantExtension\" rel=\"nofollow noreferrer\"... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/956/"
] | We're using Mercurial where I work and I want to have a setup similar to how I used SVN:
* Trunk
* Tags
+ Production
* Branches
Since Mercurial supports branches natively, I know how to create a named branch, but I can't find any documentation on how to repeatedly merge 'Trunk' with 'Production'.
Quite simply, I want to have a development branch for normal work and a production branch that I routinely pull changes from the development branch into. How do I do this with Mercurial? | As the previous poster mentioned, the transplant extension can be used for cherry-picking individual changes from one branch to another. If, however, you always want to pull *all* the latest changes, the `hg merge` command will get you there.
The simplest case is when you're using clones to implement branching (since that's the use case Mercurial is designed around). Assuming you've turned on the built-in [fetch](http://www.selenic.com/mercurial/wiki/index.cgi/FetchExtension) extension in your `.hgrc` / `Mercurial.ini`:
```
cd ~/src/development
# hack hack hack
hg commit -m "Made some changes"
cd ../production
hg fetch ../development
```
If you're using local branches:
```
hg update -C development
# hack hack hack
hg commit -m "Made some changes"
hg update -C production
hg merge development
hg commit -m "Merged from development"
``` |
50,236 | <p>Often time I need to add a control to a dialog after the dialog has been generated via dialog template and CreateDialogIndirect. In these cases the tab order is set by the dialog template and there is no obvious way to change the tab order by including a newly created control.</p>
| [
{
"answer_id": 50241,
"author": "Karim",
"author_id": 2494,
"author_profile": "https://Stackoverflow.com/users/2494",
"pm_score": 5,
"selected": true,
"text": "<p>I recently discovered that you can use SetWindowPos to accomplish this. Determine which control after which you want to inse... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2494/"
] | Often time I need to add a control to a dialog after the dialog has been generated via dialog template and CreateDialogIndirect. In these cases the tab order is set by the dialog template and there is no obvious way to change the tab order by including a newly created control. | I recently discovered that you can use SetWindowPos to accomplish this. Determine which control after which you want to insert the new control in the tab order then use SetWindowPos like this:
```
SetWindowPos(hNewControl, hOldControl, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE);
```
This changes the z-order of controls which, in turn, establishes the tab order. |
50,251 | <p>I'm stuck trying to create a dynamic linq extension method that returns a string in JSON format - I'm using System.Linq.Dynamic and Newtonsoft.Json and I can't get the Linq.Dynamic to parse the "cell=new object[]" part. Perhaps too complex? Any ideas? : </p>
<p><strong>My Main method:</strong></p>
<pre><code>static void Main(string[] args)
{
NorthwindDataContext db = new NorthwindDataContext();
var query = db.Customers;
string json = JSonify<Customer>
.GetJsonTable(
query,
2,
10,
"CustomerID"
,
new string[]
{
"CustomerID",
"CompanyName",
"City",
"Country",
"Orders.Count"
});
Console.WriteLine(json);
}
</code></pre>
<p><strong>JSonify class</strong></p>
<pre><code>public static class JSonify<T>
{
public static string GetJsonTable(
this IQueryable<T> query,
int pageNumber,
int pageSize,
string IDColumnName,
string[] columnNames)
{
string selectItems =
String.Format(@"
new
{
{{0}} as ID,
cell = new object[]{{{1}}}
}",
IDColumnName,
String.Join(",", columnNames));
var items = new
{
page = pageNumber,
total = query.Count(),
rows =
query
.Select(selectItems)
.Skip(pageNumber * pageSize)
.Take(pageSize)
};
return JavaScriptConvert.SerializeObject(items);
// Should produce this result:
// {
// "page":2,
// "total":91,
// "rows":
// [
// {"ID":"FAMIA","cell":["FAMIA","Familia Arquibaldo","Sao Paulo","Brazil",7]},
// {"ID":"FISSA","cell":["FISSA","FISSA Fabrica Inter. Salchichas S.A.","Madrid","Spain",0]},
// {"ID":"FOLIG","cell":["FOLIG","Folies gourmandes","Lille","France",5]},
// {"ID":"FOLKO","cell":["FOLKO","Folk och fä HB","Bräcke","Sweden",19]},
// {"ID":"FRANK","cell":["FRANK","Frankenversand","München","Germany",15]},
// {"ID":"FRANR","cell":["FRANR","France restauration","Nantes","France",3]},
// {"ID":"FRANS","cell":["FRANS","Franchi S.p.A.","Torino","Italy",6]},
// {"ID":"FURIB","cell":["FURIB","Furia Bacalhau e Frutos do Mar","Lisboa","Portugal",8]},
// {"ID":"GALED","cell":["GALED","Galería del gastrónomo","Barcelona","Spain",5]},
// {"ID":"GODOS","cell":["GODOS","Godos Cocina Típica","Sevilla","Spain",10]}
// ]
// }
}
}
</code></pre>
| [
{
"answer_id": 50592,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 0,
"selected": false,
"text": "<pre><code>static void Main(string[] args)\n{\n NorthwindDataContext db = new NorthwindDataContext();\n var query... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3396/"
] | I'm stuck trying to create a dynamic linq extension method that returns a string in JSON format - I'm using System.Linq.Dynamic and Newtonsoft.Json and I can't get the Linq.Dynamic to parse the "cell=new object[]" part. Perhaps too complex? Any ideas? :
**My Main method:**
```
static void Main(string[] args)
{
NorthwindDataContext db = new NorthwindDataContext();
var query = db.Customers;
string json = JSonify<Customer>
.GetJsonTable(
query,
2,
10,
"CustomerID"
,
new string[]
{
"CustomerID",
"CompanyName",
"City",
"Country",
"Orders.Count"
});
Console.WriteLine(json);
}
```
**JSonify class**
```
public static class JSonify<T>
{
public static string GetJsonTable(
this IQueryable<T> query,
int pageNumber,
int pageSize,
string IDColumnName,
string[] columnNames)
{
string selectItems =
String.Format(@"
new
{
{{0}} as ID,
cell = new object[]{{{1}}}
}",
IDColumnName,
String.Join(",", columnNames));
var items = new
{
page = pageNumber,
total = query.Count(),
rows =
query
.Select(selectItems)
.Skip(pageNumber * pageSize)
.Take(pageSize)
};
return JavaScriptConvert.SerializeObject(items);
// Should produce this result:
// {
// "page":2,
// "total":91,
// "rows":
// [
// {"ID":"FAMIA","cell":["FAMIA","Familia Arquibaldo","Sao Paulo","Brazil",7]},
// {"ID":"FISSA","cell":["FISSA","FISSA Fabrica Inter. Salchichas S.A.","Madrid","Spain",0]},
// {"ID":"FOLIG","cell":["FOLIG","Folies gourmandes","Lille","France",5]},
// {"ID":"FOLKO","cell":["FOLKO","Folk och fä HB","Bräcke","Sweden",19]},
// {"ID":"FRANK","cell":["FRANK","Frankenversand","München","Germany",15]},
// {"ID":"FRANR","cell":["FRANR","France restauration","Nantes","France",3]},
// {"ID":"FRANS","cell":["FRANS","Franchi S.p.A.","Torino","Italy",6]},
// {"ID":"FURIB","cell":["FURIB","Furia Bacalhau e Frutos do Mar","Lisboa","Portugal",8]},
// {"ID":"GALED","cell":["GALED","Galería del gastrónomo","Barcelona","Spain",5]},
// {"ID":"GODOS","cell":["GODOS","Godos Cocina Típica","Sevilla","Spain",10]}
// ]
// }
}
}
``` | This is really ugly and there may be some issues with the string replacement, but it produces the expected results:
```
public static class JSonify
{
public static string GetJsonTable<T>(
this IQueryable<T> query, int pageNumber, int pageSize, string IDColumnName, string[] columnNames)
{
string select = string.Format("new ({0} as ID, \"CELLSTART\" as CELLSTART, {1}, \"CELLEND\" as CELLEND)", IDColumnName, string.Join(",", columnNames));
var items = new
{
page = pageNumber,
total = query.Count(),
rows = query.Select(select).Skip((pageNumber - 1) * pageSize).Take(pageSize)
};
string json = JavaScriptConvert.SerializeObject(items);
json = json.Replace("\"CELLSTART\":\"CELLSTART\",", "\"cell\":[");
json = json.Replace(",\"CELLEND\":\"CELLEND\"", "]");
foreach (string column in columnNames)
{
json = json.Replace("\"" + column + "\":", "");
}
return json;
}
}
``` |
50,280 | <p>I have a site I made really fast that uses floats to display different sections of content. The floated content and the content that has an additional margin both appear fine in FF/IE, but on safari one of the divs is completely hidden. I've tried switching to <code>padding</code> and <code>position:relative</code>, but nothing has worked for me. If I take out the code to display it to the right it shows up again but under the floated content.</p>
<p>The main section of css that seems to be causing the problem is:</p>
<pre class="lang-css prettyprint-override"><code>#settings{
float:left;
}
#right_content{
margin-top:20px;
margin-left:440px;
width:400px;
}
</code></pre>
<p>This gives me the same result whether I specify a size to the #settings div or not. Any ideas would be appreciated.</p>
<p>The site is available at: <a href="http://frickinsweet.com/tools/Theme.mvc.aspx" rel="nofollow noreferrer">http://frickinsweet.com/tools/Theme.mvc.aspx</a> to see the source code.</p>
| [
{
"answer_id": 50302,
"author": "Mike H",
"author_id": 4563,
"author_profile": "https://Stackoverflow.com/users/4563",
"pm_score": 1,
"selected": false,
"text": "<p>Have you tried floating the #right_content div to the right?</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#rig... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1385358/"
] | I have a site I made really fast that uses floats to display different sections of content. The floated content and the content that has an additional margin both appear fine in FF/IE, but on safari one of the divs is completely hidden. I've tried switching to `padding` and `position:relative`, but nothing has worked for me. If I take out the code to display it to the right it shows up again but under the floated content.
The main section of css that seems to be causing the problem is:
```css
#settings{
float:left;
}
#right_content{
margin-top:20px;
margin-left:440px;
width:400px;
}
```
This gives me the same result whether I specify a size to the #settings div or not. Any ideas would be appreciated.
The site is available at: <http://frickinsweet.com/tools/Theme.mvc.aspx> to see the source code. | I believe the error lies in the mark up that the color picker is generating. I saved the page and removed that code for the color picker and it renders fine in IE/FF/SF. |
50,312 | <p>I'm running some <a href="http://jakarta.apache.org/jmeter/" rel="noreferrer">JMeter</a> tests against a Java process to determine how responsive a web application is under load (500+ users). JMeter will give the response time for each web request, and I've written a script to ping the Tomcat Manager every X seconds which will get me the current size of the JVM heap.</p>
<p>I'd like to collect stats on the server of the % of CPU being used by Tomcat. I tried to do it in a shell script using <code>ps</code> like this:</p>
<pre><code>PS_RESULTS=`ps -o pcpu,pmem,nlwp -p $PID`
</code></pre>
<p>...running the command every X seconds and appending the results to a text file. (for anyone wondering, <code>pmem</code> = % mem usage and <code>nlwp</code> is number of threads)</p>
<p>However I've found that this gives a different definition of "% of CPU Utilization" than I'd like - according to the manpages for ps, <code>pcpu</code> is defined as:</p>
<blockquote>
<p>cpu utilization of the process in "##.#" format. It is the CPU time used divided by the time the process has been running (cputime/realtime ratio), expressed as a percentage. </p>
</blockquote>
<p>In other words, <code>pcpu</code> gives me the % CPU utilization for the process for the <em>lifetime</em> of the process.</p>
<p>Since I want to take a sample every X seconds, I'd like to be collecting the CPU utilization of the process at the current time only - similar to what <code>top</code> would give me
(CPU utilization of the process since the last update). </p>
<p>How can I collect this from within a shell script? </p>
| [
{
"answer_id": 50334,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 5,
"selected": true,
"text": "<p>Use <code>top -b</code> (and other switches if you want different outputs). It will just dump to stdout instead of jum... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
] | I'm running some [JMeter](http://jakarta.apache.org/jmeter/) tests against a Java process to determine how responsive a web application is under load (500+ users). JMeter will give the response time for each web request, and I've written a script to ping the Tomcat Manager every X seconds which will get me the current size of the JVM heap.
I'd like to collect stats on the server of the % of CPU being used by Tomcat. I tried to do it in a shell script using `ps` like this:
```
PS_RESULTS=`ps -o pcpu,pmem,nlwp -p $PID`
```
...running the command every X seconds and appending the results to a text file. (for anyone wondering, `pmem` = % mem usage and `nlwp` is number of threads)
However I've found that this gives a different definition of "% of CPU Utilization" than I'd like - according to the manpages for ps, `pcpu` is defined as:
>
> cpu utilization of the process in "##.#" format. It is the CPU time used divided by the time the process has been running (cputime/realtime ratio), expressed as a percentage.
>
>
>
In other words, `pcpu` gives me the % CPU utilization for the process for the *lifetime* of the process.
Since I want to take a sample every X seconds, I'd like to be collecting the CPU utilization of the process at the current time only - similar to what `top` would give me
(CPU utilization of the process since the last update).
How can I collect this from within a shell script? | Use `top -b` (and other switches if you want different outputs). It will just dump to stdout instead of jumping into a curses window. |
50,315 | <p>I have a couple of solutions, but none of them work perfectly.</p>
<p><strong>Platform</strong></p>
<ol>
<li>ASP.NET / VB.NET / .NET 2.0</li>
<li>IIS 6</li>
<li>IE6 (primarily), with some IE7; Firefox not necessary, but useful</li>
</ol>
<p><em>Allowed 3rd Party Options</em></p>
<ol>
<li>Flash</li>
<li>ActiveX (would like to avoid)</li>
<li>Java (would like to avoid)</li>
</ol>
<p><strong>Current Attempts</strong></p>
<p><em>Gmail Style</em>: You can use javascript to add new Upload elements (input type='file'), then upload them all at once with the click of a button. This works, but still requires a lot of clicks. (I was able to use an invisible ActiveX control to detect things like File Size, which would be useful.)</p>
<p><em>Flash Uploader</em>: I discovered a couple of Flash Upload controls that use a 1x1 flash file to act as the uploader, callable by javascript. (One such control is <a href="http://digitarald.de/project/fancyupload/" rel="nofollow noreferrer">FancyUpload</a>, another is <a href="http://www.sitepen.com/blog/2008/09/02/the-dojo-toolkit-multi-file-uploader/" rel="nofollow noreferrer">Dojo's Multiple File Uploader</a>, yet another is one by <a href="http://www.codeproject.com/KB/aspnet/FlashUpload.aspx" rel="nofollow noreferrer">darick_c at CodeProject</a>.) These excited me, but I quickly ran into two issues:</p>
<ol>
<li>Flash 10 will break the functionality that is used to call the multiple file upload dialogue box. The workaround is to use a transparent flash frame, or just use a flash button to call the dialogue box. That's not a huge deal. </li>
<li>The integrated windows authentication used on our intranet is not used when the Flash file attempts to upload the files, prompting the user for credentials. The workaround for this is to use cookieless sessions, which would be a nightmare for our project due to several other reasons.</li>
</ol>
<p><em>Java Uploader</em>: I noticed several Java-based multiple-file uploaders, but most of the appear to cost money. If I found one that worked really well, I could arrange to purchase it. I'd just rather not. I also don't like the look of most of them. I liked FancyUpload because it interacted with html/javascript so that I could easily style and manage it any way I want. </p>
<p><em>ActiveX Uploader</em>: I found <a href="http://support.persits.com/xupload/demo1.asp" rel="nofollow noreferrer">an ActiveX solution</a> as well. It appears that ActiveX will work. I would just write my own instead of buying that one. This will be my last resort, I think.</p>
<p><strong>Resolution</strong></p>
<p>I would love to be able to use something like FancyUpload. If I can just get by the credentials prompt some way, it would be perfect. But, from my research, it appears that the only real workaround is cookieless sessions, which I just can't do. </p>
<p>So, the question is: Is there a way to resolve the issues presented above OR is there a different solution that I have not listed which accomplishes the same goal?</p>
| [
{
"answer_id": 50657,
"author": "Bermo",
"author_id": 5110,
"author_profile": "https://Stackoverflow.com/users/5110",
"pm_score": 1,
"selected": false,
"text": "<p>You could try <a href=\"http://www.swfupload.org/\" rel=\"nofollow noreferrer\">SWFUpload</a> as well - it would fit in your... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/106/"
] | I have a couple of solutions, but none of them work perfectly.
**Platform**
1. ASP.NET / VB.NET / .NET 2.0
2. IIS 6
3. IE6 (primarily), with some IE7; Firefox not necessary, but useful
*Allowed 3rd Party Options*
1. Flash
2. ActiveX (would like to avoid)
3. Java (would like to avoid)
**Current Attempts**
*Gmail Style*: You can use javascript to add new Upload elements (input type='file'), then upload them all at once with the click of a button. This works, but still requires a lot of clicks. (I was able to use an invisible ActiveX control to detect things like File Size, which would be useful.)
*Flash Uploader*: I discovered a couple of Flash Upload controls that use a 1x1 flash file to act as the uploader, callable by javascript. (One such control is [FancyUpload](http://digitarald.de/project/fancyupload/), another is [Dojo's Multiple File Uploader](http://www.sitepen.com/blog/2008/09/02/the-dojo-toolkit-multi-file-uploader/), yet another is one by [darick\_c at CodeProject](http://www.codeproject.com/KB/aspnet/FlashUpload.aspx).) These excited me, but I quickly ran into two issues:
1. Flash 10 will break the functionality that is used to call the multiple file upload dialogue box. The workaround is to use a transparent flash frame, or just use a flash button to call the dialogue box. That's not a huge deal.
2. The integrated windows authentication used on our intranet is not used when the Flash file attempts to upload the files, prompting the user for credentials. The workaround for this is to use cookieless sessions, which would be a nightmare for our project due to several other reasons.
*Java Uploader*: I noticed several Java-based multiple-file uploaders, but most of the appear to cost money. If I found one that worked really well, I could arrange to purchase it. I'd just rather not. I also don't like the look of most of them. I liked FancyUpload because it interacted with html/javascript so that I could easily style and manage it any way I want.
*ActiveX Uploader*: I found [an ActiveX solution](http://support.persits.com/xupload/demo1.asp) as well. It appears that ActiveX will work. I would just write my own instead of buying that one. This will be my last resort, I think.
**Resolution**
I would love to be able to use something like FancyUpload. If I can just get by the credentials prompt some way, it would be perfect. But, from my research, it appears that the only real workaround is cookieless sessions, which I just can't do.
So, the question is: Is there a way to resolve the issues presented above OR is there a different solution that I have not listed which accomplishes the same goal? | [@davidinbcn.myopenid.co](https://stackoverflow.com/questions/50315/how-do-you-allow-multiple-file-uploads-on-an-internal-windows-authentication-in#70521): That's basically how I solved this issue. But, in an effort to provide a more detailed answer, I'm posting my solution here.
**The Solution!**
Create two web applications, or websites, or whatever.
**Application A** is a simple web application. The purpose of this application is to receive file uploads and save them to the proper place. Set this up as an anonymous access allowed. Then make a single ASPX page that accepts posted files and saves them to a given location. (I'm doing this on an intranet. Internet sites may be exposing themselves to security issues by doing this. Take extra precautions if that is the case.) The code behind for this page would look something like this:
```
Dim uploads As HttpFileCollection = HttpContext.Current.Request.Files
If uploads.Count > 0 Then
UploadFiles(uploads)
Else
result = "error"
err = "File Not Uploaded"
End If
```
**Application B** is your primary site that will allow file uploads. Set this up as an authenticated web application that does not allow anonymous access. Then, place the [FancyUpload](http://digitarald.de/journal/54706744/fancyupload-for-flash-10/#comments) (or similar solution) on a page on this site. Configure it to post its files to Application A's upload ASPX page. |
50,316 | <p>I'm developing a website. I'm using a single-page web-app style, so all of the different parts of the site are AJAX'd into index.php. When a user logs in and tells Firefox to remember his username and password, all input boxes on the site get auto-filled with that username and password. This is a problem on the form to change a password. How can i prevent Firefox from automatically filling out these fields? I already tried giving them different names and ids.</p>
<p>Edit: <a href="https://stackoverflow.com/questions/32369/disable-browser-save-password-functionality">Someone has already asked this</a>. Thanks Joel Coohorn.</p>
| [
{
"answer_id": 50319,
"author": "Rob Rolnick",
"author_id": 4798,
"author_profile": "https://Stackoverflow.com/users/4798",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried adding the autocomplete=\"off\" attribute in the input tag? Not sure if it'll work, but it is worth a t... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3757/"
] | I'm developing a website. I'm using a single-page web-app style, so all of the different parts of the site are AJAX'd into index.php. When a user logs in and tells Firefox to remember his username and password, all input boxes on the site get auto-filled with that username and password. This is a problem on the form to change a password. How can i prevent Firefox from automatically filling out these fields? I already tried giving them different names and ids.
Edit: [Someone has already asked this](https://stackoverflow.com/questions/32369/disable-browser-save-password-functionality). Thanks Joel Coohorn. | From Mozilla's documentation
```
<form name="form1" id="form1" method="post" autocomplete="off"
action="http://www.example.com/form.cgi">
[...]
</form>
```
<http://developer.mozilla.org/en/How_to_Turn_Off_Form_Autocompletion> |
50,332 | <p>I'm trying to implement Drag & Drop functionality with source being a TreeView control. When I initiate a drag on a node, I'm getting:</p>
<p><em>Invalid FORMATETC structure (Exception from HRESULT: 0x80040064 (DV_E_FORMATETC))</em></p>
<p>The ItemDrag handler (where the exception takes place), looks like:</p>
<pre><code>private void treeView_ItemDrag(object sender,
System.Windows.Forms.ItemDragEventArgs e)
{
this.DoDragDrop(e.Item, DragDropEffects.Move);
}
</code></pre>
<p>Does anyone know the root cause of this and how to remedy it? (.NET 2.0, Windows XP SP2)</p>
| [
{
"answer_id": 52030,
"author": "Stradas",
"author_id": 5410,
"author_profile": "https://Stackoverflow.com/users/5410",
"pm_score": 1,
"selected": false,
"text": "<p><strong><code>FORMATETC</code></strong> is a type of application clipboard, for lack of a better term. In order to pull o... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4398/"
] | I'm trying to implement Drag & Drop functionality with source being a TreeView control. When I initiate a drag on a node, I'm getting:
*Invalid FORMATETC structure (Exception from HRESULT: 0x80040064 (DV\_E\_FORMATETC))*
The ItemDrag handler (where the exception takes place), looks like:
```
private void treeView_ItemDrag(object sender,
System.Windows.Forms.ItemDragEventArgs e)
{
this.DoDragDrop(e.Item, DragDropEffects.Move);
}
```
Does anyone know the root cause of this and how to remedy it? (.NET 2.0, Windows XP SP2) | In case it helps anyone else - I encountered this problem with the WPF TreeView (not Windows Forms as listed in the question) and the solution was simply to make sure to mark the event as handled in the drop event handler.
```
private void OnDrop(object sender, DragEventArgs e)
{
// Other logic...
e.Handled = true;
}
``` |
50,339 | <pre><code>- Unit Testing
- Mocking
- Inversion of Control
- Refactoring
- Object Relational Mapping
- Others?
</code></pre>
<p>I have found <a href="http://www.lastcraft.com/simple_test.php" rel="nofollow noreferrer">simpletest</a> for unit testing and mocking and, though it leaves much to be desired, it kind-of sort of works.</p>
<p>I have yet to find any reasonable Inversion of Control framework (there is one that came up on phpclasses but no documentation and doesn't seem like anyone's tried it).</p>
| [
{
"answer_id": 50428,
"author": "Mike H",
"author_id": 4563,
"author_profile": "https://Stackoverflow.com/users/4563",
"pm_score": 1,
"selected": false,
"text": "<p>Unit Testing - PHPUnit <a href=\"http://www.phpunit.de/\" rel=\"nofollow noreferrer\">phpunit.de</a></p>\n\n<p>ORM - Doctri... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | ```
- Unit Testing
- Mocking
- Inversion of Control
- Refactoring
- Object Relational Mapping
- Others?
```
I have found [simpletest](http://www.lastcraft.com/simple_test.php) for unit testing and mocking and, though it leaves much to be desired, it kind-of sort of works.
I have yet to find any reasonable Inversion of Control framework (there is one that came up on phpclasses but no documentation and doesn't seem like anyone's tried it). | [phpUnderControl](http://www.phpundercontrol.org/) - continuous integration.
Don't forget about version control (e.g. using [CVS](http://www.nongnu.org/cvs/) or [Subversion](http://subversion.tigris.org/))! |
50,373 | <p>I'm trying to mixin the <code>MultiMap</code> trait with a <code>HashMap</code> like so:</p>
<pre><code>val children:MultiMap[Integer, TreeNode] =
new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode]
</code></pre>
<p>The definition for the <code>MultiMap</code> trait is:</p>
<pre><code>trait MultiMap[A, B] extends Map[A, Set[B]]
</code></pre>
<p>Meaning that a <code>MultiMap</code> of types <code>A</code> & <code>B</code> is a <code>Map</code> of types <code>A</code> & <code>Set[B]</code>, or so it seems to me. However, the compiler complains:</p>
<pre><code>C:\...\TestTreeDataModel.scala:87: error: illegal inheritance; template $anon inherits different type instances of trait Map: scala.collection.mutable.Map[Integer,scala.collection.mutable.Set[package.TreeNode]] and scala.collection.mutable.Map[Integer,Set[package.TreeNode]]
new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode]
^ one error found
</code></pre>
<p>It seems that generics are tripping me up again.</p>
| [
{
"answer_id": 50420,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 6,
"selected": true,
"text": "<p>I had to import <code>scala.collection.mutable.Set</code>. It seems the compiler thought the Set in <code>HashMap[Integer, ... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] | I'm trying to mixin the `MultiMap` trait with a `HashMap` like so:
```
val children:MultiMap[Integer, TreeNode] =
new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode]
```
The definition for the `MultiMap` trait is:
```
trait MultiMap[A, B] extends Map[A, Set[B]]
```
Meaning that a `MultiMap` of types `A` & `B` is a `Map` of types `A` & `Set[B]`, or so it seems to me. However, the compiler complains:
```
C:\...\TestTreeDataModel.scala:87: error: illegal inheritance; template $anon inherits different type instances of trait Map: scala.collection.mutable.Map[Integer,scala.collection.mutable.Set[package.TreeNode]] and scala.collection.mutable.Map[Integer,Set[package.TreeNode]]
new HashMap[Integer, Set[TreeNode]] with MultiMap[Integer, TreeNode]
^ one error found
```
It seems that generics are tripping me up again. | I had to import `scala.collection.mutable.Set`. It seems the compiler thought the Set in `HashMap[Integer, Set[TreeNode]]` was `scala.collection.Set`. The Set in the MultiMap def is `scala.collection.`**`mutable`**`.Set`. |
50,384 | <p>I'm using <a href="http://en.wikipedia.org/wiki/Windows_Script_Host#Usage" rel="noreferrer">WScript</a> to automate some tasks, by using WScript.Shell to call external programs.</p>
<p>However, right now it does not wait for the external program to finish, and instead moves on. This causes issues because I have some tasks dependent on others finishing first.</p>
<p>I am using code like:</p>
<pre><code>ZipCommand = "7za.exe a -r -y " & ZipDest & BuildLabel & ".zip " & buildSourceDir
Set wshShell = WScript.CreateObject("Wscript.Shell")
wshShell.run ZipCommand
</code></pre>
<p>Is there a way to do this so it blocks until the shell executed program returns?</p>
| [
{
"answer_id": 50395,
"author": "Guy Starbuck",
"author_id": 2194,
"author_profile": "https://Stackoverflow.com/users/2194",
"pm_score": 3,
"selected": false,
"text": "<p>If you use the \"Exec\" method, it returns a reference, so you can poll the \"Status\" property to determine when it ... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1965/"
] | I'm using [WScript](http://en.wikipedia.org/wiki/Windows_Script_Host#Usage) to automate some tasks, by using WScript.Shell to call external programs.
However, right now it does not wait for the external program to finish, and instead moves on. This causes issues because I have some tasks dependent on others finishing first.
I am using code like:
```
ZipCommand = "7za.exe a -r -y " & ZipDest & BuildLabel & ".zip " & buildSourceDir
Set wshShell = WScript.CreateObject("Wscript.Shell")
wshShell.run ZipCommand
```
Is there a way to do this so it blocks until the shell executed program returns? | Turns out, that while loop is severe CPU hog :P
I found a better way:
```
ZipCommand = "7za.exe a -r -y " & ZipDest & BuildLabel & ".zip " & buildSourceDir
Set wshShell = WScript.CreateObject("Wscript.Shell")
wshShell.Run ZipCommand,1,1
```
The last two arguments are Show window and Block Execution :) |
50,394 | <p>I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly.</p>
<p>I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - <a href="http://mail.python.org/pipermail/python-list/2000-March/028122.html" rel="noreferrer">this old discussion list link</a> has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions.</p>
<p>Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself? :) </p>
| [
{
"answer_id": 50413,
"author": "Justin Standard",
"author_id": 92,
"author_profile": "https://Stackoverflow.com/users/92",
"pm_score": 0,
"selected": false,
"text": "<p>Another way to do it is to use <code>urllib2</code> module to parse some other page's whois service (many sites like t... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50394",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4172/"
] | I'm trying to get a webservice up and running that actually requires to check whois databases. What I'm doing right now is ugly and I'd like to avoid it as much as I can: I call gwhois command and parse its output. Ugly.
I did some search to try to find a pythonic way to do this task. Generally I got quite much nothing - [this old discussion list link](http://mail.python.org/pipermail/python-list/2000-March/028122.html) has a way to check if domain exist. Quite not what I was looking for... But still, it was best anwser Google gave me - everything else is just a bunch of unanwsered questions.
Any of you have succeeded to get some method up and running? I'd very much appreciate some tips, or should I just do it the opensource-way, sit down and code something by myself? :) | There's nothing wrong with using a command line utility to do what you want. If you put a nice wrapper around the service, you can implement the internals however you want! For example:
```
class Whois(object):
_whois_by_query_cache = {}
def __init__(self, query):
"""Initializes the instance variables to defaults. See :meth:`lookup`
for details on how to submit the query."""
self.query = query
self.domain = None
# ... other fields.
def lookup(self):
"""Submits the `whois` query and stores results internally."""
# ... implementation
```
Now, whether or not you roll your own using urllib, wrap around a command line utility (like you're doing), or import a third party library and use that (like [you're saying](https://stackoverflow.com/questions/50394#50423)), this interface stays the same.
This approach is generally not considered ugly at all -- **sometimes command utilities do what you want and you should be able to leverage them**. If speed ends up being a bottleneck, your abstraction makes the process of switching to a native Python implementation transparent to your client code.
[Practicality beats purity](http://www.python.org/dev/peps/pep-0020/) -- that's what's Pythonic. :) |
50,417 | <p>When I use Emacs I want to be able to easily display and navigate through a list of files I worked on from not just the current session but from previous sessions. (BTW, running Emacs 22.2 on Windows)</p>
| [
{
"answer_id": 50422,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 6,
"selected": true,
"text": "<p>From <a href=\"http://www.joegrossberg.com/archives/000182.html\" rel=\"noreferrer\">Joe Grossberg</a>'s blog (no longe... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50417",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] | When I use Emacs I want to be able to easily display and navigate through a list of files I worked on from not just the current session but from previous sessions. (BTW, running Emacs 22.2 on Windows) | From [Joe Grossberg](http://www.joegrossberg.com/archives/000182.html)'s blog (no longer available):
>
> But if you're using GNU Emacs 21.2
> (the latest version, which includes
> this as part of the standard distro),
> you can just put the following lines
> into your .emacs file
>
>
>
> ```
> ;; recentf stuff
> (require 'recentf)
> (recentf-mode 1)
> (setq recentf-max-menu-items 25)
> (global-set-key "\C-x\ \C-r" 'recentf-open-files)
>
> ```
>
> Then, when you launch emacs, hit
> `CTRL`-`X` `CTRL`-`R`. It will show a list of
> the recently-opened files in a buffer.
> Move the cursor to a line and press
> `ENTER`. That will open the file in
> question, and move it to the top of
> your recent-file list.
>
>
> (Note: Emacs records file names.
> Therefore, if you move or rename a
> file outside of Emacs, it won't
> automatically update the list. You'll
> have to open the renamed file with the
> normal `CTRL`-`X` `CTRL`-`F` method.)
>
>
> Jayakrishnan Varnam has a [page
> including screenshots](http://web.archive.org/web/20021114012120/http://varnam.org/e-recentf.html) of how this
> package works.
>
>
>
*Note:* You don't need the `(require 'recentf)` line. |
50,450 | <p>This has been driving me crazy for a few days. Why doesn't the following work?</p>
<blockquote>
<pre><code> Dim arr(3, 3) As Integer
For y As Integer = 0 To arr.GetLength(0) - 1
For x As Integer = 0 To arr.GetLength(y) - 1
arr(y, x) = y + x
Next
Next
</code></pre>
</blockquote>
<p>Also, what if the array looked like this instead?</p>
<pre><code>{ {1, 2, 3},
{4, 5, 6, 7, 8, 9, 9, 9},
{5, 4, 3, 2}
}
</code></pre>
| [
{
"answer_id": 50454,
"author": "harpo",
"author_id": 4525,
"author_profile": "https://Stackoverflow.com/users/4525",
"pm_score": 2,
"selected": false,
"text": "<p><code>arr.GetLength(y)</code></p>\n\n<p>should be</p>\n\n<p><code>arr.GetLength(1)</code></p>\n"
},
{
"answer_id": 5... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50450",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/795/"
] | This has been driving me crazy for a few days. Why doesn't the following work?
>
>
> ```
> Dim arr(3, 3) As Integer
>
> For y As Integer = 0 To arr.GetLength(0) - 1
> For x As Integer = 0 To arr.GetLength(y) - 1
> arr(y, x) = y + x
> Next
> Next
>
> ```
>
>
Also, what if the array looked like this instead?
```
{ {1, 2, 3},
{4, 5, 6, 7, 8, 9, 9, 9},
{5, 4, 3, 2}
}
``` | Ok, so what you really need is a "jagged array". This will allow you to have an "array that contains other arrays of varying lengths".
```
Dim arr As Integer()() = {New Integer() {1, 2, 3}, New Integer() {4, 5, 6, 7, 8, 9, 9, 9}, New Integer() {5, 4, 3, 2}}
For x = 0 To arr.GetUpperBound(0)
Console.WriteLine("Row " & x & " has " & arr(x).GetUpperBound(0) & " columns")
For y = 0 To arr(x).GetUpperBound(0)
Console.WriteLine("(" & x & "," & y & ") = " & arr(x)(y))
Next
Next
```
Output:
```
Row 0 has 2 columns
(0,0) = 1
(0,1) = 2
(0,2) = 3
Row 1 has 7 columns
(1,0) = 4
(1,1) = 5
(1,2) = 6
(1,3) = 7
(1,4) = 8
(1,5) = 9
(1,6) = 9
(1,7) = 9
Row 2 has 3 columns
(2,0) = 5
(2,1) = 4
(2,2) = 3
(2,3) = 2
``` |
50,467 | <p>Is there a good way to adjust the size of a <code>UITextView</code> to conform to its content? Say for instance I have a <code>UITextView</code> that contains one line of text:</p>
<pre><code>"Hello world"
</code></pre>
<p>I then add another line of text:</p>
<pre><code>"Goodbye world"
</code></pre>
<p>Is there a good way in Cocoa Touch to get the <code>rect</code> that will hold all of the lines in the text view so that I can adjust the parent view accordingly?</p>
<p>As another example, look at the notes' field for events in the Calendar application - note how the cell (and the <code>UITextView</code> it contains) expands to hold all lines of text in the notes' string.</p>
| [
{
"answer_id": 50608,
"author": "Mike McMaster",
"author_id": 544,
"author_profile": "https://Stackoverflow.com/users/544",
"pm_score": 4,
"selected": false,
"text": "<p>Did you try <code>[textView sizeThatFits:textView.bounds]</code> ?</p>\n\n<p>Edit: sizeThatFits returns the size but d... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1967/"
] | Is there a good way to adjust the size of a `UITextView` to conform to its content? Say for instance I have a `UITextView` that contains one line of text:
```
"Hello world"
```
I then add another line of text:
```
"Goodbye world"
```
Is there a good way in Cocoa Touch to get the `rect` that will hold all of the lines in the text view so that I can adjust the parent view accordingly?
As another example, look at the notes' field for events in the Calendar application - note how the cell (and the `UITextView` it contains) expands to hold all lines of text in the notes' string. | This works for both iOS 6.1 and iOS 7:
```
- (void)textViewDidChange:(UITextView *)textView
{
CGFloat fixedWidth = textView.frame.size.width;
CGSize newSize = [textView sizeThatFits:CGSizeMake(fixedWidth, MAXFLOAT)];
CGRect newFrame = textView.frame;
newFrame.size = CGSizeMake(fmaxf(newSize.width, fixedWidth), newSize.height);
textView.frame = newFrame;
}
```
Or in Swift (Works with Swift 4.1 in iOS 11)
```
let fixedWidth = textView.frame.size.width
let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
textView.frame.size = CGSize(width: max(newSize.width, fixedWidth), height: newSize.height)
```
If you want support for iOS 6.1 then you should also:
```
textview.scrollEnabled = NO;
``` |
50,470 | <p>I'm building a webapp that contains an IFrame in design mode so my user's can "tart" their content up and paste in content to be displayed on their page. Like the WYSIWYG editor on most blog engines or forums.</p>
<p>I'm trying to think of all potential security holes I need to plug, one of which is a user pasting in Javascript:</p>
<pre><code><script type="text/javascript">
// Do some nasty stuff
</script>
</code></pre>
<p>Now I know I can strip this out at the server end, before saving it and/or serving it back, but I'm worried about the possibility of someone being able to paste some script in and run it there and then, without even sending it back to the server for processing.</p>
<p>Am I worrying over nothing?</p>
<p>Any advice would be great, couldn't find much searching Google.</p>
<p>Anthony</p>
| [
{
"answer_id": 50474,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 2,
"selected": false,
"text": "<p>As Jason said, I would focus more on cleaning the data on the server side. You don't really have any real cont... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50470",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/366/"
] | I'm building a webapp that contains an IFrame in design mode so my user's can "tart" their content up and paste in content to be displayed on their page. Like the WYSIWYG editor on most blog engines or forums.
I'm trying to think of all potential security holes I need to plug, one of which is a user pasting in Javascript:
```
<script type="text/javascript">
// Do some nasty stuff
</script>
```
Now I know I can strip this out at the server end, before saving it and/or serving it back, but I'm worried about the possibility of someone being able to paste some script in and run it there and then, without even sending it back to the server for processing.
Am I worrying over nothing?
Any advice would be great, couldn't find much searching Google.
Anthony | >
> ...I'm worried about the possibility of someone being able to paste some script in and run it there and then, without even sending it back to the server for processing.
>
>
> Am I worrying over nothing?
>
>
>
Firefox has a plug-in called Greasemonkey that allows users to arbitrarily run JavaScript against any page that loads into their browser, and there is nothing you can do about it. Firebug allows you to modify web pages as well as run arbitrary JavaScript.
AFAIK, you really only need to worry once it gets to your server, and then potentially hits other users. |
50,499 | <p>I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process. </p>
<p>For example, let's say I have three files. Using <a href="http://docs.python.org/library/functions.html#execfile" rel="noreferrer">execfile</a>:</p>
<ul>
<li><code>script_1.py</code> calls <code>script_2.py</code>. </li>
<li>In turn, <code>script_2.py</code> calls <code>script_3.py</code>. </li>
</ul>
<p>How can I get the file name and path of <strong><code>script_3.py</code></strong>, <em>from code within <code>script_3.py</code></em>, without having to pass that information as arguments from <code>script_2.py</code>?</p>
<p>(Executing <code>os.getcwd()</code> returns the original starting script's filepath not the current file's.)</p>
| [
{
"answer_id": 50502,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 4,
"selected": false,
"text": "<p>It's not entirely clear what you mean by \"the filepath of the file that is currently running within the process\".\n... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50499",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
] | I have scripts calling other script files but I need to get the filepath of the file that is currently running within the process.
For example, let's say I have three files. Using [execfile](http://docs.python.org/library/functions.html#execfile):
* `script_1.py` calls `script_2.py`.
* In turn, `script_2.py` calls `script_3.py`.
How can I get the file name and path of **`script_3.py`**, *from code within `script_3.py`*, without having to pass that information as arguments from `script_2.py`?
(Executing `os.getcwd()` returns the original starting script's filepath not the current file's.) | p1.py:
```
execfile("p2.py")
```
p2.py:
```
import inspect, os
print (inspect.getfile(inspect.currentframe())) # script filename (usually with path)
print (os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))) # script directory
``` |
50,525 | <p>Let's take the code</p>
<pre><code>int a, b, c;
...
if ((a + b) > C)
</code></pre>
<p>If we add the values of a and b and the sum exceeds the maximum value of an int, will the integrity of the comparison be compromised? I was thinking that there might be an implicit up cast or overflow bit check and that will be factored into the evaluation of this expression.</p>
| [
{
"answer_id": 50530,
"author": "hazzen",
"author_id": 5066,
"author_profile": "https://Stackoverflow.com/users/5066",
"pm_score": 4,
"selected": true,
"text": "<p>C will do no such thing. It will silently overflow and lead to a possibly incorrect comparison. You can up-cast yourself, bu... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2064/"
] | Let's take the code
```
int a, b, c;
...
if ((a + b) > C)
```
If we add the values of a and b and the sum exceeds the maximum value of an int, will the integrity of the comparison be compromised? I was thinking that there might be an implicit up cast or overflow bit check and that will be factored into the evaluation of this expression. | C will do no such thing. It will silently overflow and lead to a possibly incorrect comparison. You can up-cast yourself, but it will not be done automatically. |
50,532 | <p>How do I format a number in Java?<br />
What are the "Best Practices"?</p>
<p>Will I need to round a number before I format it?</p>
<blockquote>
<p><code>32.302342342342343</code> => <code>32.30</code></p>
<p><code>.7323</code> => <code>0.73</code></p>
</blockquote>
<p>etc.</p>
| [
{
"answer_id": 50543,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 8,
"selected": true,
"text": "<p>From <a href=\"http://bytes.com/forum/thread16212.html\" rel=\"noreferrer\">this thread</a>, there are different ways to do th... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1310/"
] | How do I format a number in Java?
What are the "Best Practices"?
Will I need to round a number before I format it?
>
> `32.302342342342343` => `32.30`
>
>
> `.7323` => `0.73`
>
>
>
etc. | From [this thread](http://bytes.com/forum/thread16212.html), there are different ways to do this:
```
double r = 5.1234;
System.out.println(r); // r is 5.1234
int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);
// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();
System.out.println(r); // r is 5.12
```
---
```
f = (float) (Math.round(n*100.0f)/100.0f);
```
---
```
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();
// The value of dd2dec will be 100.24
```
The [DecimalFormat()](http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html) seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code. |
50,539 | <p>One of the guys I work with needs a custom control that would work like a multiline ddl since such a thing does not exist as far as we have been able to discover</p>
<p>does anyone have any ideas or have created such a thing before<br>
we have a couple ideas but they involve to much database usage </p>
<p>We prefer that it be FREE!!!</p>
| [
{
"answer_id": 50543,
"author": "Espo",
"author_id": 2257,
"author_profile": "https://Stackoverflow.com/users/2257",
"pm_score": 8,
"selected": true,
"text": "<p>From <a href=\"http://bytes.com/forum/thread16212.html\" rel=\"noreferrer\">this thread</a>, there are different ways to do th... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50539",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2486/"
] | One of the guys I work with needs a custom control that would work like a multiline ddl since such a thing does not exist as far as we have been able to discover
does anyone have any ideas or have created such a thing before
we have a couple ideas but they involve to much database usage
We prefer that it be FREE!!! | From [this thread](http://bytes.com/forum/thread16212.html), there are different ways to do this:
```
double r = 5.1234;
System.out.println(r); // r is 5.1234
int decimalPlaces = 2;
BigDecimal bd = new BigDecimal(r);
// setScale is immutable
bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_HALF_UP);
r = bd.doubleValue();
System.out.println(r); // r is 5.12
```
---
```
f = (float) (Math.round(n*100.0f)/100.0f);
```
---
```
DecimalFormat df2 = new DecimalFormat( "#,###,###,##0.00" );
double dd = 100.2397;
double dd2dec = new Double(df2.format(dd)).doubleValue();
// The value of dd2dec will be 100.24
```
The [DecimalFormat()](http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html) seems to be the most dynamic way to do it, and it is also very easy to understand when reading others code. |
50,558 | <p>I have a two dimensional array that I need to load data into. I know the width of the data (22 values) but I do not know the height (estimated around 4000 records, but variable).</p>
<p>I have it declared as follows: </p>
<pre><code>float[,] _calibrationSet;
....
int calibrationRow = 0;
While (recordsToRead)
{
for (int i = 0; i < SensorCount; i++)
{
_calibrationSet[calibrationRow, i] = calibrationArrayView.ReadFloat();
}
calibrationRow++;
}
</code></pre>
<p>This causes a NullReferenceException, so when I try to initialize it like this: </p>
<pre><code>_calibrationSet = new float[,];
</code></pre>
<p>I get an "Array creation must have array size or array initializer."</p>
<p>Thank you,
Keith</p>
| [
{
"answer_id": 50581,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 4,
"selected": true,
"text": "<p>You can't use an array.\nOr rather, you would need to pick a size, and if you ended up needing more then you would have to allo... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50558",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1048/"
] | I have a two dimensional array that I need to load data into. I know the width of the data (22 values) but I do not know the height (estimated around 4000 records, but variable).
I have it declared as follows:
```
float[,] _calibrationSet;
....
int calibrationRow = 0;
While (recordsToRead)
{
for (int i = 0; i < SensorCount; i++)
{
_calibrationSet[calibrationRow, i] = calibrationArrayView.ReadFloat();
}
calibrationRow++;
}
```
This causes a NullReferenceException, so when I try to initialize it like this:
```
_calibrationSet = new float[,];
```
I get an "Array creation must have array size or array initializer."
Thank you,
Keith | You can't use an array.
Or rather, you would need to pick a size, and if you ended up needing more then you would have to allocate a new, larger, array, copy the data from the old one into the new one, and continue on as before (until you exceed the size of the new one...)
Generally, you would go with one of the collection classes - ArrayList, List<>, LinkedList<>, etc. - which one depends a lot on what you're looking for; List will give you the closest thing to what i described initially, while LinkedList<> will avoid the problem of frequent re-allocations (at the cost of slower access and greater memory usage).
Example:
```
List<float[]> _calibrationSet = new List<float[]>();
// ...
while (recordsToRead)
{
float[] record = new float[SensorCount];
for (int i = 0; i < SensorCount; i++)
{
record[i] = calibrationArrayView.ReadFloat();
}
_calibrationSet.Add(record);
}
// access later: _calibrationSet[record][sensor]
```
Oh, and it's worth noting (as [Grauenwolf](https://stackoverflow.com/questions/50558/how-do-you-initialize-a-2-dimensional-array-when-you-do-not-know-the-size#50591) did), that what i'm doing here doesn't give you the same memory structure as a single, multi-dimensional array would - under the hood, it's an array of references to other arrays that actually hold the data. This speeds up building the array a good deal by making reallocation cheaper, but can have an impact on access speed (and, of course, memory usage). Whether this is an issue for you depends a lot on what you'll be doing with the data after it's loaded... and whether there are two hundred records or two million records. |
50,565 | <p>I have a ContextMenu that is displayed after a user right clicks on a ComboBox. When the user selects an item in the context menu, a form is brought up using the <code>ShowDialog()</code> method. </p>
<pre><code>If frmOptions.ShowDialog() = Windows.Forms.DialogResult.Cancel Then
LoadComboBoxes()
End If
</code></pre>
<p>When that form is closed, I refresh all the data in the ComboBoxes on the parent form. However, when this happens the ComboBox that opened the ContextMenu is reset to have a selected index of -1 but the other selected indexes of the other ComboBoxes remain the same. </p>
<p>How do I prevent the ComboBox that opened the context menu from being reset?</p>
| [
{
"answer_id": 50590,
"author": "DaveK",
"author_id": 4244,
"author_profile": "https://Stackoverflow.com/users/4244",
"pm_score": 2,
"selected": true,
"text": "<p>One way to handle this would be to use the context menu's Popup event to grab the selected index of the combobox launching th... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50565",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/299/"
] | I have a ContextMenu that is displayed after a user right clicks on a ComboBox. When the user selects an item in the context menu, a form is brought up using the `ShowDialog()` method.
```
If frmOptions.ShowDialog() = Windows.Forms.DialogResult.Cancel Then
LoadComboBoxes()
End If
```
When that form is closed, I refresh all the data in the ComboBoxes on the parent form. However, when this happens the ComboBox that opened the ContextMenu is reset to have a selected index of -1 but the other selected indexes of the other ComboBoxes remain the same.
How do I prevent the ComboBox that opened the context menu from being reset? | One way to handle this would be to use the context menu's Popup event to grab the selected index of the combobox launching the menu. When the dialog form closes reset the selected index. |
50,579 | <p>I'm having a strange problem.</p>
<p>I have to use <code>GetPostBackEventRefence</code> to force a Postback, but it works the first time, after the first postback, the .NET function is not rendered... any ideas?</p>
<p>This is what I'm missing after the postback:</p>
<pre><code><script language="javascript" type="text/javascript">
<!--
function __doPostBack(eventTarget, eventArgument) {
var theform;
if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
theform = document.Main;
}
else {
theform = document.forms["Main"];
}
theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
theform.__EVENTARGUMENT.value = eventArgument;
theform.submit();
}
// -->
</script>
</code></pre>
| [
{
"answer_id": 50593,
"author": "Haydar",
"author_id": 288,
"author_profile": "https://Stackoverflow.com/users/288",
"pm_score": 3,
"selected": true,
"text": "<p>The first thing I would look at is whether you have any asp controls (such as linkbutton, comboboxes,that don't normally gener... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] | I'm having a strange problem.
I have to use `GetPostBackEventRefence` to force a Postback, but it works the first time, after the first postback, the .NET function is not rendered... any ideas?
This is what I'm missing after the postback:
```
<script language="javascript" type="text/javascript">
<!--
function __doPostBack(eventTarget, eventArgument) {
var theform;
if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1) {
theform = document.Main;
}
else {
theform = document.forms["Main"];
}
theform.__EVENTTARGET.value = eventTarget.split("$").join(":");
theform.__EVENTARGUMENT.value = eventArgument;
theform.submit();
}
// -->
</script>
``` | The first thing I would look at is whether you have any asp controls (such as linkbutton, comboboxes,that don't normally generate a submit but requre a postback) being displayed on the page.
**The \_\_doPostback function will only be put into the page if ASP thinks that one of your controls requires it.**
If you aren't using one of those you can use:
```
Page.ClientScript.GetPostBackClientHyperlink(controlName, "")
```
to add the function to your page |
50,585 | <p>How do you capture the mouse events, move and click over top of a Shockwave Director Object (not flash) in Firefox, via JavaScript. The code works in IE but not in FF. </p>
<p>The script works on the document body of both IE and Moz, but mouse events do not fire when mouse is over a shockwave director object embed.</p>
<p>Update: </p>
<pre><code> function displaycoordIE(){
window.status=event.clientX+" : " + event.clientY;
}
function displaycoordNS(e){
window.status=e.clientX+" : " + e.clientY;
}
function displaycoordMoz(e)
{
window.alert(e.clientX+" : " + e.clientY);
}
document.onmousemove = displaycoordIE;
document.onmousemove = displaycoordNS;
document.onclick = displaycoordMoz;
</code></pre>
<hr>
<p>Just a side note, I have also tried using an addEventListener to "mousemove".</p>
| [
{
"answer_id": 171164,
"author": "ken",
"author_id": 20300,
"author_profile": "https://Stackoverflow.com/users/20300",
"pm_score": 1,
"selected": false,
"text": "<p>Just an idea.</p>\n\n<p>Try overlaying the shockwave object with a div with opacity 0, then you can capture events on the d... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50585",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/567/"
] | How do you capture the mouse events, move and click over top of a Shockwave Director Object (not flash) in Firefox, via JavaScript. The code works in IE but not in FF.
The script works on the document body of both IE and Moz, but mouse events do not fire when mouse is over a shockwave director object embed.
Update:
```
function displaycoordIE(){
window.status=event.clientX+" : " + event.clientY;
}
function displaycoordNS(e){
window.status=e.clientX+" : " + e.clientY;
}
function displaycoordMoz(e)
{
window.alert(e.clientX+" : " + e.clientY);
}
document.onmousemove = displaycoordIE;
document.onmousemove = displaycoordNS;
document.onclick = displaycoordMoz;
```
---
Just a side note, I have also tried using an addEventListener to "mousemove". | You could also catch the mouse event within Director (That never fails) and then call your JS functions from there, using gotoNetPage "javascript:function('" & argument & "')"
ej:
```
on mouseDown me
gotoNetPage "javascript:function('" & argument & "')"
end
```
The mouse move detection is a little bit trickier, as there is no such an event in lingo, but you can use:
```
property pMouseLock
on beginsprite
pMouseLock = _mouse.mouseLock
end
on exitFrame
if _mouse.mouseLock <> pMouseLock then
gotoNetPage "javascript:function('" & argument & "')"
pMouseLock = _mouse.mouseLock
end if
end
```
regards |
50,605 | <p>Suppose I have the following C code.</p>
<pre><code>unsigned int u = 1234;
int i = -5678;
unsigned int result = u + i;
</code></pre>
<p>What implicit conversions are going on here, and is this code safe for all values of <code>u</code> and <code>i</code>? (Safe, in the sense that even though <em>result</em> in this example will overflow to some huge positive number, I could cast it back to an <em>int</em> and get the real result.)</p>
| [
{
"answer_id": 50632,
"author": "Ozgur Ozcitak",
"author_id": 976,
"author_profile": "https://Stackoverflow.com/users/976",
"pm_score": 9,
"selected": true,
"text": "<p><strong>Short Answer</strong></p>\n\n<p>Your <code>i</code> will be <em>converted</em> to an unsigned integer by adding... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4828/"
] | Suppose I have the following C code.
```
unsigned int u = 1234;
int i = -5678;
unsigned int result = u + i;
```
What implicit conversions are going on here, and is this code safe for all values of `u` and `i`? (Safe, in the sense that even though *result* in this example will overflow to some huge positive number, I could cast it back to an *int* and get the real result.) | **Short Answer**
Your `i` will be *converted* to an unsigned integer by adding `UINT_MAX + 1`, then the addition will be carried out with the unsigned values, resulting in a large `result` (depending on the values of `u` and `i`).
**Long Answer**
According to the C99 Standard:
>
> 6.3.1.8 Usual arithmetic conversions
>
>
> 1. If both operands have the same type, then no further conversion is needed.
> 2. Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
> 3. Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
> 4. Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.
> 5. Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.
>
>
>
In your case, we have one unsigned int (`u`) and signed int (`i`). Referring to (3) above, since both operands have the same rank, your `i` will need to be *converted* to an unsigned integer.
>
> 6.3.1.3 Signed and unsigned integers
>
>
> 1. When a value with integer type is converted to another integer type other than \_Bool, if the value can be represented by the new type, it is unchanged.
> 2. Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
> 3. Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
>
>
>
Now we need to refer to (2) above. Your `i` will be converted to an unsigned value by adding `UINT_MAX + 1`. So the result will depend on how `UINT_MAX` is defined on your implementation. It will be large, but it will not overflow, because:
>
> 6.2.5 (9)
>
>
> A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.
>
>
>
**Bonus: Arithmetic Conversion Semi-WTF**
```
#include <stdio.h>
int main(void)
{
unsigned int plus_one = 1;
int minus_one = -1;
if(plus_one < minus_one)
printf("1 < -1");
else
printf("boring");
return 0;
}
```
You can use this link to try this online: [https://repl.it/repls/QuickWhimsicalBytes](http://codepad.org/yPhYCMFO)
**Bonus: Arithmetic Conversion Side Effect**
Arithmetic conversion rules can be used to get the value of `UINT_MAX` by initializing an unsigned value to `-1`, ie:
```
unsigned int umax = -1; // umax set to UINT_MAX
```
This is guaranteed to be portable regardless of the signed number representation of the system because of the conversion rules described above. See this SO question for more information: [Is it safe to use -1 to set all bits to true?](https://stackoverflow.com/questions/809227/is-it-safe-to-use-1-to-set-all-bits-to-true) |
50,618 | <p>Syntax aside, what is the difference between</p>
<pre><code>try {
}
catch() {
}
finally {
x = 3;
}
</code></pre>
<p>and </p>
<pre><code>try {
}
catch() {
}
x = 3;
</code></pre>
<p>edit: in .NET 2.0?</p>
<hr>
<p>so</p>
<pre><code>try {
throw something maybe
x = 3
}
catch (...) {
x = 3
}
</code></pre>
<p>is behaviourally equivalent?</p>
| [
{
"answer_id": 50621,
"author": "Ryan Lanciaux",
"author_id": 1385358,
"author_profile": "https://Stackoverflow.com/users/1385358",
"pm_score": 0,
"selected": false,
"text": "<p>So you can clean up any open connections, etc. initialized in the try block. If you opened a connection and th... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5278/"
] | Syntax aside, what is the difference between
```
try {
}
catch() {
}
finally {
x = 3;
}
```
and
```
try {
}
catch() {
}
x = 3;
```
edit: in .NET 2.0?
---
so
```
try {
throw something maybe
x = 3
}
catch (...) {
x = 3
}
```
is behaviourally equivalent? | Depends on the language as there might be some slight semantic differences, but the idea is that it will execute (almost) always, even if the code in the try block threw an exception.
In the second example, if the code in the catch block returns or quits, the x = 3 will not be executed. In the first it will.
In the .NET platform, in some cases the execution of the finally block won't occur:
Security Exceptions, Thread suspensions, Computer shut down :), etc. |
50,702 | <p>If I have 2 query sources how do I find ones that are in one that are not in the other?</p>
<p>example of join to find items in both:</p>
<pre><code>var results = from item1 in qs1.Items
join item2 in qs2 on item1.field1 equals item2.field2
select item1;
</code></pre>
<p>So what would the linq code be to return the items in qs1 that are not in qs2?</p>
| [
{
"answer_id": 50719,
"author": "Bramha Ghosh",
"author_id": 3268,
"author_profile": "https://Stackoverflow.com/users/3268",
"pm_score": 2,
"selected": false,
"text": "<p>From <a href=\"http://programminglinq.com/blogs/marcorusso/archive/2008/01/14/the-not-in-clause-in-linq-to-sql.aspx\"... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50702",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1215/"
] | If I have 2 query sources how do I find ones that are in one that are not in the other?
example of join to find items in both:
```
var results = from item1 in qs1.Items
join item2 in qs2 on item1.field1 equals item2.field2
select item1;
```
So what would the linq code be to return the items in qs1 that are not in qs2? | Darren Kopp's [answer](https://stackoverflow.com/questions/50702/linq-how-do-you-do-a-query-for-items-in-one-query-source-that-are-not-in-anothe/50724#50724):
```
var excluded = items1.Except(items2);
```
is the best solution from a performance perspective.
*(NB: This true for at least regular LINQ, perhaps LINQ to SQL changes things as per [Marco Russo's blog post](http://programminglinq.com/blogs/marcorusso/archive/2008/01/14/the-not-in-clause-in-linq-to-sql.aspx). However, I'd imagine that in the "worst case" Darren Kopp's method will return at least the speed of Russo's method even in a LINQ to SQL environment).*
As a quick example try this in [LINQPad](http://www.linqpad.net/):
```
void Main()
{
Random rand = new Random();
int n = 100000;
var randomSeq = Enumerable.Repeat(0, n).Select(i => rand.Next());
var randomFilter = Enumerable.Repeat(0, n).Select(i => rand.Next());
/* Method 1: Bramha Ghosh's/Marco Russo's method */
(from el1 in randomSeq where !(from el2 in randomFilter select el2).Contains(el1) select el1).Dump("Result");
/* Method 2: Darren Kopp's method */
randomSeq.Except(randomFilter).Dump("Result");
}
```
Try commenting one of the two methods out at a time and try out the performance for different values of n.
My experience (on my Core 2 Duo Laptop) seems to suggest:
```
n = 100. Method 1 takes about 0.05 seconds, Method 2 takes about 0.05 seconds
n = 1,000. Method 1 takes about 0.6 seconds, Method 2 takes about 0.4 seconds
n = 10,000. Method 1 takes about 2.5 seconds, Method 2 takes about 0.425 seconds
n = 100,000. Method 1 takes about 20 seconds, Method 2 takes about 0.45 seconds
n = 1,000,000. Method 1 takes about 3 minutes 25 seconds, Method 2 takes about 1.3 seconds
```
*Method 2 (Darren Kopp's answer) is clearly faster.*
The speed decrease for Method 2 for larger n is most likely due to the creation of the random data (feel free to put in a DateTime diff to confirm this) whereas Method 1 clearly has algorithmic complexity issues (and just by looking you can see it is at least O(N^2) as for each number in the first collection it is comparing against the entire second collection).
**Conclusion:** Use Darren Kopp's answer of LINQ's 'Except' method |
50,737 | <p>Is there a way to have TortoiseSVN (or any other tool) auto-add any new .cs files I create within a directory to my working copy so I don't have to remember which files I created at the end of the day?</p>
| [
{
"answer_id": 50742,
"author": "Blorgbeard",
"author_id": 369,
"author_profile": "https://Stackoverflow.com/users/369",
"pm_score": 3,
"selected": false,
"text": "<p>If you just commit your working copy, you'll get a file list showing you your unversioned files, which you can tick to ad... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] | Is there a way to have TortoiseSVN (or any other tool) auto-add any new .cs files I create within a directory to my working copy so I don't have to remember which files I created at the end of the day? | I would probably make a batch file, something like this (untested):
```
dir /b /S *.cs > allcsfiles.txt
svn add --targets allcsfiles.txt
```
I believe svn won't mind you trying to add files which are already versioned..
Anyway, that's probably about as automatic as you will easily get. |
50,744 | <p>What's the simplest way of blocking a thread until a file has been unlocked and is accessible for reading and renaming? For example, is there a WaitOnFile() somewhere in the .NET Framework?</p>
<p>I have a service that uses a FileSystemWatcher to look for files that are to be transmitted to an FTP site, but the <em>file created</em> event fires before the other process has finished writing the file.</p>
<p>The ideal solution would have a timeout period so the thread doesn't hang forever before giving up.</p>
<p>Edit: After trying out some of the solutions below, I ended up changing the <em>system</em> so that all files wrote to <code>Path.GetTempFileName()</code>, then performed a <code>File.Move()</code> to the final location. As soon as the <code>FileSystemWatcher</code> event fired, the file was already complete.</p>
| [
{
"answer_id": 50753,
"author": "Gulzar Nazim",
"author_id": 4337,
"author_profile": "https://Stackoverflow.com/users/4337",
"pm_score": 2,
"selected": false,
"text": "<p>One of the techniques I used some time back was to write my own function. Basically catch the exception and retry usi... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5548/"
] | What's the simplest way of blocking a thread until a file has been unlocked and is accessible for reading and renaming? For example, is there a WaitOnFile() somewhere in the .NET Framework?
I have a service that uses a FileSystemWatcher to look for files that are to be transmitted to an FTP site, but the *file created* event fires before the other process has finished writing the file.
The ideal solution would have a timeout period so the thread doesn't hang forever before giving up.
Edit: After trying out some of the solutions below, I ended up changing the *system* so that all files wrote to `Path.GetTempFileName()`, then performed a `File.Move()` to the final location. As soon as the `FileSystemWatcher` event fired, the file was already complete. | This was the answer I gave on a [related question](https://stackoverflow.com/questions/41290/file-access-strategy-in-a-multi-threaded-environment-web-app#41559):
```
/// <summary>
/// Blocks until the file is not locked any more.
/// </summary>
/// <param name="fullPath"></param>
bool WaitForFile(string fullPath)
{
int numTries = 0;
while (true)
{
++numTries;
try
{
// Attempt to open the file exclusively.
using (FileStream fs = new FileStream(fullPath,
FileMode.Open, FileAccess.ReadWrite,
FileShare.None, 100))
{
fs.ReadByte();
// If we got this far the file is ready
break;
}
}
catch (Exception ex)
{
Log.LogWarning(
"WaitForFile {0} failed to get an exclusive lock: {1}",
fullPath, ex.ToString());
if (numTries > 10)
{
Log.LogWarning(
"WaitForFile {0} giving up after 10 tries",
fullPath);
return false;
}
// Wait for the lock to be released
System.Threading.Thread.Sleep(500);
}
}
Log.LogTrace("WaitForFile {0} returning true after {1} tries",
fullPath, numTries);
return true;
}
``` |
50,746 | <p>We are using VS 2008 Team System with the automated test suite, and upon running tests the test host "randomly" locks up. I actually have to kill the VSTestHost process and re-run the tests to get something to happen, otherwise all tests sit in a "pending" state.</p>
<p>Has anyone experience similar behavior and know of a fix? We have 3 developers here experiencing the same behavior.</p>
| [
{
"answer_id": 51063,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 2,
"selected": false,
"text": "<p>When you say lock up, do you mean VS is actually hung, or do the tests not run?</p>\n\n<p>The easiest way to track down w... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5289/"
] | We are using VS 2008 Team System with the automated test suite, and upon running tests the test host "randomly" locks up. I actually have to kill the VSTestHost process and re-run the tests to get something to happen, otherwise all tests sit in a "pending" state.
Has anyone experience similar behavior and know of a fix? We have 3 developers here experiencing the same behavior. | When you say lock up, do you mean VS is actually hung, or do the tests not run?
The easiest way to track down what is going on would be to look at a dump of the hung process. If you are on Vista, just right-click on the process and choose to create a memory dump. If you are on Windows XP, and don't have the [Debugging Tools for Windows](http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx) installed, you can get a memory dump using ntsd.exe. You'll need the process ID, which you can get from Task Manager by adding the PID column to the Processes tab display.
Once you have that, run the following commands:
```
ntsd -p <PID>
.dump C:\mydump.dmp
```
You can then either inspect that dump using [WinDBG and SOS](http://blogs.msdn.com/johan/archive/2007/11/13/getting-started-with-windbg-part-i.aspx) or if you can post the dump somewhere I'd be happy to take a look at it.
In any case, you'll want to likely take two dumps about a minute apart. That way if you do things like !runaway you can see which threads are working which will help you track down why it is hanging.
One other question - are you on VS2008 SP1? |
50,771 | <p>This would be a question for anyone who has code in the App_Code folder and uses a hardware load balancer. Its true the hardware load balancer could be set to sticky sessions to solve the issue, but in a perfect world, I would like the feature turned off.</p>
<p>When a file in the App_Code folder, and the site is not pre-compiled iis will generate random file names for these files.</p>
<pre><code>server1 "/ajax/SomeControl, App_Code.tjazq3hb.ashx"
server2 "/ajax/SomeControl, App_Code.wzp3akyu.ashx"
</code></pre>
<p>So when a user posts the page and gets transfered to the other server nothing works.</p>
<p>Does anyone have a solution for this? I could change to a pre-compiled web-site, but we would lose the ability for our QA department to just promote the changed files.</p>
| [
{
"answer_id": 50780,
"author": "Michael Haren",
"author_id": 29,
"author_profile": "https://Stackoverflow.com/users/29",
"pm_score": 1,
"selected": false,
"text": "<p>Does your load balancer supports sticky sessions? With this on, the balancer will route the same IP to the same server o... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50771",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3453/"
] | This would be a question for anyone who has code in the App\_Code folder and uses a hardware load balancer. Its true the hardware load balancer could be set to sticky sessions to solve the issue, but in a perfect world, I would like the feature turned off.
When a file in the App\_Code folder, and the site is not pre-compiled iis will generate random file names for these files.
```
server1 "/ajax/SomeControl, App_Code.tjazq3hb.ashx"
server2 "/ajax/SomeControl, App_Code.wzp3akyu.ashx"
```
So when a user posts the page and gets transfered to the other server nothing works.
Does anyone have a solution for this? I could change to a pre-compiled web-site, but we would lose the ability for our QA department to just promote the changed files. | You could move whatever is in your app\_code to an external class library if your QA dept can promote that entire library. I think you are stuck with sticky sessions if you can't find a convenient or tolerable way to switch to a pre-compiled site. |
50,786 | <p>How do I get ms-access to connect (through ODBC) to an ms-sql database as a different user than their Active Directory ID? </p>
<p>I don't want to specify an account in the ODBC connection, I want to do it on the ms-access side to hide it from my users. Doing it in the ODBC connection would put me right back in to the original situation I'm trying to avoid.</p>
<p>Yes, this relates to a previous question: <a href="http://www.stackoverflow.com/questions/50164/">http://www.stackoverflow.com/questions/50164/</a></p>
| [
{
"answer_id": 51016,
"author": "tbreffni",
"author_id": 637,
"author_profile": "https://Stackoverflow.com/users/637",
"pm_score": 0,
"selected": false,
"text": "<p>I think you'd have to launch the MS Access process under the account you want to use to connect. There are various tools t... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/685/"
] | How do I get ms-access to connect (through ODBC) to an ms-sql database as a different user than their Active Directory ID?
I don't want to specify an account in the ODBC connection, I want to do it on the ms-access side to hide it from my users. Doing it in the ODBC connection would put me right back in to the original situation I'm trying to avoid.
Yes, this relates to a previous question: <http://www.stackoverflow.com/questions/50164/> | I think you can get this to work the way you want it to if you use an ["ODBC DSN-LESS connection"](http://www.carlprothman.net/Default.aspx?tabid=90#ODBCDriverForSQLServer)
If you need to, keep your ODBC DSN's on your users' machines using windows authentication. Give your users read-only access to your database. (If they create a new mdb file and link the tables they'll only be able to read the data.)
Create a SQL Login which has read/write permission to your database.
Write a VBA routine which loops over your linked tables and resets the connection to use you SQL Login but be sure to use the "DSN-Less" syntax.
```
"ODBC;Driver={SQL Native Client};" &
"Server=MyServerName;" & _
"Database=myDatabaseName;" & _
"Uid=myUsername;" & _
"Pwd=myPassword"
```
Call this routine as part of your startup code.
**A couple of notes about this approach:**
* Access seems to have an issue with the connection info once you change from Read/Write to Read Only and try going back to Read/Write without closing and re-opening the database (mde/mdb) file. If you can change this once at startup to Read/Write and not change it during the session this solution should work.
* By using a DSN - Less connection you are able to hide the credentials from the user in code (assuming you're giving them an mde file you should be ok). Normally hard-coding connection strings isn't a good idea, but since you're dealing with an in-house app you should be ok with this approach. |
50,794 | <p>How does unix handle full path name with space and arguments ?<br>
In windows we quote the path and add the command-line arguments after, how is it in unix?</p>
<pre><code> "c:\foo folder with space\foo.exe" -help
</code></pre>
<p><strong>update:</strong></p>
<p>I meant how do I recognize a path from the command line arguments.</p>
| [
{
"answer_id": 50798,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 4,
"selected": false,
"text": "<p>You can quote if you like, or you can escape the spaces with a preceding \\, but most UNIX paths (Mac OS X aside) don't ... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2566/"
] | How does unix handle full path name with space and arguments ?
In windows we quote the path and add the command-line arguments after, how is it in unix?
```
"c:\foo folder with space\foo.exe" -help
```
**update:**
I meant how do I recognize a path from the command line arguments. | You can either quote it like your Windows example above, or escape the spaces with backslashes:
```
"/foo folder with space/foo" --help
/foo\ folder\ with\ space/foo --help
``` |
50,801 | <p>How would you find the fractional part of a floating point number in PHP?</p>
<p>For example, if I have the value <code>1.25</code>, I want to return <code>0.25</code>.</p>
| [
{
"answer_id": 50806,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 7,
"selected": true,
"text": "<pre><code>$x = $x - floor($x)\n</code></pre>\n"
},
{
"answer_id": 50807,
"author": "Ethan Gunderson",
"author... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4925/"
] | How would you find the fractional part of a floating point number in PHP?
For example, if I have the value `1.25`, I want to return `0.25`. | ```
$x = $x - floor($x)
``` |
50,824 | <p>I wrote a simple tool to generate a DBUnit XML dataset using queries that the user enters. I want to include each query entered in the XML as a comment, but the DBUnit API to generate the XML file doesn't support inserting the comment where I would like it (above the data it generates), so I am resorting to putting the comment with ALL queries either at the top or bottom.</p>
<p>So my question: is it valid XML to place it at either location? For example, above the XML Declaration:</p>
<pre><code><!-- Queries used: ... -->
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
...
</dataset>
</code></pre>
<p>Or below the root node:</p>
<pre><code><?xml version='1.0' encoding='UTF-8'?>
<dataset>
...
</dataset>
<!-- Queries used: ... -->
</code></pre>
<p>I plan to initially try above the XML Declaration, but I have doubts on if that is valid XML, despite the claim from <a href="http://en.wikipedia.org/wiki/Xml#Well-formed_documents:_XML_syntax" rel="noreferrer">wikipedia</a>:</p>
<blockquote>
<p>Comments can be placed anywhere in the tree, including in the text if the content of the element is text or #PCDATA.</p>
</blockquote>
<p>I plan to post back if this works, but it would be nice to know if it is an official XML standard.</p>
<p><strong>UPDATE:</strong> See <a href="https://stackoverflow.com/questions/50824/can-xml-comments-go-anywhere#50976">my response below</a> for the result of my test.</p>
| [
{
"answer_id": 50832,
"author": "Anonymoose",
"author_id": 2391,
"author_profile": "https://Stackoverflow.com/users/2391",
"pm_score": 5,
"selected": true,
"text": "<p>According to the <a href=\"http://www.w3.org/TR/2006/REC-xml-20060816/#sec-comments\" rel=\"noreferrer\">XML specificati... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50824",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] | I wrote a simple tool to generate a DBUnit XML dataset using queries that the user enters. I want to include each query entered in the XML as a comment, but the DBUnit API to generate the XML file doesn't support inserting the comment where I would like it (above the data it generates), so I am resorting to putting the comment with ALL queries either at the top or bottom.
So my question: is it valid XML to place it at either location? For example, above the XML Declaration:
```
<!-- Queries used: ... -->
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
...
</dataset>
```
Or below the root node:
```
<?xml version='1.0' encoding='UTF-8'?>
<dataset>
...
</dataset>
<!-- Queries used: ... -->
```
I plan to initially try above the XML Declaration, but I have doubts on if that is valid XML, despite the claim from [wikipedia](http://en.wikipedia.org/wiki/Xml#Well-formed_documents:_XML_syntax):
>
> Comments can be placed anywhere in the tree, including in the text if the content of the element is text or #PCDATA.
>
>
>
I plan to post back if this works, but it would be nice to know if it is an official XML standard.
**UPDATE:** See [my response below](https://stackoverflow.com/questions/50824/can-xml-comments-go-anywhere#50976) for the result of my test. | According to the [XML specification](http://www.w3.org/TR/2006/REC-xml-20060816/#sec-comments), a well-formed XML document is:
>
> `document ::= prolog element Misc*`
>
>
>
where `prolog` is
>
> `prolog ::= XMLDecl? Misc* (doctypedecl Misc*)?`
>
>
>
and `Misc` is
>
> `Misc ::= Comment | PI | S`
>
>
>
and
>
> `XMLDecl ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'`
>
>
>
which means that, if you want to have comments at the top, you cannot have an XML type declaration.
You can, however, have comments after the declaration and outside the document element, either at the top or the bottom of the document, because `Misc*` can contain comments.
The specification agrees with Wikipedia on comments:
>
> 2.5 Comments
>
>
> [Definition: Comments may appear anywhere in a document outside other markup; in addition, they may appear within the document type declaration at places allowed by the grammar. They are not part of the document's character data; an XML processor MAY, but need not, make it possible for an application to retrieve the text of comments. For compatibility, the string "--" (double-hyphen) MUST NOT occur within comments.] Parameter entity references MUST NOT be recognized within comments.
>
>
>
All of this together means that you can put comments **anywhere that's not inside other markup**, except that you **cannot have an XML declaration if you lead with a comment**.
However, while in theory theory agrees with practice, in practice it doesn't, so I'd be curious to see how your experiment works out. |
50,845 | <p>For my acceptance testing I'm writing text into the auto complete extender and I need to click on the populated list.</p>
<p>In order to populate the list I have to use AppendText instead of TypeText, otherwise the textbox looses focus before the list is populated.</p>
<p>Now my problem is when I try to click on the populated list. I've tried searching the UL element and clicking on it; but it's not firing the click event on the list.</p>
<p>Then I tried to search the list by tagname and value:</p>
<pre><code>Element element = Browser.Element(Find.By("tagname", "li") && Find.ByValue("lookupString"));
</code></pre>
<p>but it's not finding it, has anyone been able to do what I'm trying to do?</p>
| [
{
"answer_id": 50857,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": -1,
"selected": false,
"text": "<p>I would go with XML. XML is widely supported on all platforms and has lots of libraries and tools available for it. An... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1560/"
] | For my acceptance testing I'm writing text into the auto complete extender and I need to click on the populated list.
In order to populate the list I have to use AppendText instead of TypeText, otherwise the textbox looses focus before the list is populated.
Now my problem is when I try to click on the populated list. I've tried searching the UL element and clicking on it; but it's not firing the click event on the list.
Then I tried to search the list by tagname and value:
```
Element element = Browser.Element(Find.By("tagname", "li") && Find.ByValue("lookupString"));
```
but it's not finding it, has anyone been able to do what I'm trying to do? | The best solution (if we're talking .NET) seem to be to use WCF and streaming http. The client makes the first http connection to the server at port 80, the connection is then kept open with a streaming response that never ends. (And if it does it reconnects).
Here's a sample that demonstrates this: [Streaming XML](http://blogs.thinktecture.com/buddhike/archive/2007/05/23/414851.aspx).
The solution to pushing through firewalls: [Keeping connections open in IIS](http://blogs.msdn.com/drnick/archive/2006/10/20/keeping-connections-open-in-iis.aspx "Keeping connections open in IIS") |
50,853 | <p>I have a relationship between two entities (e1 and e2) and e1 has a collection of e2, however I have a similar relationship set up between (e2 and e3), yet e2 does not contain a collection of e3's, any reason why this would happen? Anything I can post to make this easier to figure out?</p>
<p>Edit: I just noticed that the relationship between e1 and e2 is solid and between e2 and e3 is dotted, what causes that? Is it related?</p>
| [
{
"answer_id": 50957,
"author": "Gabe Anzelini",
"author_id": 5236,
"author_profile": "https://Stackoverflow.com/users/5236",
"pm_score": 0,
"selected": false,
"text": "<p>the FK_Contraints are set up like this:</p>\n\n<p>ALTER TABLE [dbo].[e2] WITH CHECK ADD CONSTRAINT [FK_e2_e1] FOREIG... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50853",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5236/"
] | I have a relationship between two entities (e1 and e2) and e1 has a collection of e2, however I have a similar relationship set up between (e2 and e3), yet e2 does not contain a collection of e3's, any reason why this would happen? Anything I can post to make this easier to figure out?
Edit: I just noticed that the relationship between e1 and e2 is solid and between e2 and e3 is dotted, what causes that? Is it related? | **Using this setup, everything worked.**
*1) LINQ to SQL Query, 2) DB Tables, 3) LINQ to SQL Data Model in VS.NET 2008*
**1 - LINQ to SQL Query**
```
DataClasses1DataContext db = new DataClasses1DataContext();
var results = from threes in db.tableThrees
join twos in db.tableTwos on threes.fk_tableTwo equals twos.id
join ones in db.tableOnes on twos.fk_tableOne equals ones.id
select new { ones, twos, threes };
```
**2 - Database Scripts**
```
--Table One
CREATE TABLE tableOne(
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
CONSTRAINT [PK_tableOne] PRIMARY KEY CLUSTERED
( [id] ASC ) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
--Table Two
CREATE TABLE tableTwo(
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
[fk_tableOne] [int] NOT NULL,
CONSTRAINT [PK_tableTwo] PRIMARY KEY CLUSTERED
( [id] ASC ) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
ALTER TABLE tableTwo WITH CHECK
ADD CONSTRAINT [FK_tableTwo_tableOne]
FOREIGN KEY([fk_tableOne])
REFERENCES tableOne ([id]);
ALTER TABLE tableTwo CHECK CONSTRAINT [FK_tableTwo_tableOne];
--Table Three
CREATE TABLE tableThree(
[id] [int] IDENTITY(1,1) NOT NULL,
[value] [nvarchar](50) NULL,
[fk_tableTwo] [int] NOT NULL,
CONSTRAINT [PK_tableThree] PRIMARY KEY CLUSTERED
([id] ASC ) WITH (
PAD_INDEX = OFF,
STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF,
ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY];
ALTER TABLE tableThree WITH CHECK
ADD CONSTRAINT [FK_tableThree_tableTwo]
FOREIGN KEY([fk_tableTwo])
REFERENCES tableTwo ([id]);
ALTER TABLE tableThree CHECK CONSTRAINT [FK_tableThree_tableTwo];
```
**3 - LINQ to SQL Data Model in Visual Studio**
[alt text http://i478.photobucket.com/albums/rr148/KyleLanser/ThreeLevelHierarchy.png](http://i478.photobucket.com/albums/rr148/KyleLanser/ThreeLevelHierarchy.png) |
50,900 | <p>So I have about 10 short css files that I use with mvc app.
There are like
error.css
login.css
etc...
Just some really short css files that make updating and editing easy (At least for me). What I want is something that will optimize the if else branch and not incorporate it within the final bits. I want to do something like this</p>
<pre><code>if(Debug.Mode){
<link rel="stylesheet" type="text/css" href="error.css" />
<link rel="stylesheet" type="text/css" href="login.css" />
<link rel="stylesheet" type="text/css" href="menu.css" />
<link rel="stylesheet" type="text/css" href="page.css" />
} else {
<link rel="stylesheet" type="text/css" href="site.css" />
}
</code></pre>
<p>I'll have a msbuild task that will combine all the css files, minimize them and all that good stuff. I just need to know if there is a way to remove the if else branch in the final bits.</p>
| [
{
"answer_id": 50921,
"author": "jdelator",
"author_id": 438,
"author_profile": "https://Stackoverflow.com/users/438",
"pm_score": 3,
"selected": false,
"text": "<p>I should had used google.</p>\n\n<pre><code>#if DEBUG\n Console.WriteLine(\"Debug mode.\") \n#else \n Console.WriteLi... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50900",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/438/"
] | So I have about 10 short css files that I use with mvc app.
There are like
error.css
login.css
etc...
Just some really short css files that make updating and editing easy (At least for me). What I want is something that will optimize the if else branch and not incorporate it within the final bits. I want to do something like this
```
if(Debug.Mode){
<link rel="stylesheet" type="text/css" href="error.css" />
<link rel="stylesheet" type="text/css" href="login.css" />
<link rel="stylesheet" type="text/css" href="menu.css" />
<link rel="stylesheet" type="text/css" href="page.css" />
} else {
<link rel="stylesheet" type="text/css" href="site.css" />
}
```
I'll have a msbuild task that will combine all the css files, minimize them and all that good stuff. I just need to know if there is a way to remove the if else branch in the final bits. | Specifically, like this in C#:
```
#if (DEBUG)
Debug Stuff
#endif
```
C# has the following preprocessor directives:
```
#if
#else
#elif // Else If
#endif
#define
#undef // Undefine
#warning // Causes the preprocessor to fire warning
#error // Causes the preprocessor to fire a fatal error
#line // Lets the preprocessor know where this source line came from
#region // Codefolding
#endregion
``` |
50,931 | <p>I'm using <a href="http://www.helicontech.com/isapi_rewrite/" rel="nofollow noreferrer">Helicon's ISAPI Rewrite 3</a>, which basically enables .htaccess in IIS. I need to redirect a non-www URL to the www version, i.e. example.com should redirect to www.example.com. I used the following rule from the examples but it affects subdomains:</p>
<pre><code>RewriteCond %{HTTPS} (on)?
RewriteCond %{HTTP:Host} ^(?!www\.)(.+)$ [NC]
RewriteCond %{REQUEST_URI} (.+)
RewriteRule .? http(?%1s)://www.%2%3 [R=301,L]
</code></pre>
<p>This works for most part, but is also redirect sub.example.com to www.sub.example.com. How can I rewrite the above rule so that subdomains do not get redirected?</p>
| [
{
"answer_id": 50937,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 0,
"selected": false,
"text": "<p>Can't you adjust the RewriteCond to only operate on example.com?</p>\n\n<pre><code>RewriteCond %{HTTP:Host} ^example\\.com(... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2614/"
] | I'm using [Helicon's ISAPI Rewrite 3](http://www.helicontech.com/isapi_rewrite/), which basically enables .htaccess in IIS. I need to redirect a non-www URL to the www version, i.e. example.com should redirect to www.example.com. I used the following rule from the examples but it affects subdomains:
```
RewriteCond %{HTTPS} (on)?
RewriteCond %{HTTP:Host} ^(?!www\.)(.+)$ [NC]
RewriteCond %{REQUEST_URI} (.+)
RewriteRule .? http(?%1s)://www.%2%3 [R=301,L]
```
This works for most part, but is also redirect sub.example.com to www.sub.example.com. How can I rewrite the above rule so that subdomains do not get redirected? | Append the following RewriteCond:
```
RewriteCond %{HTTP:Host} ^[^.]+\.[a-z]{2,5}$ [NC]
```
That way it'll only apply the rule to nondottedsomething.uptofiveletters as you can see, subdomain.domain.com will not match the condition and thus will not be rewritten.
You can change [a-z]{2,5} for a stricter tld matching regex, as well as placing all the constraints for allowed chars in domain names (as [^.]+ is more permissive than strictly necessary).
All in all I think in this case that wouldn't be necessary.
EDIT: sadie spotted a flaw on the regex, changed the first part of it from [^.] to [^.]+ |
50,983 | <p>I liked the discussion at <a href="https://stackoverflow.com/questions/31693/differences-in-generics">Differences in Generics</a>, and was wondering whether there were any languages that used this feature particularly well.</p>
<p>I really dislike Java's <code>List<? extends Foo></code> for a <code>List</code> of things that are Liskov-substitutable for <code>Foo</code>. Why can't <code>List<Foo></code> cover that?</p>
<p>And honestly, <code>Comparable<? super Bar></code>?</p>
<p>I also can't remember for the life of my why you should never return an Array of generics:</p>
<pre><code>public T[] getAll<T>() { ... }
</code></pre>
<p>I never liked templates in C++, but that was mostly because none of the compilers could ever spit out a remotely meaningful error message for them. One time I actually did a <code>make realclean && make</code> 17 times to get something to compile; I never did figure out why the 17th time was the charm.</p>
<p>So, who actually <em>likes</em> using generics in their pet language?</p>
| [
{
"answer_id": 50991,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 5,
"selected": true,
"text": "<p>Haskell implements type-constructor parameterisation (generics, or parametric polymorphism) quite well. So does Scala (al... | 2008/09/08 | [
"https://Stackoverflow.com/questions/50983",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1190/"
] | I liked the discussion at [Differences in Generics](https://stackoverflow.com/questions/31693/differences-in-generics), and was wondering whether there were any languages that used this feature particularly well.
I really dislike Java's `List<? extends Foo>` for a `List` of things that are Liskov-substitutable for `Foo`. Why can't `List<Foo>` cover that?
And honestly, `Comparable<? super Bar>`?
I also can't remember for the life of my why you should never return an Array of generics:
```
public T[] getAll<T>() { ... }
```
I never liked templates in C++, but that was mostly because none of the compilers could ever spit out a remotely meaningful error message for them. One time I actually did a `make realclean && make` 17 times to get something to compile; I never did figure out why the 17th time was the charm.
So, who actually *likes* using generics in their pet language? | Haskell implements type-constructor parameterisation (generics, or parametric polymorphism) quite well. So does Scala (although it needs a bit of hand-holding sometimes).
Both of these languages have higher-kinded types (a.k.a. abstract type constructors, or type-constructor polymorphism, or higher-order polymorphism).
See here: [Generics of a Higher Kind](http://lambda-the-ultimate.org/node/2579) |
50,995 | <p>I'm a C# developer who's fumbling in the first VB code he's written since VB6, so if I am asking a rather obvious question, please forgive me.</p>
<p>I decided to experiment with XML Literals to generate some XML code for me, instead of using XMLDocument</p>
<p>I have 2 questions, the second regarding a workaround due to my inability to figure out the first.</p>
<p>1: Ideal solution</p>
<p>I have a Dictionary of ElementName, ElementValue whose KeyValue pairs I was looping over in the hope of generating the values dynamically, but the following syntax dies a horrible death</p>
<pre><code>Dim xConnections As XElement
For Each connection As Connection In connections.AsList
For Each kvp As KeyValuePair(Of String, String) In connection.DecompiledElements
xConnections = <Connections> <<%= kvp.Key %>><%= kvp.Value %><\<%=kvp.Key %>> </Connections>
Next
Next
</code></pre>
<p>I have vague memories of the T4 syntax (the <%=%> syntax) being able to handle more complex operations (rather than direct assignment to the <%= ) and a 'Response.Write' like object to write output to, but I can't remember the details.</p>
<p>2: Cludgy workaround</p>
<p>Instead I thought of building a StringBuilder object and assigning its .ToString to the XElement, but that also failed with a conversion error.</p>
<p>I would prefer to continue using my key value pair concept in example one above, as I feel cludging together a string as in example 2 above is rather nasty, and I really should go back to using XMLDocument if instead.</p>
<p>Any thoughts or assistance greatly appreciated</p>
| [
{
"answer_id": 51025,
"author": "DaveK",
"author_id": 4244,
"author_profile": "https://Stackoverflow.com/users/4244",
"pm_score": 1,
"selected": true,
"text": "<p>If I understand correctly what you are trying to do, you can use the StringBuilder. Use the StringBuilder.Append method and a... | 2008/09/09 | [
"https://Stackoverflow.com/questions/50995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5302/"
] | I'm a C# developer who's fumbling in the first VB code he's written since VB6, so if I am asking a rather obvious question, please forgive me.
I decided to experiment with XML Literals to generate some XML code for me, instead of using XMLDocument
I have 2 questions, the second regarding a workaround due to my inability to figure out the first.
1: Ideal solution
I have a Dictionary of ElementName, ElementValue whose KeyValue pairs I was looping over in the hope of generating the values dynamically, but the following syntax dies a horrible death
```
Dim xConnections As XElement
For Each connection As Connection In connections.AsList
For Each kvp As KeyValuePair(Of String, String) In connection.DecompiledElements
xConnections = <Connections> <<%= kvp.Key %>><%= kvp.Value %><\<%=kvp.Key %>> </Connections>
Next
Next
```
I have vague memories of the T4 syntax (the <%=%> syntax) being able to handle more complex operations (rather than direct assignment to the <%= ) and a 'Response.Write' like object to write output to, but I can't remember the details.
2: Cludgy workaround
Instead I thought of building a StringBuilder object and assigning its .ToString to the XElement, but that also failed with a conversion error.
I would prefer to continue using my key value pair concept in example one above, as I feel cludging together a string as in example 2 above is rather nasty, and I really should go back to using XMLDocument if instead.
Any thoughts or assistance greatly appreciated | If I understand correctly what you are trying to do, you can use the StringBuilder. Use the StringBuilder.Append method and append the XmlElement 'OuterXml' property.
For example:
sb.Append(xmlElement.OuterXml) |
51,010 | <p>I have 2 time values which have the type <code>datetime.time</code>. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type <code>datetime.datetime</code> but not for <code>datetime.time</code>. So what is the best way to do this?</p>
| [
{
"answer_id": 51015,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 1,
"selected": false,
"text": "<p>It seems that this isn't supported, since there wouldn't be a good way to deal with overflows in datetime.time. I know t... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51010",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5304/"
] | I have 2 time values which have the type `datetime.time`. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type `datetime.datetime` but not for `datetime.time`. So what is the best way to do this? | Firstly, note that a datetime.time is a time of day, independent of a given day, and so the different between any two datetime.time values is going to be less than 24 hours.
One approach is to convert both datetime.time values into comparable values (such as milliseconds), and find the difference.
```
t1, t2 = datetime.time(...), datetime.time(...)
t1_ms = (t1.hour*60*60 + t1.minute*60 + t1.second)*1000 + t1.microsecond
t2_ms = (t2.hour*60*60 + t2.minute*60 + t2.second)*1000 + t2.microsecond
delta_ms = max([t1_ms, t2_ms]) - min([t1_ms, t2_ms])
```
It's a little lame, but it works. |
51,019 | <p>What does it mean when a <a href="http://en.wikipedia.org/wiki/PostgreSQL" rel="noreferrer">PostgreSQL</a> process is "idle in transaction"?</p>
<p>On a server that I'm looking at, the output of "ps ax | grep postgres" I see 9 PostgreSQL processes that look like the following:</p>
<pre><code>postgres: user db 127.0.0.1(55658) idle in transaction
</code></pre>
<p>Does this mean that some of the processes are hung, waiting for a transaction to be committed? Any pointers to relevant documentation are appreciated.</p>
| [
{
"answer_id": 51058,
"author": "Anonymoose",
"author_id": 2391,
"author_profile": "https://Stackoverflow.com/users/2391",
"pm_score": 7,
"selected": true,
"text": "<p>The <a href=\"http://www.postgresql.org/docs/8.3/interactive/monitoring-ps.html\" rel=\"noreferrer\">PostgreSQL manual</... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4883/"
] | What does it mean when a [PostgreSQL](http://en.wikipedia.org/wiki/PostgreSQL) process is "idle in transaction"?
On a server that I'm looking at, the output of "ps ax | grep postgres" I see 9 PostgreSQL processes that look like the following:
```
postgres: user db 127.0.0.1(55658) idle in transaction
```
Does this mean that some of the processes are hung, waiting for a transaction to be committed? Any pointers to relevant documentation are appreciated. | The [PostgreSQL manual](http://www.postgresql.org/docs/8.3/interactive/monitoring-ps.html) indicates that this means the transaction is open (inside BEGIN) and idle. It's most likely a user connected using the monitor who is thinking or typing. I have plenty of those on my system, too.
If you're using Slony for replication, however, the [Slony-I FAQ](http://slony1.projects.postgresql.org/slony1-1.2.6/doc/adminguide/faq.html) suggests `idle in transaction` may mean that the network connection was terminated abruptly. Check out the discussion in that FAQ for more details. |
51,028 | <p>How do I create a background process with Haskell on windows without a visible command window being created?</p>
<p>I wrote a Haskell program that runs backup processes periodically but every time I run it, a command window opens up to the top of all the windows. I would like to get rid of this window. What is the simplest way to do this?</p>
| [
{
"answer_id": 51049,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 0,
"selected": false,
"text": "<p>The simplest way I can think of is to run the rsync command from within a Windows Shell script (vbs or cmd).</p>\n"
},... | 2008/09/09 | [
"https://Stackoverflow.com/questions/51028",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5304/"
] | How do I create a background process with Haskell on windows without a visible command window being created?
I wrote a Haskell program that runs backup processes periodically but every time I run it, a command window opens up to the top of all the windows. I would like to get rid of this window. What is the simplest way to do this? | You should really tell us how you are trying to do this currently, but on my system (using linux) the following snippet will run a command without opening a new terminal window. It should work the same way on windows.
```
module Main where
import System
import System.Process
import Control.Monad
main :: IO ()
main = do
putStrLn "Running command..."
pid <- runCommand "mplayer song.mp3" -- or whatever you want
replicateM_ 10 $ putStrLn "Doing other stuff"
waitForProcess pid >>= exitWith
``` |