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
102,631
<p>I have had thoughts of trying to write a simple crawler that might crawl and produce a list of its findings for our NPO's websites and content.</p> <p>Does anybody have any thoughts on how to do this? Where do you point the crawler to get started? How does it send back its findings and still keep crawling? How does it know what it finds, etc,etc.</p>
[ { "answer_id": 102665, "author": "whatsisname", "author_id": 8159, "author_profile": "https://Stackoverflow.com/users/8159", "pm_score": 0, "selected": false, "text": "<p>Use wget, do a recursive web suck, which will dump all the files onto your harddrive, then write another script to go...
2008/09/19
[ "https://Stackoverflow.com/questions/102631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have had thoughts of trying to write a simple crawler that might crawl and produce a list of its findings for our NPO's websites and content. Does anybody have any thoughts on how to do this? Where do you point the crawler to get started? How does it send back its findings and still keep crawling? How does it know what it finds, etc,etc.
You'll be reinventing the wheel, to be sure. But here's the basics: * A list of unvisited URLs - seed this with one or more starting pages * A list of visited URLs - so you don't go around in circles * A set of rules for URLs you're not interested in - so you don't index the whole Internet Put these in persistent storage, so you can stop and start the crawler without losing state. Algorithm is: ``` while(list of unvisited URLs is not empty) { take URL from list remove it from the unvisited list and add it to the visited list fetch content record whatever it is you want to about the content if content is HTML { parse out URLs from links foreach URL { if it matches your rules and it's not already in either the visited or unvisited list add it to the unvisited list } } } ```
102,690
<p>This question comes out of the discussion on <a href="https://stackoverflow.com/questions/101825/whats-the-best-way-of-using-a-pair-triple-etc-of-values-as-one-value-in-c">tuples</a>.</p> <p>I started thinking about the hash code that a tuple should have. What if we will accept KeyValuePair class as a tuple? It doesn't override the GetHashCode() method, so probably it won't be aware of the hash codes of it's "children"... So, run-time will call Object.GetHashCode(), which is not aware of the real object structure.</p> <p>Then we can make two instances of some reference type, which are actually Equal, because of the overloaded GetHashCode() and Equals(). And use them as "children" in tuples to "cheat" the dictionary.</p> <p>But it doesn't work! Run-time somehow figures out the structure of our tuple and calls the overloaded GetHashCode of our class!</p> <p>How does it work? What's the analysis made by Object.GetHashCode()? </p> <p>Can it affect the performance in some bad scenario, when we use some complicated keys? (probably, impossible scenario... but still)</p> <p>Consider this code as an example:</p> <pre><code>namespace csharp_tricks { class Program { class MyClass { int keyValue; int someInfo; public MyClass(int key, int info) { keyValue = key; someInfo = info; } public override bool Equals(object obj) { MyClass other = obj as MyClass; if (other == null) return false; return keyValue.Equals(other.keyValue); } public override int GetHashCode() { return keyValue.GetHashCode(); } } static void Main(string[] args) { Dictionary&lt;object, object&gt; dict = new Dictionary&lt;object, object&gt;(); dict.Add(new KeyValuePair&lt;MyClass,object&gt;(new MyClass(1, 1), 1), 1); //here we get the exception -- an item with the same key was already added //but how did it figure out the hash code? dict.Add(new KeyValuePair&lt;MyClass,object&gt;(new MyClass(1, 2), 1), 1); return; } } } </code></pre> <p><strong>Update</strong> I think I've found an explanation for this as stated below in my answer. The main outcomes of it are:</p> <ul> <li>Be careful with your keys and their hash codes :-)</li> <li>For complicated dictionary keys you must override Equals() and GetHashCode() correctly.</li> </ul>
[ { "answer_id": 102757, "author": "Dan Blair", "author_id": 1327, "author_profile": "https://Stackoverflow.com/users/1327", "pm_score": 0, "selected": false, "text": "<p>I don't have the book reference anymore, and I'll have to find it just to confirm, but I thought the default base hash ...
2008/09/19
[ "https://Stackoverflow.com/questions/102690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2351099/" ]
This question comes out of the discussion on [tuples](https://stackoverflow.com/questions/101825/whats-the-best-way-of-using-a-pair-triple-etc-of-values-as-one-value-in-c). I started thinking about the hash code that a tuple should have. What if we will accept KeyValuePair class as a tuple? It doesn't override the GetHashCode() method, so probably it won't be aware of the hash codes of it's "children"... So, run-time will call Object.GetHashCode(), which is not aware of the real object structure. Then we can make two instances of some reference type, which are actually Equal, because of the overloaded GetHashCode() and Equals(). And use them as "children" in tuples to "cheat" the dictionary. But it doesn't work! Run-time somehow figures out the structure of our tuple and calls the overloaded GetHashCode of our class! How does it work? What's the analysis made by Object.GetHashCode()? Can it affect the performance in some bad scenario, when we use some complicated keys? (probably, impossible scenario... but still) Consider this code as an example: ``` namespace csharp_tricks { class Program { class MyClass { int keyValue; int someInfo; public MyClass(int key, int info) { keyValue = key; someInfo = info; } public override bool Equals(object obj) { MyClass other = obj as MyClass; if (other == null) return false; return keyValue.Equals(other.keyValue); } public override int GetHashCode() { return keyValue.GetHashCode(); } } static void Main(string[] args) { Dictionary<object, object> dict = new Dictionary<object, object>(); dict.Add(new KeyValuePair<MyClass,object>(new MyClass(1, 1), 1), 1); //here we get the exception -- an item with the same key was already added //but how did it figure out the hash code? dict.Add(new KeyValuePair<MyClass,object>(new MyClass(1, 2), 1), 1); return; } } } ``` **Update** I think I've found an explanation for this as stated below in my answer. The main outcomes of it are: * Be careful with your keys and their hash codes :-) * For complicated dictionary keys you must override Equals() and GetHashCode() correctly.
It seems that I have a clue now. I thought KeyValuePair is a reference type, but it is not, it is a struct. And so it uses ValueType.GetHashCode() method. MSDN for it says: "One or more fields of the derived type is used to calculate the return value". If you will take a real reference type as a "tuple-provider" you'll cheat the dictionary (or yourself...). ``` using System.Collections.Generic; namespace csharp_tricks { class Program { class MyClass { int keyValue; int someInfo; public MyClass(int key, int info) { keyValue = key; someInfo = info; } public override bool Equals(object obj) { MyClass other = obj as MyClass; if (other == null) return false; return keyValue.Equals(other.keyValue); } public override int GetHashCode() { return keyValue.GetHashCode(); } } class Pair<T, R> { public T First { get; set; } public R Second { get; set; } } static void Main(string[] args) { var dict = new Dictionary<Pair<int, MyClass>, object>(); dict.Add(new Pair<int, MyClass>() { First = 1, Second = new MyClass(1, 2) }, 1); //this is a pair of the same values as previous! but... no exception this time... dict.Add(new Pair<int, MyClass>() { First = 1, Second = new MyClass(1, 3) }, 1); return; } } } ```
102,720
<p>I just finished a medium sized web site and one thing I noticed about my css organization was that I have a lot of hard coded colour values throughout. This obviously isn't great for maintainability. Generally, when I design a site I pick 3-5 main colours for a theme. I end up setting some default values for paragraphs, links, etc... at the beginning of my main css, but some components will change the colour (like the legend tag for example) and require me to restyle with the colour I wanted. How do you avoid this? I was thinking of creating separate rules for each colour and just use those when I need to restyle.</p> <p>i.e.</p> <pre><code>.color1 { color: #3d444d; } </code></pre>
[ { "answer_id": 102791, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 0, "selected": false, "text": "<p>You could have a colours.css file with just the colours/images for each tag in.\nThen you can change the colours just by...
2008/09/19
[ "https://Stackoverflow.com/questions/102720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12529/" ]
I just finished a medium sized web site and one thing I noticed about my css organization was that I have a lot of hard coded colour values throughout. This obviously isn't great for maintainability. Generally, when I design a site I pick 3-5 main colours for a theme. I end up setting some default values for paragraphs, links, etc... at the beginning of my main css, but some components will change the colour (like the legend tag for example) and require me to restyle with the colour I wanted. How do you avoid this? I was thinking of creating separate rules for each colour and just use those when I need to restyle. i.e. ``` .color1 { color: #3d444d; } ```
That's exactly what you should do. The more centralized you can make your css, the easier it will be to make changes in the future. And let's be serious, you will want to change colors in the future. You should almost never hard-code any css into your html, it should **all** be in the css. Also, something I have started doing more often is to layer your css classes on eachother to make it even easier to change colors once... represent everywhere. Sample (random color) css: ``` .main_text {color:#444444;} .secondary_text{color:#765123;} .main_color {background:#343434;} .secondary_color {background:#765sda;} ``` Then some markup, notice how I am using the colors layer with otehr classes, that way I can just change ONE css class: ``` <body class='main_text'> <div class='main_color secondary_text'> <span class='secondary color main_text'>bla bla bla</span> </div> <div class='main_color secondary_text> You get the idea... </div> </body> ``` Remember... inline css = bad (most of the time)
102,742
<p>Like many of you, I use ReSharper to speed up the development process. When you use it to override the equality members of a class, the code-gen it produces for <code>GetHashCode()</code> looks like:</p> <pre class="lang-cs prettyprint-override"><code> public override int GetHashCode() { unchecked { int result = (Key != null ? Key.GetHashCode() : 0); result = (result * 397) ^ (EditableProperty != null ? EditableProperty.GetHashCode() : 0); result = (result * 397) ^ ObjectId; return result; } } </code></pre> <p>Of course I have some of my own members in there, but what I am wanting to know is why 397?</p> <ul> <li>EDIT: So my question would be better worded as, is there something 'special' about the 397 prime number outside of it being a prime number?</li> </ul>
[ { "answer_id": 102878, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 8, "selected": true, "text": "<p>Probably because 397 is a prime of sufficient size to cause the result variable to overflow and mix the bits of the...
2008/09/19
[ "https://Stackoverflow.com/questions/102742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5289/" ]
Like many of you, I use ReSharper to speed up the development process. When you use it to override the equality members of a class, the code-gen it produces for `GetHashCode()` looks like: ```cs public override int GetHashCode() { unchecked { int result = (Key != null ? Key.GetHashCode() : 0); result = (result * 397) ^ (EditableProperty != null ? EditableProperty.GetHashCode() : 0); result = (result * 397) ^ ObjectId; return result; } } ``` Of course I have some of my own members in there, but what I am wanting to know is why 397? * EDIT: So my question would be better worded as, is there something 'special' about the 397 prime number outside of it being a prime number?
Probably because 397 is a prime of sufficient size to cause the result variable to overflow and mix the bits of the hash somewhat, providing a better distribution of hash codes. There's nothing particularly special about 397 that distinguishes it from other primes of the same magnitude.
102,759
<p>Everyone has accidentally forgotten the <code>WHERE</code> clause on a <code>DELETE</code> query and blasted some un-backed up data once or twice. I was pondering that problem, and I was wondering if the solution I came up with is practical.</p> <p>What if, in place of actual <code>DELETE</code> queries, the application and maintenance scripts did something like:</p> <pre><code>UPDATE foo SET to_be_deleted=1 WHERE blah = 50; </code></pre> <p>And then a cron job was set to go through and actually delete everything with the flag? The downside would be that pretty much every other query would need to have <code>WHERE to_be_deleted != 1</code> appended to it, but the upside would be that you'd never mistakenly lose data again. You could see "2,349,325 rows affected" and say, "Hmm, looks like I forgot the <code>WHERE</code> clause," and reset the flags. You could even make the to_be_deleted field a <code>DATE</code> column, so the cron job would check to see if a row's time had come yet.</p> <p>Also, you could remove <code>DELETE</code> permission from the production database user, so even if someone managed to inject some SQL into your site, they wouldn't be able to remove anything.</p> <p>So, my question is: Is this a good idea, or are there pitfalls I'm not seeing? </p>
[ { "answer_id": 102809, "author": "Ken Ray", "author_id": 12253, "author_profile": "https://Stackoverflow.com/users/12253", "pm_score": 1, "selected": false, "text": "<p>You could set up a view on that table that selects WHERE to_be_deleted != 1, and all of your normal selects are done on...
2008/09/19
[ "https://Stackoverflow.com/questions/102759", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16034/" ]
Everyone has accidentally forgotten the `WHERE` clause on a `DELETE` query and blasted some un-backed up data once or twice. I was pondering that problem, and I was wondering if the solution I came up with is practical. What if, in place of actual `DELETE` queries, the application and maintenance scripts did something like: ``` UPDATE foo SET to_be_deleted=1 WHERE blah = 50; ``` And then a cron job was set to go through and actually delete everything with the flag? The downside would be that pretty much every other query would need to have `WHERE to_be_deleted != 1` appended to it, but the upside would be that you'd never mistakenly lose data again. You could see "2,349,325 rows affected" and say, "Hmm, looks like I forgot the `WHERE` clause," and reset the flags. You could even make the to\_be\_deleted field a `DATE` column, so the cron job would check to see if a row's time had come yet. Also, you could remove `DELETE` permission from the production database user, so even if someone managed to inject some SQL into your site, they wouldn't be able to remove anything. So, my question is: Is this a good idea, or are there pitfalls I'm not seeing?
That is fine if you want to do that, but it seems like a lot of work. How many people are manually changing the database? It should be very few, especially if your users have an app to work with. When I work on the production db I put EVERYTHING I do in a transaction so if I mess up I can rollback. Just having a standard practice like that for me has helped me. I don't see anything really wrong with that though other than ever single point of data manipulation in each applicaiton will have to be aware of this functionality and not just the data it wants.
102,850
<p>Doesn't work with other modules, but to give an example. I installed Text::CSV_XS with a CPAN setting:</p> <pre><code>'makepl_arg' =&gt; q[PREFIX=~/lib], </code></pre> <p>When I try running a test.pl script:</p> <blockquote> <p>$ perl test.pl</p> </blockquote> <pre><code>#!/usr/bin/perl use lib "/homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi"; use Text::CSV_XS; print "test"; </code></pre> <p>I get</p> <pre> Can't load '/homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi/auto/Text/CSV_XS/CSV_XS.so' for module Text::CSV_XS: /homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi/auto/Text/CSV_XS/CSV_XS.so: cannot open shared object file: No such file or directory at /www/common/perl/lib/5.8.2/i686-linux/DynaLoader.pm line 229. at test.pl line 6 Compilation failed in require at test.pl line 6. BEGIN failed--compilation aborted at test.pl line 6. </pre> <p>I traced the error back to DynaLoader.pm it happens at this line:</p> <pre><code># Many dynamic extension loading problems will appear to come from # this section of code: XYZ failed at line 123 of DynaLoader.pm. # Often these errors are actually occurring in the initialisation # C code of the extension XS file. Perl reports the error as being # in this perl code simply because this was the last perl code # it executed. my $libref = dl_load_file($file, $module-&gt;dl_load_flags) or croak("Can't load '$file' for module $module: ".dl_error()); </code></pre> <p><b>CSV_XS.so exists in the above directory</b></p>
[ { "answer_id": 103018, "author": "Frosty", "author_id": 7476, "author_profile": "https://Stackoverflow.com/users/7476", "pm_score": 2, "selected": false, "text": "<p>Try this instead:</p>\n\n<pre><code>'makepl_arg' =&gt; q[PREFIX=~/]\n</code></pre>\n\n<p>PREFIX sets the base for all the ...
2008/09/19
[ "https://Stackoverflow.com/questions/102850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10523/" ]
Doesn't work with other modules, but to give an example. I installed Text::CSV\_XS with a CPAN setting: ``` 'makepl_arg' => q[PREFIX=~/lib], ``` When I try running a test.pl script: > > $ perl test.pl > > > ``` #!/usr/bin/perl use lib "/homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi"; use Text::CSV_XS; print "test"; ``` I get ``` Can't load '/homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi/auto/Text/CSV_XS/CSV_XS.so' for module Text::CSV_XS: /homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi/auto/Text/CSV_XS/CSV_XS.so: cannot open shared object file: No such file or directory at /www/common/perl/lib/5.8.2/i686-linux/DynaLoader.pm line 229. at test.pl line 6 Compilation failed in require at test.pl line 6. BEGIN failed--compilation aborted at test.pl line 6. ``` I traced the error back to DynaLoader.pm it happens at this line: ``` # Many dynamic extension loading problems will appear to come from # this section of code: XYZ failed at line 123 of DynaLoader.pm. # Often these errors are actually occurring in the initialisation # C code of the extension XS file. Perl reports the error as being # in this perl code simply because this was the last perl code # it executed. my $libref = dl_load_file($file, $module->dl_load_flags) or croak("Can't load '$file' for module $module: ".dl_error()); ``` **CSV\_XS.so exists in the above directory**
Personally I would suggest to use [local::lib](http://search.cpan.org/dist/local-lib/). :)
102,881
<p>I am running some queries to track down a problem with our backup logs and would like to display datetime fields in 24-hour military time. Is there a simple way to do this? I've tried googling and could find nothing.</p>
[ { "answer_id": 102906, "author": "Nick Craver", "author_id": 13249, "author_profile": "https://Stackoverflow.com/users/13249", "pm_score": 0, "selected": false, "text": "<p>It's not oracle that determines the display of the date, it's the tool you're using to run queries. What are you u...
2008/09/19
[ "https://Stackoverflow.com/questions/102881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
I am running some queries to track down a problem with our backup logs and would like to display datetime fields in 24-hour military time. Is there a simple way to do this? I've tried googling and could find nothing.
``` select to_char(sysdate,'DD/MM/YYYY HH24:MI:SS') from dual; ``` Give the time in 24 hour format. More options are described [here](http://www.oradev.com/oracle_date_format.jsp).
102,964
<p>I have a Java bean like this:</p> <pre><code>class Person { int age; String name; } </code></pre> <p>I'd like to iterate over a collection of these beans in a JSP, showing each person in a HTML table row, and in the last row of the table I'd like to show the total of all the ages.</p> <p>The code to generate the table rows will look something like this:</p> <pre><code>&lt;c:forEach var="person" items="${personList}"&gt; &lt;tr&gt;&lt;td&gt;${person.name}&lt;td&gt;&lt;td&gt;${person.age}&lt;/td&gt;&lt;/tr&gt; &lt;/c:forEach&gt; </code></pre> <p>However, I'm struggling to find a way to calculate the age total that will be shown in the final row <strong>without resorting to scriptlet code</strong>, any suggestions?</p>
[ { "answer_id": 103009, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>It's a bit hacky, but in your controller code you could just create a dummy Person object with the total in it!</p>\n\n<p>H...
2008/09/19
[ "https://Stackoverflow.com/questions/102964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
I have a Java bean like this: ``` class Person { int age; String name; } ``` I'd like to iterate over a collection of these beans in a JSP, showing each person in a HTML table row, and in the last row of the table I'd like to show the total of all the ages. The code to generate the table rows will look something like this: ``` <c:forEach var="person" items="${personList}"> <tr><td>${person.name}<td><td>${person.age}</td></tr> </c:forEach> ``` However, I'm struggling to find a way to calculate the age total that will be shown in the final row **without resorting to scriptlet code**, any suggestions?
***Note:*** I tried combining answers to make a comprehensive list. I mentioned names where appropriate to give credit where it is due. There are many ways to solve this problem, with pros/cons associated with each: **Pure JSP Solution** As ScArcher2 mentioned above, a very easy and simple solution to the problem is to implement it directly in the JSP as so: ``` <c:set var="ageTotal" value="${0}" /> <c:forEach var="person" items="${personList}"> <c:set var="ageTotal" value="${ageTotal + person.age}" /> <tr><td>${person.name}<td><td>${person.age}</td></tr> </c:forEach> ${ageTotal} ``` The problem with this solution is that the JSP becomes confusing to the point where you might as well have introduced scriplets. If you anticipate that everyone looking at the page will be able to follow the rudimentary logic present it is a fine choice. **Pure EL solution** If you're already on EL 3.0 (Java EE 7 / Servlet 3.1), use new support for [streams and lambdas](http://docs.oracle.com/javaee/7/tutorial/jsf-el004.htm): ``` <c:forEach var="person" items="${personList}"> <tr><td>${person.name}<td><td>${person.age}</td></tr> </c:forEach> ${personList.stream().map(person -> person.age).sum()} ``` **JSP EL Functions** Another way to output the total without introducing scriplet code into your JSP is to use an EL function. EL functions allow you to call a public static method in a public class. For example, if you would like to iterate over your collection and sum the values you could define a public static method called sum(List people) in a public class, perhaps called PersonUtils. In your tld file you would place the following declaration: ``` <function> <name>sum</name> <function-class>com.example.PersonUtils</function-class> <function-signature>int sum(java.util.List people)</function-signature> </function> ``` Within your JSP you would write: ``` <%@ taglib prefix="f" uri="/your-tld-uri"%> ... <c:out value="${f:sum(personList)}"/> ``` JSP EL Functions have a few benefits. They allow you to use existing Java methods without the need to code to a specific UI (Custom Tag Libraries). They are also compact and will not confuse a non-programming oriented person. **Custom Tag** Yet another option is to roll your own custom tag. This option will involve the most setup but will give you what I think you are esentially looking for, absolutly no scriptlets. A nice tutorial for using simple custom tags can be found at <http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags5.html#74701> The steps involved include subclassing TagSupport: ``` public PersonSumTag extends TagSupport { private List personList; public List getPersonList(){ return personList; } public void setPersonList(List personList){ this.personList = personList; } public int doStartTag() throws JspException { try { int sum = 0; for(Iterator it = personList.iterator(); it.hasNext()){ Person p = (Person)it.next(); sum+=p.getAge(); } pageContext.getOut().print(""+sum); } catch (Exception ex) { throw new JspTagException("SimpleTag: " + ex.getMessage()); } return SKIP_BODY; } public int doEndTag() { return EVAL_PAGE; } } ``` Define the tag in a tld file: ``` <tag> <name>personSum</name> <tag-class>example.PersonSumTag</tag-class> <body-content>empty</body-content> ... <attribute> <name>personList</name> <required>true</required> <rtexprvalue>true</rtexprvalue> <type>java.util.List</type> </attribute> ... </tag> ``` Declare the taglib on the top of your JSP: ``` <%@ taglib uri="/you-taglib-uri" prefix="p" %> ``` and use the tag: ``` <c:forEach var="person" items="${personList}"> <tr><td>${person.name}<td><td>${person.age}</td></tr> </c:forEach> <p:personSum personList="${personList}"/> ``` **Display Tag** As zmf mentioned earlier, you could also use the display tag, although you will need to include the appropriate libraries: <http://displaytag.sourceforge.net/11/tut_basic.html>
103,000
<p>I need to retrieve a record from a database, display it on a web page (I'm using ASP.NET) but store the ID (primary key) from that record somewhere so I can go back to the database later with that ID (perhaps to do an update).</p> <p>I know there are probably a few ways to do this, such as storing the ID in ViewState or a hidden field, but what is the best method and what are the reasons I might choose this method over any others?</p>
[ { "answer_id": 103024, "author": "Chris James", "author_id": 3193, "author_profile": "https://Stackoverflow.com/users/3193", "pm_score": -1, "selected": false, "text": "<pre><code>Session[\"MyId\"]=myval;\n</code></pre>\n\n<p>It would be a little safer and essentially offers the same mec...
2008/09/19
[ "https://Stackoverflow.com/questions/103000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4605/" ]
I need to retrieve a record from a database, display it on a web page (I'm using ASP.NET) but store the ID (primary key) from that record somewhere so I can go back to the database later with that ID (perhaps to do an update). I know there are probably a few ways to do this, such as storing the ID in ViewState or a hidden field, but what is the best method and what are the reasons I might choose this method over any others?
It depends. Do you care if anyone sees the record id? If you do then both hidden fields and viewstate are not suitable; you need to store it in session state, or encrypt viewstate. Do you care if someone submits the form with a bogus id? If you do then you can't use a hidden field (and you need to look at CSRF protection as a bonus) Do you want it unchangable but don't care about it being open to viewing (with some work)? Use viewstate and set enableViewStateMac="true" on your page (or globally) Want it hidden and protected but can't use session state? Encrypt your viewstate by setting the following web.config entries ``` <pages enableViewState="true" enableViewStateMac="true" /> <machineKey ... validation="3DES" /> ```
103,005
<p>Here is my situation:</p> <p>Table one contains a set of data that uses an id for an unique identifier. This table has a one to many relationship with about 6 other tables such that.</p> <p>Given Table 1 with Id of 001: Table 2 might have 3 rows with foreign key: 001 Table 3 might have 12 rows with foreign key: 001 Table 4 might have 0 rows with foreign key: 001 Table 5 might have 28 rows with foreign key: 001</p> <p>I need to write a report that lists all of the rows from Table 1 for a specified time frame followed by all of the data contained in the handful of tables that reference it.</p> <p>My current approach in pseudo code would look like this:</p> <pre><code>select * from table 1 foreach(result) { print result; select * from table 2 where id = result.id; foreach(result2) { print result2; } select * from table 3 where id = result.id foreach(result3) { print result3; } //continued for each table } </code></pre> <p>This means that the single report can run in the neighbor hood of 1000 queries. I know this is excessive however my sql-fu is a little weak and I could use some help. </p>
[ { "answer_id": 103044, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 2, "selected": false, "text": "<p>LEFT OUTER JOIN Tables2-N on Table1</p>\n\n<pre><code>SELECT Table1.*, Table2.*, Table3.*, Table4.*, Table5.*...
2008/09/19
[ "https://Stackoverflow.com/questions/103005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2246765/" ]
Here is my situation: Table one contains a set of data that uses an id for an unique identifier. This table has a one to many relationship with about 6 other tables such that. Given Table 1 with Id of 001: Table 2 might have 3 rows with foreign key: 001 Table 3 might have 12 rows with foreign key: 001 Table 4 might have 0 rows with foreign key: 001 Table 5 might have 28 rows with foreign key: 001 I need to write a report that lists all of the rows from Table 1 for a specified time frame followed by all of the data contained in the handful of tables that reference it. My current approach in pseudo code would look like this: ``` select * from table 1 foreach(result) { print result; select * from table 2 where id = result.id; foreach(result2) { print result2; } select * from table 3 where id = result.id foreach(result3) { print result3; } //continued for each table } ``` This means that the single report can run in the neighbor hood of 1000 queries. I know this is excessive however my sql-fu is a little weak and I could use some help.
LEFT OUTER JOIN Tables2-N on Table1 ``` SELECT Table1.*, Table2.*, Table3.*, Table4.*, Table5.* FROM Table1 LEFT OUTER JOIN Table2 ON Table1.ID = Table2.ID LEFT OUTER JOIN Table3 ON Table1.ID = Table3.ID LEFT OUTER JOIN Table4 ON Table1.ID = Table4.ID LEFT OUTER JOIN Table5 ON Table1.ID = Table5.ID WHERE (CRITERIA) ```
103,006
<p>I've got a CSV file containing latitude and longitude values, such as:</p> <blockquote> <p>"25°36'55.57""E","45°39'12.52""N"</p> </blockquote> <p>Anyone have a quick and simple piece of C# code to convert this to double values?</p> <p>Thanks</p>
[ { "answer_id": 103057, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 5, "selected": true, "text": "<p>If you mean C# code to do this:</p>\n\n<p>result = 25 + (36 / 60) + (55.57 / 3600)</p>\n\n<p>First you'll need to parse the ex...
2008/09/19
[ "https://Stackoverflow.com/questions/103006", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5932/" ]
I've got a CSV file containing latitude and longitude values, such as: > > "25°36'55.57""E","45°39'12.52""N" > > > Anyone have a quick and simple piece of C# code to convert this to double values? Thanks
If you mean C# code to do this: result = 25 + (36 / 60) + (55.57 / 3600) First you'll need to parse the expression with Regex or some other mechanism and split it into the individual parts. Then: ``` String hour = "25"; String minute = "36"; String second = "55.57"; Double result = (hour) + (minute) / 60 + (second) / 3600; ``` And of course a switch to flip sign depending on N/S or E/S. Wikipedia has a little on that: > > For calculations, the West/East suffix is replaced by a negative sign in the western hemisphere. Confusingly, the convention of negative for East is also sometimes seen. The preferred convention -- that East be positive -- is consistent with a right-handed Cartesian coordinate system with the North Pole up. A specific longitude may then be combined with a specific latitude (usually positive in the northern hemisphere) to give a precise position on the Earth's surface. > (<http://en.wikipedia.org/wiki/Longitude>) > > >
103,016
<p>When you pipe two process and kill the one at the "output" of the pipe, the first process used to receive the "Broken Pipe" signal, which usually terminated it aswell. E.g. running</p> <pre><code>$&gt; do_something_intensive | less </code></pre> <p>and then exiting <em>less</em> used to return you immediately to a responsive shell, on a SuSE8 or former releases. when i'm trying that today, <em>do_something_intensive</em> is obviously still running until i kill it manually. It seems that something has changed (glib ? shell ?) that makes program ignore "broken pipes" ...</p> <p>Anyone of you has hints on this ? how to restore the former behaviour ? why it has been changed (or why it always existed multiple semantics) ?</p> <p><em>edit</em> : further tests (using strace) reveal that "SIGPIPE" <em>is</em> generated, but that the program is not interrupted. A simple</p> <pre><code>#include &lt;stdio.h&gt; int main() { while(1) printf("dumb test\n"); exit(0); } </code></pre> <p>will go on with an endless</p> <pre><code>--- SIGPIPE (Broken pipe) @ 0 (0) --- write(1, "dumb test\ndumb test\ndumb test\ndu"..., 1024) = -1 EPIPE (Broken pipe) </code></pre> <p>when <em>less</em> is killed. I could for sure program a signal handler in my program and ensure it terminates, but i'm more looking for some environment variable or a shell option that would force programs to terminate on SIGPIPE</p> <p><em>edit again</em>: it seems to be a tcsh-specific issue (bash handles it properly) and terminal-dependent (Eterm 0.9.4)</p>
[ { "answer_id": 103079, "author": "Daniel Papasian", "author_id": 7548, "author_profile": "https://Stackoverflow.com/users/7548", "pm_score": 3, "selected": false, "text": "<p>Well, if there is an attempt to write to a pipe after the reader has gone away, a SIGPIPE signal gets generated. ...
2008/09/19
[ "https://Stackoverflow.com/questions/103016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15304/" ]
When you pipe two process and kill the one at the "output" of the pipe, the first process used to receive the "Broken Pipe" signal, which usually terminated it aswell. E.g. running ``` $> do_something_intensive | less ``` and then exiting *less* used to return you immediately to a responsive shell, on a SuSE8 or former releases. when i'm trying that today, *do\_something\_intensive* is obviously still running until i kill it manually. It seems that something has changed (glib ? shell ?) that makes program ignore "broken pipes" ... Anyone of you has hints on this ? how to restore the former behaviour ? why it has been changed (or why it always existed multiple semantics) ? *edit* : further tests (using strace) reveal that "SIGPIPE" *is* generated, but that the program is not interrupted. A simple ``` #include <stdio.h> int main() { while(1) printf("dumb test\n"); exit(0); } ``` will go on with an endless ``` --- SIGPIPE (Broken pipe) @ 0 (0) --- write(1, "dumb test\ndumb test\ndumb test\ndu"..., 1024) = -1 EPIPE (Broken pipe) ``` when *less* is killed. I could for sure program a signal handler in my program and ensure it terminates, but i'm more looking for some environment variable or a shell option that would force programs to terminate on SIGPIPE *edit again*: it seems to be a tcsh-specific issue (bash handles it properly) and terminal-dependent (Eterm 0.9.4)
Thanks for your advices, the solution is getting closer... According to the manpage of tcsh, "non-login shells inherit the terminate behavior from their parents. Other signals have the values which the shell inherited from its parent." Which suggest my *terminal* is actually the root of the problem ... if it ignored SIGPIPE, the shell itself will ignore SIGPIPE as well ... *edit:* i have the definitive confirmation that the problem only arise with Eterm+tcsh and found a suspiciously missing signal(SIGPIPE,SIG\_DFL) in Eterm source code. I think that close the case.
103,034
<p>I'm having an odd problem with my vs debugger. When running my program under the vs debugger, the debugger does not break on an unhandled exception. Instead control is returned to VS as if the program exited normally. If I look in the output tab, There is a first-chance exeption listed just before the thread termination.</p> <p>I understand how to use the "Exceptions" box from the Debug menu. I have the break on unhandled exceptions checked. If I check first-chance exceptions for the specific exeption that is occuring, the debugger will stop.</p> <p>However, it is my understanding that the debugger should also stop on any 'Unhandled-Exceptions'. It is not doing this for me.</p> <p>Here are the last few lines of my Output tab:</p> <pre><code>A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll The thread 0x60c has exited with code 0 (0x0). The program '[3588] ALMSSecurityManager.vshost.exe: Managed' has exited with code -532459699 (0xe0434f4d). </code></pre> <p>I don't understand why the exception is flagges as a "first chance" exception when it is unhandled.</p> <p>I believe that the 0xe0434f4d exit code is a generic COM error.</p> <p>Any Ideas?</p> <p>Metro.</p>
[ { "answer_id": 103049, "author": "hova", "author_id": 2170, "author_profile": "https://Stackoverflow.com/users/2170", "pm_score": 0, "selected": false, "text": "<p>There are two checkboxes in the \"Exceptions...\" box, I usually have to have them both checked to get it to break on unhand...
2008/09/19
[ "https://Stackoverflow.com/questions/103034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18978/" ]
I'm having an odd problem with my vs debugger. When running my program under the vs debugger, the debugger does not break on an unhandled exception. Instead control is returned to VS as if the program exited normally. If I look in the output tab, There is a first-chance exeption listed just before the thread termination. I understand how to use the "Exceptions" box from the Debug menu. I have the break on unhandled exceptions checked. If I check first-chance exceptions for the specific exeption that is occuring, the debugger will stop. However, it is my understanding that the debugger should also stop on any 'Unhandled-Exceptions'. It is not doing this for me. Here are the last few lines of my Output tab: ``` A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll The thread 0x60c has exited with code 0 (0x0). The program '[3588] ALMSSecurityManager.vshost.exe: Managed' has exited with code -532459699 (0xe0434f4d). ``` I don't understand why the exception is flagges as a "first chance" exception when it is unhandled. I believe that the 0xe0434f4d exit code is a generic COM error. Any Ideas? Metro.
If you're on a 64-bit OS, there's a pretty good chance you're being bitten by an OS-level behavior that causes exceptions to disappear. The most reliable way to reproduce it is to make a new WinForm application that simply throws an exception in OnLoad; it will appear to not get thrown. Take a look at these: 1. Visual Studio doesn't break on unhandled exception with windows 64-bit * http: // social.msdn.microsoft.com/Forums/en/vsdebug/thread/69a0b831-7782-4bd9-b910-25c85f18bceb 2. [The case of the disappearing OnLoad exception](http://blog.paulbetts.org/index.php/2010/07/20/the-case-of-the-disappearing-onload-exception-user-mode-callback-exceptions-in-x64/) 3. Silent exceptions on x64 development machines (Microsoft Connect) * https: // connect.microsoft.com/VisualStudio/feedback/details/357311/silent-exceptions-on-x64-development-machines The first is what I found from Google (after this thread didn't help), and that thread led me to the following two. The second has the best explanation, and the third is the Microsoft bug/ticket (that re-affirms that this is "by design" behavior). So, basically, if your application throws an Exception that hits a kernel-mode boundary on its way back up the stack, it gets blocked at that boundary. And the Windows team decided the best way to deal with it was to pretend the exception was handled; execution continues as if everything completed normally. Oh, and this happens *everywhere*. Debug versus Release is irrelevant. .Net vs C++ is irrelevant. This is OS-level behavior. Imagine you have to write some critical data to disk, but it fails on the wrong side of a kernal-mode boundary. Other code tries to use it later and, if you're lucky, you detect something's wrong with the data ...but why? I bet you never consider that your application failed to write the data---because you expected an exception would be thrown. Jerks.
103,136
<p>I am trying to execute some stored procedures in groovy way. I am able to do it quite easily by using straight JDBC but this does not seem in the spirit of Grails.</p> <p>I am trying to call the stored procedure as:</p> <pre><code>sql.query( "{call web_GetCityStateByZip(?,?,?,?,?)}",[params.postalcode, sql.out(java.sql.Types.VARCHAR), sql.out(java.sql.Types.VARCHAR), sql.out(java.sql.Types.INTEGER), sql.out(java.sql.Types.VARCHAR)]) { rs -&gt; params.city = rs.getString(2) params.state = rs.getString(3) } </code></pre> <p>I tried various ways like <code>sql.call</code>. I was trying to get output variable value after this.</p> <p>Everytime error:</p> <pre><code>Message: Cannot register out parameter. Caused by: java.sql.SQLException: Cannot register out parameter. Class: SessionExpirationFilter </code></pre> <p>but this does not seem to work.</p> <p>Can anyone point me in the right direction?</p>
[ { "answer_id": 107518, "author": "Internet Friend", "author_id": 18037, "author_profile": "https://Stackoverflow.com/users/18037", "pm_score": 1, "selected": false, "text": "<p>This is still unanswered, so I did a bit of digging although I don't fully understand the problem. The followin...
2008/09/19
[ "https://Stackoverflow.com/questions/103136", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am trying to execute some stored procedures in groovy way. I am able to do it quite easily by using straight JDBC but this does not seem in the spirit of Grails. I am trying to call the stored procedure as: ``` sql.query( "{call web_GetCityStateByZip(?,?,?,?,?)}",[params.postalcode, sql.out(java.sql.Types.VARCHAR), sql.out(java.sql.Types.VARCHAR), sql.out(java.sql.Types.INTEGER), sql.out(java.sql.Types.VARCHAR)]) { rs -> params.city = rs.getString(2) params.state = rs.getString(3) } ``` I tried various ways like `sql.call`. I was trying to get output variable value after this. Everytime error: ``` Message: Cannot register out parameter. Caused by: java.sql.SQLException: Cannot register out parameter. Class: SessionExpirationFilter ``` but this does not seem to work. Can anyone point me in the right direction?
This is still unanswered, so I did a bit of digging although I don't fully understand the problem. The following turned up from the Groovy source, perhaps it's of some help: This line seems to be the origin of the exception: <http://groovy.codehaus.org/xref/groovy/sql/Sql.html#1173> This would seem to indicate that you have a Statement object implementing PreparedStatement, when you need the subinterface CallableStatement, which has the registerOutParameter() method which should be ultimately invoked.
103,157
<p>Can someone please remind me how to create a .Net class from an XML file?<br></p> <p>I would prefer the batch commands, or a way to integrate it into the shell.<br></p> <p>Thanks!</p>
[ { "answer_id": 103191, "author": "Quintin Robinson", "author_id": 12707, "author_profile": "https://Stackoverflow.com/users/12707", "pm_score": 0, "selected": false, "text": "<p>You might be able to use the xsd.exe tool to generate a class, otherwise you probably have to implement a cust...
2008/09/19
[ "https://Stackoverflow.com/questions/103157", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14484/" ]
Can someone please remind me how to create a .Net class from an XML file? I would prefer the batch commands, or a way to integrate it into the shell. Thanks!
The below batch will create a .Net **Class** from **XML** in the current directory. So... XML -> XSD -> VB (Feel free to substitute CS for Language) Create a **Convert2Class.Bat** in the %UserProfile%\SendTo directory. Then copy/save the below: ``` @Echo off Set XsdExePath="C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\XSD.exe" Set Language=VB %~d1 CD %~d1%~p1 %XsdExePath% "%~n1.xml" /nologo %XsdExePath% "%~n1.xsd" /nologo /c /language:%Language% ``` Works on my machine - Good Luck!!
103,177
<p>How do you enumerate the fields of a certificate help in a store. Specifically, I am trying to enumerate the fields of personal certificates issued to the logged on user.</p>
[ { "answer_id": 103228, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 1, "selected": false, "text": "<p>See <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509store.aspx\"...
2008/09/19
[ "https://Stackoverflow.com/questions/103177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How do you enumerate the fields of a certificate help in a store. Specifically, I am trying to enumerate the fields of personal certificates issued to the logged on user.
See <http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509store.aspx> ``` using System.Security.Cryptography.X509Certificates; ... var store = new X509Store(StoreName.My); foreach(var cert in store.Certificates) ... ```
103,179
<p>I know I can specify one for each form, or for the root form and then it'll cascade through to all of the children forms, but I'd like to have a way of overriding the default Java Coffee Cup for all forms even those I might forget.</p> <p>Any suggestions?</p>
[ { "answer_id": 103223, "author": "Andreas Bakurov", "author_id": 7400, "author_profile": "https://Stackoverflow.com/users/7400", "pm_score": 0, "selected": false, "text": "<p>Extend the JDialog class (for example name it MyDialog) and set the icon in constructor. Then all dialogs should ...
2008/09/19
[ "https://Stackoverflow.com/questions/103179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
I know I can specify one for each form, or for the root form and then it'll cascade through to all of the children forms, but I'd like to have a way of overriding the default Java Coffee Cup for all forms even those I might forget. Any suggestions?
You can make the root form (by which I assume you mean `JFrame`) be your own subclass of `JFrame`, and put standard functionality in its constructor, such as: ``` this.setIconImage(STANDARD_ICON); ``` You can bundle other standard stuff in here too, such as memorizing the frame's window metrics as a user preference, managing splash panes, etc. Any new frames spawned by this one would also be instances of this `JFrame` subclass. The only thing you have to remember is to instantiate your subclass, instead of `JFrame`. I don't think there's any substitute for remembering to do this, but at least now it's a matter of remembering a subclass instead of a `setIconImage` call (among possibly other features).
103,203
<p>We recently had a security audit and it exposed several weaknesses in the systems that are in place here. One of the tasks that resulted from it is that we need to update our partner credentials system make it more secure. </p> <p>The "old" way of doing things was to generate a (bad) password, give it to the partner with an ID and then they would send that ID and a Base 64 encoded copy of that password in with all of their XML requests over https. We then decode them and validate them.</p> <p>These passwords won't change (because then our partners would have to make coding/config changes to change them and coordinating password expirations with hundreds of partners for multiple environments would be a nightmare) and they don't have to be entered by a human or human readable. I am open to changing this if there is a better but still relatively simple implementation for our partners.</p> <p>Basically it comes down to two things: I need a more secure Java password generation system and to ensure that they are transmitted in a secure way.</p> <p>I've found a few hand-rolled password generators but nothing that really stood out as a standard way to do this (maybe for good reason). There may also be a more secure way to transmit them than simple Base 64 encoding over https. </p> <p>What would you do for the password generator and do you think that the transmission method in place is secure enough for it?</p> <p>Edit: The XML comes in a SOAP message and the credentials are in the header not in the XML itself. Also, since the passwords are a one-off operation for each partner when we set them up we're not too worried about efficiency of the generator.</p>
[ { "answer_id": 103648, "author": "delfuego", "author_id": 16414, "author_profile": "https://Stackoverflow.com/users/16414", "pm_score": 0, "selected": false, "text": "<p>I'm unclear why transmitting the passwords over SSL -- via HTTPS -- is being considered \"insecure\" by your audit tea...
2008/09/19
[ "https://Stackoverflow.com/questions/103203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12662/" ]
We recently had a security audit and it exposed several weaknesses in the systems that are in place here. One of the tasks that resulted from it is that we need to update our partner credentials system make it more secure. The "old" way of doing things was to generate a (bad) password, give it to the partner with an ID and then they would send that ID and a Base 64 encoded copy of that password in with all of their XML requests over https. We then decode them and validate them. These passwords won't change (because then our partners would have to make coding/config changes to change them and coordinating password expirations with hundreds of partners for multiple environments would be a nightmare) and they don't have to be entered by a human or human readable. I am open to changing this if there is a better but still relatively simple implementation for our partners. Basically it comes down to two things: I need a more secure Java password generation system and to ensure that they are transmitted in a secure way. I've found a few hand-rolled password generators but nothing that really stood out as a standard way to do this (maybe for good reason). There may also be a more secure way to transmit them than simple Base 64 encoding over https. What would you do for the password generator and do you think that the transmission method in place is secure enough for it? Edit: The XML comes in a SOAP message and the credentials are in the header not in the XML itself. Also, since the passwords are a one-off operation for each partner when we set them up we're not too worried about efficiency of the generator.
### Password Generation As far as encoding a password for transmission, the only encoding that will truly add security is encryption. Using Base-64 or hexadecimal isn't for security, but just to be able to include it in a text format like XML. Entropy is used to measure password quality. So, choosing each bit with a random "coin-flip" will give you the best quality password. You'd want passwords to be as strong as other cryptographic keys, so I'd recommend a minimum of 128 bits of entropy. There are two easy methods, depending on how you want to encode the password as text (which really doesn't matter from a security standpoint). For [Base-64](http://en.wikipedia.org/wiki/Base64), use something like this: ``` SecureRandom rnd = new SecureRandom(); /* Byte array length is multiple of LCM(log2(64), 8) / 8 = 3. */ byte[] password = new byte[18]; rnd.nextBytes(password); String encoded = Base64.encode(password); ``` The following doesn't require you to come up with a Base-64 encoder. The resulting encoding is not as compact (26 characters instead of 24) and the password doesn't have as much entropy. (But 130 bits is already a lot, comparable to a password of at least 30 characters chosen by a human.) ``` SecureRandom rnd = new SecureRandom(); /* Bit length is multiple of log2(32) = 5. */ String encoded = new BigInteger(130, rnd).toString(32); ``` Creating new SecureRandom objects is computationally expensive, so if you are going to generate passwords frequently, you may want to create one instance and keep it around. ### A Better Approach Embedding the password in the XML itself seems like a mistake. First of all, it seems like you would want to authenticate a sender before processing any documents they send you. Suppose I hate your guts, and start sending you giant XML files to execute a denial of service attack. Do you want to have to parse the XML only to find out that I'm not a legitimate partner? Wouldn't it be better if the servlet just rejected requests from unauthenticated users up front? Second, the passwords of your legitimate partners were protected during transmission by HTTPS, but now they are likely stored "in the clear" on your system somewhere. That's bad security. A better approach would be to authenticate partners when they send you a document with credentials in the HTTP request headers. If you only allow HTTPS, you can take the password out of the document completely and put it into an [HTTP "Basic" authentication](http://www.ietf.org/rfc/rfc2617.txt) header instead. It's secured by SSL during transmission, and not stored on your system in the clear (you only store a one-way hash for authentication purposes). HTTP Basic authentication is simple, widely supported, and will be much easier for you and your partners to implement than SSL client certificates. ### Protecting Document Content If the content of the documents themselves is sensitive, they really should be encrypted by the sender, and stored by you in their encrypted form. The best way to do this is with public key cryptography, but that would be a subject for another question.
103,261
<p>I recently inherited an old visual basic 6/ crystal reports project which connects to a sql server database. The error message I get (Error# -2147191803 A String is required here) when I attempt to run the project seems to be narrowed down to the .Printout command in the following code: </p> <pre> 'Login to database Set Tables = Report.Database.Tables Set Table = Tables.Item(1) Table.SetLogOnInfo ConnName, DBName, user, pass DomainName = CStr(selected) 'Set parameter Fields 'Declare parameter holders Set ParamDefs = Report.ParameterFields 'Store parameter objects For Each ParamDef In ParamDefs With ParamDef MsgBox("DomainName : " + DomainName) Select Case .ParameterFieldName Case "Company Name" .SetCurrentValue DomainName End Select Select Case .Name Case "{?Company Name}" .SetCurrentValue DomainName End Select 'Flag to see what is assigned to Current value MsgBox("paramdef: " + ParamDef.Value) End With Next Report.EnableParameterPrompting = False Screen.MousePointer = vbHourglass 'CRViewer1.ReportSource = Report 'CRViewer1.ViewReport test = 1 **Report.PrintOut** test = test + 3 currenttime = Str(Now) currenttime = Replace(currenttime, "/", "-") currenttime = Replace(currenttime, ":", "-") DomainName = Replace(DomainName, ".", "") startName = mPath + "\crysta~1.pdf" endName = mPath + "\" + DomainName + "\" + DomainName + " " + currenttime + ".pdf" rc = MsgBox("Wait for PDF job to finish", vbInformation, "H/W Report") Name startName As endName Screen.MousePointer = vbDefault End If </pre> <p>During the run, the form shows up, the ParamDef variable sets the "company name" and when it gets to the <strong>Report.PrintOut</strong> line which prompts to print, it throws the error. I'm guessing the crystal report isn't receiving the "Company Name" to properly run the crystal report. Does any one know how to diagnose this...either on the vb6 or crystal reports side to determine what I'm missing here? </p> <p><strong>UPDATE:</strong> </p> <ul> <li>inserted CStr(selected) to force DomainName to be a string</li> <li>inserted msgboxes into the for loop above and below the .setcurrentvalue line </li> <li>inserted Case "{?Company Name}" statement to see if that helps setting the value</li> <li>tried .AddCurrentValue and .SetCurrentValue functions as suggested by other forum websites</li> <li>ruled out that it was my development environement..loaded it on another machine with the exact same vb6 crystal reports 8.5 running on winxp prof sp2 and the same errors come up. </li> </ul> <p>and when I run the MsgBox(ParamDef.Value) and it also turns up blank with the same missing string error. I also can't find any documentation on the craxdrt.ParameterFieldDefinition class to see what other hidden functions are available. When I see the list of methods and property variables, it doesn't list SetCurrentValue as one of the functions. Any ideas on this?</p>
[ { "answer_id": 103346, "author": "Arthur Miller", "author_id": 13085, "author_profile": "https://Stackoverflow.com/users/13085", "pm_score": 1, "selected": false, "text": "<p>What is the value of your selected variable?</p>\n\n<p>Table.SetLogOnInfo ConnName, DBName, user, pass<br />\n<st...
2008/09/19
[ "https://Stackoverflow.com/questions/103261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18853/" ]
I recently inherited an old visual basic 6/ crystal reports project which connects to a sql server database. The error message I get (Error# -2147191803 A String is required here) when I attempt to run the project seems to be narrowed down to the .Printout command in the following code: ``` 'Login to database Set Tables = Report.Database.Tables Set Table = Tables.Item(1) Table.SetLogOnInfo ConnName, DBName, user, pass DomainName = CStr(selected) 'Set parameter Fields 'Declare parameter holders Set ParamDefs = Report.ParameterFields 'Store parameter objects For Each ParamDef In ParamDefs With ParamDef MsgBox("DomainName : " + DomainName) Select Case .ParameterFieldName Case "Company Name" .SetCurrentValue DomainName End Select Select Case .Name Case "{?Company Name}" .SetCurrentValue DomainName End Select 'Flag to see what is assigned to Current value MsgBox("paramdef: " + ParamDef.Value) End With Next Report.EnableParameterPrompting = False Screen.MousePointer = vbHourglass 'CRViewer1.ReportSource = Report 'CRViewer1.ViewReport test = 1 **Report.PrintOut** test = test + 3 currenttime = Str(Now) currenttime = Replace(currenttime, "/", "-") currenttime = Replace(currenttime, ":", "-") DomainName = Replace(DomainName, ".", "") startName = mPath + "\crysta~1.pdf" endName = mPath + "\" + DomainName + "\" + DomainName + " " + currenttime + ".pdf" rc = MsgBox("Wait for PDF job to finish", vbInformation, "H/W Report") Name startName As endName Screen.MousePointer = vbDefault End If ``` During the run, the form shows up, the ParamDef variable sets the "company name" and when it gets to the **Report.PrintOut** line which prompts to print, it throws the error. I'm guessing the crystal report isn't receiving the "Company Name" to properly run the crystal report. Does any one know how to diagnose this...either on the vb6 or crystal reports side to determine what I'm missing here? **UPDATE:** * inserted CStr(selected) to force DomainName to be a string * inserted msgboxes into the for loop above and below the .setcurrentvalue line * inserted Case "{?Company Name}" statement to see if that helps setting the value * tried .AddCurrentValue and .SetCurrentValue functions as suggested by other forum websites * ruled out that it was my development environement..loaded it on another machine with the exact same vb6 crystal reports 8.5 running on winxp prof sp2 and the same errors come up. and when I run the MsgBox(ParamDef.Value) and it also turns up blank with the same missing string error. I also can't find any documentation on the craxdrt.ParameterFieldDefinition class to see what other hidden functions are available. When I see the list of methods and property variables, it doesn't list SetCurrentValue as one of the functions. Any ideas on this?
What is the value of your selected variable? Table.SetLogOnInfo ConnName, DBName, user, pass **DomainName = selected** 'Set parameter Fields If it is not a string, then that might be the problem. Crystal expects a string variable and when it doesn't receive what it expects, it throws errors.
103,280
<p>If by some miracle a segfault occurs in our program, I want to catch the SIGSEGV and let the user (possibly a GUI client) know with a single return code that a serious problem has occurred. At the same time I would like to display information on the command line to show which signal was caught.</p> <p>Today our signal handler looks as follows:</p> <pre><code>void catchSignal (int reason) { std :: cerr &lt;&lt; "Caught a signal: " &lt;&lt; reason &lt;&lt; std::endl; exit (1); } </code></pre> <p>I can hear the screams of horror with the above, as I have read from this <a href="http://groups.google.com/group/gnu.gcc.help/browse_thread/thread/6184795b39508519/f775c1f48284b212?lnk=gst&amp;q=deadlock#" rel="nofollow noreferrer">thread</a> that it is evil to call a non-reentrant function from a signal handler.</p> <p>Is there a portable way to handle the signal and provide information to users?</p> <p><strong>EDIT:</strong> Or at least portable within the POSIX framework?</p>
[ { "answer_id": 103553, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 0, "selected": false, "text": "<p>Write a launcher program to run your program and report abnormal exit code to the user.</p>\n" }, { "answer_id":...
2008/09/19
[ "https://Stackoverflow.com/questions/103280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11698/" ]
If by some miracle a segfault occurs in our program, I want to catch the SIGSEGV and let the user (possibly a GUI client) know with a single return code that a serious problem has occurred. At the same time I would like to display information on the command line to show which signal was caught. Today our signal handler looks as follows: ``` void catchSignal (int reason) { std :: cerr << "Caught a signal: " << reason << std::endl; exit (1); } ``` I can hear the screams of horror with the above, as I have read from this [thread](http://groups.google.com/group/gnu.gcc.help/browse_thread/thread/6184795b39508519/f775c1f48284b212?lnk=gst&q=deadlock#) that it is evil to call a non-reentrant function from a signal handler. Is there a portable way to handle the signal and provide information to users? **EDIT:** Or at least portable within the POSIX framework?
This [table](http://docs.oracle.com/cd/E19963-01/html/821-1601/gen-61908.html#gen-95948) lists all of the functions that POSIX guarantees to be async-signal-safe and so can be called from a signal handler. By using the 'write' command from this table, the following relatively "ugly" solution hopefully will do the trick: ``` #include <csignal> #ifdef _WINDOWS_ #define _exit _Exit #else #include <unistd.h> #endif #define PRINT_SIGNAL(X) case X: \ write (STDERR_FILENO, #X ")\n" , sizeof(#X ")\n")-1); \ break; void catchSignal (int reason) { char s[] = "Caught signal: ("; write (STDERR_FILENO, s, sizeof(s) - 1); switch (reason) { // These are the handlers that we catch PRINT_SIGNAL(SIGUSR1); PRINT_SIGNAL(SIGHUP); PRINT_SIGNAL(SIGINT); PRINT_SIGNAL(SIGQUIT); PRINT_SIGNAL(SIGABRT); PRINT_SIGNAL(SIGILL); PRINT_SIGNAL(SIGFPE); PRINT_SIGNAL(SIGBUS); PRINT_SIGNAL(SIGSEGV); PRINT_SIGNAL(SIGTERM); } _Exit (1); // 'exit' is not async-signal-safe } ``` **EDIT:** Building on windows. After trying to build this one windows, it appears that 'STDERR\_FILENO' is not defined. From the documentation however its value appears to be '2'. ``` #include <io.h> #define STDIO_FILENO 2 ``` **EDIT:** 'exit' should not be called from the signal handler either! As pointed out by [fizzer](https://stackoverflow.com/questions/103280/portable-way-to-catch-signals-and-report-problem-to-the-user#114413), calling \_Exit in the above is a sledge hammer approach for signals such as HUP and TERM. Ideally, when these signals are caught a flag with "volatile sig\_atomic\_t" type can be used to notify the main program that it should exit. The following I found useful in my searches. 1. [Introduction To Unix Signals Programming](http://users.actcom.co.il/~choo/lupg/tutorials/signals/signals-programming.html) 2. [Extending Traditional Signals](http://docs.oracle.com/cd/E19963-01/html/821-1601/gen-61908.html)
103,281
<p>At the beginning of each PHP page I open up the connection to MySQL, use it throughout the page and close it at the end of the page. However, I often redirect in the middle of the page to another page and so in those cases the connection does not be closed. I understand that this is not bad for performance of the web server since PHP automatically closes all MySQL connections at the end of each page anyway. Are there any other issues here to keep in mind, or is it really true that you don't have to worry about closing your database connections in PHP?</p> <pre><code>$mysqli = new mysqli("localhost", "root", "", "test"); ...do stuff, perhaps redirect to another page... $mysqli->close(); </code></pre>
[ { "answer_id": 103293, "author": "David McLaughlin", "author_id": 3404, "author_profile": "https://Stackoverflow.com/users/3404", "pm_score": 5, "selected": true, "text": "<p>From: <a href=\"http://us3.php.net/manual/en/mysqli.close.php\" rel=\"noreferrer\">http://us3.php.net/manual/en/m...
2008/09/19
[ "https://Stackoverflow.com/questions/103281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
At the beginning of each PHP page I open up the connection to MySQL, use it throughout the page and close it at the end of the page. However, I often redirect in the middle of the page to another page and so in those cases the connection does not be closed. I understand that this is not bad for performance of the web server since PHP automatically closes all MySQL connections at the end of each page anyway. Are there any other issues here to keep in mind, or is it really true that you don't have to worry about closing your database connections in PHP? ``` $mysqli = new mysqli("localhost", "root", "", "test"); ...do stuff, perhaps redirect to another page... $mysqli->close(); ```
From: <http://us3.php.net/manual/en/mysqli.close.php> > > "Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resources to PHP and MySQL faster." > > >
103,298
<p>From managed C++, I am calling an unmanaged C++ method which returns a double. How can I convert this double into a managed string?</p>
[ { "answer_id": 103350, "author": "Scott Nichols", "author_id": 4299, "author_profile": "https://Stackoverflow.com/users/4299", "pm_score": 2, "selected": false, "text": "<p>C++ is definitely not my strongest skillset. Misread the question, but this should convert to a std::string, not e...
2008/09/19
[ "https://Stackoverflow.com/questions/103298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18170/" ]
From managed C++, I am calling an unmanaged C++ method which returns a double. How can I convert this double into a managed string?
I assume something like ``` (gcnew System::Double(d))->ToString() ```
103,312
<p>How can I test for the <code>EOF</code> flag in R? </p> <p>For example:</p> <pre><code>f &lt;- file(fname, "rb") while (???) { a &lt;- readBin(f, "int", n=1) } </code></pre>
[ { "answer_id": 103396, "author": "Ben Hoffstein", "author_id": 4482, "author_profile": "https://Stackoverflow.com/users/4482", "pm_score": 3, "selected": false, "text": "<p>The <a href=\"http://wiki.r-project.org/rwiki/doku.php?id=rdoc:base:readlines\" rel=\"noreferrer\">readLines</a> fu...
2008/09/19
[ "https://Stackoverflow.com/questions/103312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
How can I test for the `EOF` flag in R? For example: ``` f <- file(fname, "rb") while (???) { a <- readBin(f, "int", n=1) } ```
The [readLines](http://wiki.r-project.org/rwiki/doku.php?id=rdoc:base:readlines) function will return a zero-length value when it reaches the EOF.
103,316
<p>In bash, environmental variables will tab-expand correctly when placed after an echo command, for example:</p> <pre><code>echo $HOME </code></pre> <p>But after cd or cat, bash places a \ before the $ sign, like so:</p> <pre><code>cd \$HOME </code></pre> <p>If I use a variable as the second argument to a command, it won't expand at all:</p> <pre><code>cp somefile $HOM </code></pre> <p>What mysterious option do I have in my .bashrc or .inputrc file that is causing me such distress?</p>
[ { "answer_id": 103463, "author": "Brent ", "author_id": 3764, "author_profile": "https://Stackoverflow.com/users/3764", "pm_score": 2, "selected": false, "text": "<p>For the second instance, you can press ESC before tab to solve it.</p>\n\n<p>I don't know the solution to your problem, bu...
2008/09/19
[ "https://Stackoverflow.com/questions/103316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14102/" ]
In bash, environmental variables will tab-expand correctly when placed after an echo command, for example: ``` echo $HOME ``` But after cd or cat, bash places a \ before the $ sign, like so: ``` cd \$HOME ``` If I use a variable as the second argument to a command, it won't expand at all: ``` cp somefile $HOM ``` What mysterious option do I have in my .bashrc or .inputrc file that is causing me such distress?
Try ***complete -r cd*** to remove the special programmatic completion function that many Linux distributions install for the `cd` command. The function adds searching a list of of directories specified in the CDPATH variable to tab completions for `cd`, but at the expense of breaking the default completion behavior. See <http://www.gnu.org/software/bash/manual/bashref.html#Programmable-Completion> for more gory details.
103,325
<p>Given this XML, what XPath returns all elements whose <code>prop</code> attribute contains <code>Foo</code> (the first three nodes):</p> <pre><code>&lt;bla&gt; &lt;a prop="Foo1"/&gt; &lt;a prop="Foo2"/&gt; &lt;a prop="3Foo"/&gt; &lt;a prop="Bar"/&gt; &lt;/bla&gt; </code></pre>
[ { "answer_id": 103364, "author": "toddk", "author_id": 17640, "author_profile": "https://Stackoverflow.com/users/17640", "pm_score": 3, "selected": false, "text": "<p>Have you tried something like:</p>\n\n<p>//a[contains(@prop, \"Foo\")]</p>\n\n<p>I've never used the contains function be...
2008/09/19
[ "https://Stackoverflow.com/questions/103325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
Given this XML, what XPath returns all elements whose `prop` attribute contains `Foo` (the first three nodes): ``` <bla> <a prop="Foo1"/> <a prop="Foo2"/> <a prop="3Foo"/> <a prop="Bar"/> </bla> ```
``` //a[contains(@prop,'Foo')] ``` Works if I use this XML to get results back. ``` <bla> <a prop="Foo1">a</a> <a prop="Foo2">b</a> <a prop="3Foo">c</a> <a prop="Bar">a</a> </bla> ``` Edit: Another thing to note is that while the XPath above will return the correct answer for that particular xml, if you want to guarantee you only get the "a" elements in element "bla", you should as others have mentioned also use ``` /bla/a[contains(@prop,'Foo')] ``` This will search you all "a" elements in your entire xml document, regardless of being nested in a "blah" element ``` //a[contains(@prop,'Foo')] ``` I added this for the sake of thoroughness and in the spirit of stackoverflow. :)
103,382
<p>I'm using managed c++ to implement a method that returns a string. I declare the method in my header file using the following signature:</p> <pre><code>String^ GetWindowText() </code></pre> <p>However, when I'm using this method from C#, the signature is:</p> <pre><code>string GetWindowTextW(); </code></pre> <p>How do I get rid of the extra "W" at the end of the method's name?</p>
[ { "answer_id": 103398, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 3, "selected": true, "text": "<p>To get around the preprocessor hackery of the Windows header files, declare it like this:</p>\n\n<pre><code>#undef GetWindowTe...
2008/09/19
[ "https://Stackoverflow.com/questions/103382", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15157/" ]
I'm using managed c++ to implement a method that returns a string. I declare the method in my header file using the following signature: ``` String^ GetWindowText() ``` However, when I'm using this method from C#, the signature is: ``` string GetWindowTextW(); ``` How do I get rid of the extra "W" at the end of the method's name?
To get around the preprocessor hackery of the Windows header files, declare it like this: ``` #undef GetWindowText String^ GetWindowText() ``` Note that, if you actually use the Win32 or MFC `GetWindowText()` routines in your code, you'll need to either redefine the macro or call them as `GetWindowTextW()`.
103,389
<p>Does anyone know why in Oracle 11g when you do a Count(1) with more than one natural join it does a cartesian join and throws the count way off?</p> <p>Such as </p> <pre><code>SELECT Count(1) FROM record NATURAL join address NATURAL join person WHERE status=1 AND code = 1 AND state = 'TN' </code></pre> <p>This pulls back like 3 million rows when</p> <pre><code>SELECT * FROM record NATURAL join address NATURAL join person WHERE status=1 AND code = 1 AND state = 'TN' </code></pre> <p>pulls back like 36000 rows, which is the correct amount.</p> <p>Am I just missing something?</p> <p>Here are the tables I'm using to get this result.</p> <pre><code>CREATE TABLE addresses ( address_id NUMBER(10,0) NOT NULL, address_1 VARCHAR2(60) NULL, address_2 VARCHAR2(60) NULL, city VARCHAR2(35) NULL, state CHAR(2) NULL, zip VARCHAR2(5) NULL, zip_4 VARCHAR2(4) NULL, county VARCHAR2(35) NULL, phone VARCHAR2(11) NULL, fax VARCHAR2(11) NULL, origin_network NUMBER(3,0) NOT NULL, owner_network NUMBER(3,0) NOT NULL, corrected_address_id NUMBER(10,0) NULL, "HASH" VARCHAR2(200) NULL ); CREATE TABLE rates ( rate_id NUMBER(10,0) NOT NULL, eob VARCHAR2(30) NOT NULL, network_code NUMBER(3,0) NOT NULL, product_code VARCHAR2(2) NOT NULL, rate_type NUMBER(1,0) NOT NULL ); CREATE TABLE records ( pk_unique_id NUMBER(10,0) NOT NULL, rate_id NUMBER(10,0) NOT NULL, address_id NUMBER(10,0) NOT NULL, effective_date DATE NOT NULL, term_date DATE NULL, last_update DATE NULL, status CHAR(1) NOT NULL, network_unique_id VARCHAR2(20) NULL, rate_id_2 NUMBER(10,0) NULL, contracted_by VARCHAR2(50) NULL, contract_version VARCHAR2(5) NULL, bill_address_id NUMBER(10,0) NULL ); </code></pre> <p>I should mention this wasn't a problem in Oracle 9i, but when we switched to 11g it became a problem.</p>
[ { "answer_id": 103467, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": false, "text": "<p>If it happens exactly as you say then it <strong>must</strong> be an optimiser bug, you should report it to Oracle...
2008/09/19
[ "https://Stackoverflow.com/questions/103389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12969/" ]
Does anyone know why in Oracle 11g when you do a Count(1) with more than one natural join it does a cartesian join and throws the count way off? Such as ``` SELECT Count(1) FROM record NATURAL join address NATURAL join person WHERE status=1 AND code = 1 AND state = 'TN' ``` This pulls back like 3 million rows when ``` SELECT * FROM record NATURAL join address NATURAL join person WHERE status=1 AND code = 1 AND state = 'TN' ``` pulls back like 36000 rows, which is the correct amount. Am I just missing something? Here are the tables I'm using to get this result. ``` CREATE TABLE addresses ( address_id NUMBER(10,0) NOT NULL, address_1 VARCHAR2(60) NULL, address_2 VARCHAR2(60) NULL, city VARCHAR2(35) NULL, state CHAR(2) NULL, zip VARCHAR2(5) NULL, zip_4 VARCHAR2(4) NULL, county VARCHAR2(35) NULL, phone VARCHAR2(11) NULL, fax VARCHAR2(11) NULL, origin_network NUMBER(3,0) NOT NULL, owner_network NUMBER(3,0) NOT NULL, corrected_address_id NUMBER(10,0) NULL, "HASH" VARCHAR2(200) NULL ); CREATE TABLE rates ( rate_id NUMBER(10,0) NOT NULL, eob VARCHAR2(30) NOT NULL, network_code NUMBER(3,0) NOT NULL, product_code VARCHAR2(2) NOT NULL, rate_type NUMBER(1,0) NOT NULL ); CREATE TABLE records ( pk_unique_id NUMBER(10,0) NOT NULL, rate_id NUMBER(10,0) NOT NULL, address_id NUMBER(10,0) NOT NULL, effective_date DATE NOT NULL, term_date DATE NULL, last_update DATE NULL, status CHAR(1) NOT NULL, network_unique_id VARCHAR2(20) NULL, rate_id_2 NUMBER(10,0) NULL, contracted_by VARCHAR2(50) NULL, contract_version VARCHAR2(5) NULL, bill_address_id NUMBER(10,0) NULL ); ``` I should mention this wasn't a problem in Oracle 9i, but when we switched to 11g it became a problem.
My advice would be to NOT use NATURAL JOIN. Explicitly define your join conditions to avoid confusion and "hidden bugs". Here is the [official NATURAL JOIN Oracle documentation](http://68.142.116.68/docs/cd/B28359_01/server.111/b28286/statements_10002.htm#sthref9907) and [more discussion](http://awads.net/wp/2006/03/20/back-to-basics-inner-joins/#comment-2837) about this subject.
103,407
<p>When attempting to call functions in <code>math.h</code>, I'm getting link errors like the following </p> <pre><code>undefined reference to sqrt </code></pre> <p>But I'm doing a <code>#include &lt;math.h&gt;</code><br> I'm using gcc and compiling as follows:</p> <pre><code>gcc -Wall -D_GNU_SOURCE blah.c -o blah </code></pre> <p>Why can't the linker find the definition for <code>sqrt</code>?</p>
[ { "answer_id": 103411, "author": "FreeMemory", "author_id": 2132, "author_profile": "https://Stackoverflow.com/users/2132", "pm_score": 2, "selected": false, "text": "<p>You need to link the math library explicitly. Add <code>-lm</code> to the flags you're passing to gcc so that the link...
2008/09/19
[ "https://Stackoverflow.com/questions/103407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2132/" ]
When attempting to call functions in `math.h`, I'm getting link errors like the following ``` undefined reference to sqrt ``` But I'm doing a `#include <math.h>` I'm using gcc and compiling as follows: ``` gcc -Wall -D_GNU_SOURCE blah.c -o blah ``` Why can't the linker find the definition for `sqrt`?
Add -lm to the command when you call gcc: gcc -Wall -D\_GNU\_SOURCE blah.c -o blah -lm This will tell the linker to link with the math library. Including math.h will tell the compiler that the math functions like sqrt() exist, but they are defined in a separate library, which the linker needs to pack with your executable. As FreeMemory pointed out the library is called libm.a . On Unix-like systems, the rule for naming libraries is lib[blah].a . Then if you want to link them to your executable you use -l[blah] .
103,460
<p>I need to get the name of the machine my .NET app is running on. What is the best way to do this?</p>
[ { "answer_id": 103468, "author": "Billy Jo", "author_id": 3447, "author_profile": "https://Stackoverflow.com/users/3447", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.environment.machinename.aspx\" rel=\"nofollow noreferrer\"><cod...
2008/09/19
[ "https://Stackoverflow.com/questions/103460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14101/" ]
I need to get the name of the machine my .NET app is running on. What is the best way to do this?
Whilst others have already said that the [System.Environment.MachineName](http://msdn.microsoft.com/en-us/library/system.environment.machinename.aspx) returns you the name of the machine, beware... That property is only returning the NetBIOS name (and only if your application has EnvironmentPermissionAccess.Read permissions). It is possible for your machine name to exceed the length defined in: ``` MAX_COMPUTERNAME_LENGTH ``` In these cases, System.Environment.MachineName will not return you the correct name! Also note, there are several names your machine could go by and in Win32 there is a method [GetComputerNameEx](http://msdn.microsoft.com/en-us/library/ms724301(VS.85).aspx) that is capable of getting the name matching each of these different name types: * ComputerNameDnsDomain * ComputerNameDnsFullyQualified * ComputerNameDnsHostname * ComputerNameNetBIOS * ComputerNamePhysicalDnsDomain * ComputerNamePhysicalDnsFullyQualified * ComputerNamePhysicalDnsHostname * ComputerNamePhysicalNetBIOS If you require this information, you're likely to need to go to Win32 through p/invoke, such as: ``` class Class1 { enum COMPUTER_NAME_FORMAT { ComputerNameNetBIOS, ComputerNameDnsHostname, ComputerNameDnsDomain, ComputerNameDnsFullyQualified, ComputerNamePhysicalNetBIOS, ComputerNamePhysicalDnsHostname, ComputerNamePhysicalDnsDomain, ComputerNamePhysicalDnsFullyQualified } [DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)] static extern bool GetComputerNameEx(COMPUTER_NAME_FORMAT NameType, [Out] StringBuilder lpBuffer, ref uint lpnSize); [STAThread] static void Main(string[] args) { bool success; StringBuilder name = new StringBuilder(260); uint size = 260; success = GetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNameDnsDomain, name, ref size); Console.WriteLine(name.ToString()); } } ```
103,489
<p>Below is the code I use to build an HTML table on the fly (using JSON data received from the server).</p> <p>I display an animated pleasewait (.gif) graphic while the data is loading. However, the graphic freezes while the JavaScript function is building the table. At first, I was just happy to make this happen (display the table), I guess now I need to work on efficiency. At the very least I need to stop the animated graphic from freezing. I can go to a static "Loading" display, but I would rather make this method work.</p> <p>Suggestions for my pleasewait display? And efficiency? Possibly a better way to build the table? Or maybe not a table, but some other "table" like display</p> <pre><code>var t = eval( "(" + request + ")" ) ; var myTable = '' ; myTable += '&lt;table id="myTable" cellspacing=0 cellpadding=2 border=1&gt;' ; myTable += "&lt;thead&gt;" ; myTable += "&lt;tr&gt;"; for (var i = 0; i &lt; t.hdrs.length; i++) { myTable += "&lt;th&gt;" + header + "&lt;/th&gt;"; } myTable += "&lt;/tr&gt;" ; myTable += "&lt;/thead&gt;" ; myTable += "&lt;tbody&gt;" ; for (var i = 0; i &lt; t.data.length; i++) { myTable += '&lt;tr&gt;'; for (var j = 0; j &lt; t.hdrs.length; j++) { myTable += '&lt;td&gt;'; if (t.data[i][t.hdrs[j]] == "") { myTable += "&amp;nbsp;" ; } else { myTable += t.data[i][t.hdrs[j]] ; } myTable += "&lt;/td&gt;"; } myTable += "&lt;/tr&gt;"; } myTable += "&lt;/tbody&gt;" ; myTable += "&lt;/table&gt;" ; $("#result").append(myTable) ; $("#PleaseWaitGraphic").addClass("hide"); $(".rslt").removeClass("hide") ; </code></pre>
[ { "answer_id": 103527, "author": "Jim", "author_id": 8427, "author_profile": "https://Stackoverflow.com/users/8427", "pm_score": 2, "selected": false, "text": "<p>What you are doing is building a string, and then parsing it all at once upon insertion. What about creating an actual table...
2008/09/19
[ "https://Stackoverflow.com/questions/103489", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
Below is the code I use to build an HTML table on the fly (using JSON data received from the server). I display an animated pleasewait (.gif) graphic while the data is loading. However, the graphic freezes while the JavaScript function is building the table. At first, I was just happy to make this happen (display the table), I guess now I need to work on efficiency. At the very least I need to stop the animated graphic from freezing. I can go to a static "Loading" display, but I would rather make this method work. Suggestions for my pleasewait display? And efficiency? Possibly a better way to build the table? Or maybe not a table, but some other "table" like display ``` var t = eval( "(" + request + ")" ) ; var myTable = '' ; myTable += '<table id="myTable" cellspacing=0 cellpadding=2 border=1>' ; myTable += "<thead>" ; myTable += "<tr>"; for (var i = 0; i < t.hdrs.length; i++) { myTable += "<th>" + header + "</th>"; } myTable += "</tr>" ; myTable += "</thead>" ; myTable += "<tbody>" ; for (var i = 0; i < t.data.length; i++) { myTable += '<tr>'; for (var j = 0; j < t.hdrs.length; j++) { myTable += '<td>'; if (t.data[i][t.hdrs[j]] == "") { myTable += "&nbsp;" ; } else { myTable += t.data[i][t.hdrs[j]] ; } myTable += "</td>"; } myTable += "</tr>"; } myTable += "</tbody>" ; myTable += "</table>" ; $("#result").append(myTable) ; $("#PleaseWaitGraphic").addClass("hide"); $(".rslt").removeClass("hide") ; ```
You basically want to set up your loops so they yield to other threads every so often. Here is some example code from [this article](http://www.julienlecomte.net/blog/2007/10/28/) on the topic of running CPU intensive operations without freezing your UI: ``` function doSomething (progressFn [, additional arguments]) { // Initialize a few things here... (function () { // Do a little bit of work here... if (continuation condition) { // Inform the application of the progress progressFn(value, total); // Process next chunk setTimeout(arguments.callee, 0); } })(); } ``` As far as simplifying the production of HTML in your script, if you're using jQuery, you might give my [Simple Templates](http://plugins.jquery.com/project/simple-templates) plug-in a try. It tidies up the process by cutting down drastically on the number of concatenations you have to do. It performs pretty well, too after I recently did some refactoring that resulted in a pretty big [speed increase](http://andrew.hedges.name/experiments/simple-templates-speed-test/). Here's an example (without doing *all* of the work for you!): ``` var t = eval('(' + request + ')') ; var templates = { tr : '<tr>#{row}</tr>', th : '<th>#{header}</th>', td : '<td>#{cell}</td>' }; var table = '<table><thead><tr>'; $.each(t.hdrs, function (key, val) { table += $.tmpl(templates.th, {header: val}); }); ... ```
103,508
<p>I'm using start.jar and stop.jar to stop and start my jetty instance. I restart by calling stop.jar, then start.jar. The problem is, if I don't sleep long enough between stop.jar and start.jar I start getting these random ClassNotFoundExceptions and the application doesn't work correctly.</p> <p>Sleeping for a longer period of time between stop and start is my current option.</p> <p>I also heard from someone that I should have something that manages my threads so that I end those before jetty finishes. Is this correct? The question I have about this is that stop.jar returns immediately, so it doesn't seem to help me, unless there's something I'm missing. Another option might be to poll the log file, but that's pretty ugly.</p> <p>What's the best way of restarting jetty?</p> <p>Gilbert: The Ant task is definitely not a bad way of doing it. However, it sleeps for a set amount of time, which is exactly what I'm trying to avoid.</p>
[ { "answer_id": 103550, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Did you try JFGI?\nSetting up Ant task that could do the work for you?</p>\n\n<p>This blog post details how to setup target...
2008/09/19
[ "https://Stackoverflow.com/questions/103508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm using start.jar and stop.jar to stop and start my jetty instance. I restart by calling stop.jar, then start.jar. The problem is, if I don't sleep long enough between stop.jar and start.jar I start getting these random ClassNotFoundExceptions and the application doesn't work correctly. Sleeping for a longer period of time between stop and start is my current option. I also heard from someone that I should have something that manages my threads so that I end those before jetty finishes. Is this correct? The question I have about this is that stop.jar returns immediately, so it doesn't seem to help me, unless there's something I'm missing. Another option might be to poll the log file, but that's pretty ugly. What's the best way of restarting jetty? Gilbert: The Ant task is definitely not a bad way of doing it. However, it sleeps for a set amount of time, which is exactly what I'm trying to avoid.
Can you write a shell script that does something like this after calling shutdown and before calling startup? ``` LISTEN_PORT = `netstat -vatn | grep LISTEN| grep 8080 | wc -l ` while [$LISTEN_PORT -ne 0] ; do sleep 1 LISTEN_PORT = `netstat -vatn | grep LISTEN| grep 8080 | wc -l ` done ```
103,512
<p>I've heard that the <code>static_cast</code> function should be preferred to C-style or simple function-style casting. Is this true? Why?</p>
[ { "answer_id": 103529, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 3, "selected": false, "text": "<p>static_cast, aside from manipulating pointers to classes, can also be used to perform conversions explicitly defined in cla...
2008/09/19
[ "https://Stackoverflow.com/questions/103512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11575/" ]
I've heard that the `static_cast` function should be preferred to C-style or simple function-style casting. Is this true? Why?
The main reason is that classic C casts make no distinction between what we call `static_cast<>()`, `reinterpret_cast<>()`, `const_cast<>()`, and `dynamic_cast<>()`. These four things are completely different. A `static_cast<>()` is usually safe. There is a valid conversion in the language, or an appropriate constructor that makes it possible. The only time it's a bit risky is when you cast down to an inherited class; you must make sure that the object is actually the descendant that you claim it is, by means external to the language (like a flag in the object). A `dynamic_cast<>()` is safe as long as the result is checked (pointer) or a possible exception is taken into account (reference). A `reinterpret_cast<>()` (or a `const_cast<>()`) on the other hand is always dangerous. You tell the compiler: "trust me: I know this doesn't look like a `foo` (this looks as if it isn't mutable), but it is". The first problem is that it's almost impossible to tell which one will occur in a C-style cast without looking at large and disperse pieces of code and knowing all the rules. Let's assume these: ``` class CDerivedClass : public CMyBase {...}; class CMyOtherStuff {...} ; CMyBase *pSomething; // filled somewhere ``` Now, these two are compiled the same way: ``` CDerivedClass *pMyObject; pMyObject = static_cast<CDerivedClass*>(pSomething); // Safe; as long as we checked pMyObject = (CDerivedClass*)(pSomething); // Same as static_cast<> // Safe; as long as we checked // but harder to read ``` However, let's see this almost identical code: ``` CMyOtherStuff *pOther; pOther = static_cast<CMyOtherStuff*>(pSomething); // Compiler error: Can't convert pOther = (CMyOtherStuff*)(pSomething); // No compiler error. // Same as reinterpret_cast<> // and it's wrong!!! ``` As you can see, there is no easy way to distinguish between the two situations without knowing a lot about all the classes involved. The second problem is that the C-style casts are too hard to locate. In complex expressions it can be very hard to see C-style casts. It is virtually impossible to write an automated tool that needs to locate C-style casts (for example a search tool) without a full blown C++ compiler front-end. On the other hand, it's easy to search for "static\_cast<" or "reinterpret\_cast<". ``` pOther = reinterpret_cast<CMyOtherStuff*>(pSomething); // No compiler error. // but the presence of a reinterpret_cast<> is // like a Siren with Red Flashing Lights in your code. // The mere typing of it should cause you to feel VERY uncomfortable. ``` That means that, not only are C-style casts more dangerous, but it's a lot harder to find them all to make sure that they are correct.
103,516
<p>Using c#, VS2005, and .NET 2.0. (XP 32 bit) This is a Winforms app that gets called by a VBA addin (.xla) via Interop libraries. This app has been around for a while and works fine when the assembly is compiled and executed anywhere other than my dev machine. On dev it crashes hard (in debugger and just running the object) with "Unhandled exception at 0x... in EXCEL.EXE: 0x...violation reading location 0x...</p> <p>But here's the weird part:</p> <p>The first method in my interface works fine. All the other methods crash as above. Here is an approximation of the code:</p> <pre><code>[Guid("123Fooetc...")] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface IBar { [DispId(1)] void ThisOneWorksFine(Excel.Workbook ActiveWorkBook); [DispId(2)] string Crash1(Excel.Workbook ActiveWorkBook); [DispId(3)] int Crash2(Excel.Workbook activeWorkBook, Excel.Range target, string someStr); } [Guid("345Fooetc..")] [ClassInterface(ClassInterfaceType.None)] [ProgId("MyNameSpace.MyClass")] public class MyClass : IBar { public void ThisOneWorksFine(Excel.Workbook ActiveWorkBook) {...} string Crash1(Excel.Workbook ActiveWorkBook); {...} int Crash2(Excel.Workbook activeWorkBook, Excel.Range target, string someStr); {...} } </code></pre> <p>It seems like some kind of environmental thing. Registry chundered? Could be code bugs, but it works fine elsewhere.</p>
[ { "answer_id": 103538, "author": "Steve Cooper", "author_id": 6722, "author_profile": "https://Stackoverflow.com/users/6722", "pm_score": 0, "selected": false, "text": "<p>Is your dev machine Win64? I've had problems with win64 builds of apps that go away if you set the build platform to...
2008/09/19
[ "https://Stackoverflow.com/questions/103516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12281/" ]
Using c#, VS2005, and .NET 2.0. (XP 32 bit) This is a Winforms app that gets called by a VBA addin (.xla) via Interop libraries. This app has been around for a while and works fine when the assembly is compiled and executed anywhere other than my dev machine. On dev it crashes hard (in debugger and just running the object) with "Unhandled exception at 0x... in EXCEL.EXE: 0x...violation reading location 0x... But here's the weird part: The first method in my interface works fine. All the other methods crash as above. Here is an approximation of the code: ``` [Guid("123Fooetc...")] [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)] public interface IBar { [DispId(1)] void ThisOneWorksFine(Excel.Workbook ActiveWorkBook); [DispId(2)] string Crash1(Excel.Workbook ActiveWorkBook); [DispId(3)] int Crash2(Excel.Workbook activeWorkBook, Excel.Range target, string someStr); } [Guid("345Fooetc..")] [ClassInterface(ClassInterfaceType.None)] [ProgId("MyNameSpace.MyClass")] public class MyClass : IBar { public void ThisOneWorksFine(Excel.Workbook ActiveWorkBook) {...} string Crash1(Excel.Workbook ActiveWorkBook); {...} int Crash2(Excel.Workbook activeWorkBook, Excel.Range target, string someStr); {...} } ``` It seems like some kind of environmental thing. Registry chundered? Could be code bugs, but it works fine elsewhere.
I've had problems in this scenario with Office 2003 in the past. Some things that have helped: * Installing Office 2003 Service Pack 2 stopped some crashes that happened when closing Excel. * Installing Office 2003 Service Pack 3 fixes a bug with using XP styles in a VSTO2005 application (not your case here) * Running the Excel VBA CodeCleaner <http://www.appspro.com/Utilities/CodeCleaner.htm> periodically helps prevent random crashes. * Accessing Excel objects from multiple threads would be dodgy, so I hope you aren't doing that. If you have the possibility you could also try opening a case with Microsoft PSS. They are pretty good if you are able to reproduce the problem. And in most cases, this kind of thing is a bug, so you won't be charged for it :)
103,532
<p>If you need to open a SqlConnection before issuing queries, can you simply handle all non-Open ConnectionStates in the same way? For example:</p> <pre><code> if (connection.State != ConnectionState.Open) { connection.Open(); } </code></pre> <p>I read somewhere that for ConnectionState.Broken the connection needs to be closed before its re-opened. Does anyone have experience with this? Thanks-</p>
[ { "answer_id": 103832, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 3, "selected": false, "text": "<p>This isn't directly answering your question, but the best practice is to open and close a connection for every access to th...
2008/09/19
[ "https://Stackoverflow.com/questions/103532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/815/" ]
If you need to open a SqlConnection before issuing queries, can you simply handle all non-Open ConnectionStates in the same way? For example: ``` if (connection.State != ConnectionState.Open) { connection.Open(); } ``` I read somewhere that for ConnectionState.Broken the connection needs to be closed before its re-opened. Does anyone have experience with this? Thanks-
<http://msdn.microsoft.com/en-us/library/system.data.connectionstate.aspx> Broken connection state does need to be closed and reopened before eligible for continued use. Edit: Unfortunately closing a closed connection will balk as well. You'll need to test the ConnectionState before acting on an unknown connection. Perhaps a short switch statement could do the trick.
103,560
<p>I have an ASP.net application that works fine in the development environment but in the production environment throws the following exception when clicking a link that performs a postback. Any ideas?</p> <blockquote> <p>Invalid postback or callback argument. Event validation is enabled using in configuration or &lt;%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.</p> </blockquote> <p><strong>Edit:</strong> This seems to only be happening when viewed with IE6 but not with IE7, any ideas?</p>
[ { "answer_id": 103599, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": 0, "selected": false, "text": "<p>It seems that the data/controls on the page are changed when the postback occurs. What happens if you turn off the even...
2008/09/19
[ "https://Stackoverflow.com/questions/103560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3111/" ]
I have an ASP.net application that works fine in the development environment but in the production environment throws the following exception when clicking a link that performs a postback. Any ideas? > > Invalid postback or callback argument. > Event validation is enabled using > > in configuration or <%@ Page > EnableEventValidation="true" %> in a > page. For security purposes, this > feature verifies that arguments to > postback or callback events originate > from the server control that > originally rendered them. If the data > is valid and expected, use the > ClientScriptManager.RegisterForEventValidation > method in order to register the > postback or callback data for > validation. > > > **Edit:** This seems to only be happening when viewed with IE6 but not with IE7, any ideas?
Problem description: This is one the common issues that a lot of ASP.NET beginners face, post, and ask about. Typically, they post the error message as below and seek for resolution without sharing much about what they were trying to do. [ArgumentException: Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.] Though, error stack trace itself suggests a quick resolution by setting eventvalidation off, it is not a recommended solution as it opens up a security hole. It is always good to know why it happened and how to solve/handle that root problem. Assessment: Event validation is done to validate if the origin of the event is the related rendered control (and not some cross site script or so). Since control registers its events during rendering, events can be validated during postback or callback (via arguments of \_\_doPostBack). This reduces the risk of unauthorized or malicious postback requests and callbacks. Refer: MSDN: Page.EnableEventValidation Property Based on above, possible scenarios that I have faced or heard that raises the issue in discussion are: Case #1: If we have angular brackets in the request data, it looks like some script tag is being passed to server. Possible Solution: HTML encode the angular brackets with help of JavaScript before submitting the form, i.e., replace “<” with “<” and “>” with “>” ``` function HTMLEncodeAngularBrackets(someString) { var modifiedString = someString.replace("<","&lt;"); modifiedString = modifiedString.replace(">","&gt;"); return modifiedString; } ``` Case #2: If we write client script that changes a control in the client at run time, we might have a dangling event. An example could be having embedded controls where an inner control registers for postback but is hidden at runtime because of an operation done on outer control. This I read about on MSDN blog written by Carlo, when looking for same issue because of multiple form tags. Possible Solution: Manually register control for event validation within Render method of the page. ``` protected override void Render(HtmlTextWriter writer) { ClientScript.RegisterForEventValidation(myButton.UniqueID.ToString()); base.Render(writer); } ``` As said, one of the other common scenario reported (which looks like falls in the this same category) is building a page where one form tag is embedded in another form tag that runs on server. Removing one of them corrects the flow and resolves the issue. Case #3: If we re-define/instantiate controls or commands at runtime on every postback, respective/related events might go for a toss. A simple example could be of re-binding a datagrid on every pageload (including postbacks). Since, on rebind all the controls in grid will have a new ID, during an event triggered by datagrid control, on postback the control ID’s are changed and thus the event might not connect to correct control raising the issue. Possible Solution: This can be simply resolved by making sure that controls are not re-created on every postback (rebind here). Using Page property IsPostback can easily handle it. If you want to create a control on every postback, then it is necessary to make sure that the ID’s are not changed. ``` protected void Page_Load(object sender, EventArgs e) { if(!Page.IsPostback) { // Create controls // Bind Grid } } ``` Conclusion: As said, an easy/direct solution can be adding enableEventValidation=”false” in the Page directive or Web.config file but is not recommended. Based on the implementation and cause, find the root cause and apply the resolution accordingly.
103,561
<p>I am taking on a maintenance team and would like to introduce tools like FxCop and StyleCop to help improve the code and introduce the developers to better programming techniques and standards. Since we are maintaining code and not making significant enhancements, we will probably only deal with a couple of methods/routines at a time when making changes. </p> <p>Is it possible to target FxCop/StyleCop to specific areas of code within Visual Studio to avoid getting overwhelmed with all of the issues that would get raised when analyzing a whole class or project? If it is possible, how do you go about it?</p> <p>Thanks, Matt</p>
[ { "answer_id": 104311, "author": "ripper234", "author_id": 11236, "author_profile": "https://Stackoverflow.com/users/11236", "pm_score": -1, "selected": false, "text": "<p>I would guess that it can't (seems a too-specific need).</p>\n" }, { "answer_id": 168262, "author": "ale...
2008/09/19
[ "https://Stackoverflow.com/questions/103561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3262/" ]
I am taking on a maintenance team and would like to introduce tools like FxCop and StyleCop to help improve the code and introduce the developers to better programming techniques and standards. Since we are maintaining code and not making significant enhancements, we will probably only deal with a couple of methods/routines at a time when making changes. Is it possible to target FxCop/StyleCop to specific areas of code within Visual Studio to avoid getting overwhelmed with all of the issues that would get raised when analyzing a whole class or project? If it is possible, how do you go about it? Thanks, Matt
I am using FxCopCmd.exe (FxCop 1.36) as an external tool with various command line parameters, including this one: ``` /types:<type list> [Short form: /t:<type list>] Analyze only these types and members. ```
103,575
<p>I am trying to validate the WPF form against an object. The validation fires when I type something in the textbox lose focus come back to the textbox and then erase whatever I have written. But if I just load the WPF application and tab off the textbox without writing and erasing anything from the textbox, then it is not fired. </p> <p>Here is the Customer.cs class: </p> <pre><code>public class Customer : IDataErrorInfo { public string FirstName { get; set; } public string LastName { get; set; } public string Error { get { throw new NotImplementedException(); } } public string this[string columnName] { get { string result = null; if (columnName.Equals("FirstName")) { if (String.IsNullOrEmpty(FirstName)) { result = "FirstName cannot be null or empty"; } } else if (columnName.Equals("LastName")) { if (String.IsNullOrEmpty(LastName)) { result = "LastName cannot be null or empty"; } } return result; } } } </code></pre> <p>And here is the WPF code: </p> <pre><code>&lt;TextBlock Grid.Row="1" Margin="10" Grid.Column="0"&gt;LastName&lt;/TextBlock&gt; &lt;TextBox Style="{StaticResource textBoxStyle}" Name="txtLastName" Margin="10" VerticalAlignment="Top" Grid.Row="1" Grid.Column="1"&gt; &lt;Binding Source="{StaticResource CustomerKey}" Path="LastName" ValidatesOnExceptions="True" ValidatesOnDataErrors="True" UpdateSourceTrigger="LostFocus"/&gt; &lt;/TextBox&gt; </code></pre>
[ { "answer_id": 103641, "author": "cranley", "author_id": 10308, "author_profile": "https://Stackoverflow.com/users/10308", "pm_score": 4, "selected": false, "text": "<p>Unfortunately this is by design. WPF validation only fires if the value in the control has changed. </p>\n\n<p>Unbeli...
2008/09/19
[ "https://Stackoverflow.com/questions/103575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3797/" ]
I am trying to validate the WPF form against an object. The validation fires when I type something in the textbox lose focus come back to the textbox and then erase whatever I have written. But if I just load the WPF application and tab off the textbox without writing and erasing anything from the textbox, then it is not fired. Here is the Customer.cs class: ``` public class Customer : IDataErrorInfo { public string FirstName { get; set; } public string LastName { get; set; } public string Error { get { throw new NotImplementedException(); } } public string this[string columnName] { get { string result = null; if (columnName.Equals("FirstName")) { if (String.IsNullOrEmpty(FirstName)) { result = "FirstName cannot be null or empty"; } } else if (columnName.Equals("LastName")) { if (String.IsNullOrEmpty(LastName)) { result = "LastName cannot be null or empty"; } } return result; } } } ``` And here is the WPF code: ``` <TextBlock Grid.Row="1" Margin="10" Grid.Column="0">LastName</TextBlock> <TextBox Style="{StaticResource textBoxStyle}" Name="txtLastName" Margin="10" VerticalAlignment="Top" Grid.Row="1" Grid.Column="1"> <Binding Source="{StaticResource CustomerKey}" Path="LastName" ValidatesOnExceptions="True" ValidatesOnDataErrors="True" UpdateSourceTrigger="LostFocus"/> </TextBox> ```
If you're not adverse to putting a bit of logic in your code behind, you can handle the actual *LostFocus* event with something like this: **.xaml** ``` <TextBox LostFocus="TextBox_LostFocus" .... ``` --- **.xaml.cs** ``` private void TextBox_LostFocus(object sender, RoutedEventArgs e) { ((Control)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource(); } ```
103,576
<p>I'm trying a very basic XPath on <a href="http://pastebin.com/f14a20a30" rel="noreferrer">this xml</a> (same as below), and it doesn't find anything. I'm trying both .NET and <a href="http://www.xmlme.com/XpathTool.aspx" rel="noreferrer">this website</a>, and XPaths such as <code>//PropertyGroup</code>, <code>/PropertyGroup</code> and <code>//MSBuildCommunityTasksPath</code> are simply not working for me (they compiled but return zero results).</p> <p>Source XML:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"&gt; &lt;!-- $Id: FxCop.proj 114 2006-03-14 06:32:46Z pwelter34 $ --&gt; &lt;PropertyGroup&gt; &lt;MSBuildCommunityTasksPath&gt;$(MSBuildProjectDirectory)\MSBuild.Community.Tasks\bin\Debug&lt;/MSBuildCommunityTasksPath&gt; &lt;/PropertyGroup&gt; &lt;Import Project="$(MSBuildProjectDirectory)\MSBuild.Community.Tasks\MSBuild.Community.Tasks.Targets" /&gt; &lt;Target Name="DoFxCop"&gt; &lt;FxCop TargetAssemblies="$(MSBuildCommunityTasksPath)\MSBuild.Community.Tasks.dll" RuleLibraries="@(FxCopRuleAssemblies)" AnalysisReportFileName="Test.html" DependencyDirectories="$(MSBuildCommunityTasksPath)" FailOnError="True" ApplyOutXsl="True" OutputXslFileName="C:\Program Files\Microsoft FxCop 1.32\Xml\FxCopReport.xsl" /&gt; &lt;/Target&gt; &lt;/Project&gt; </code></pre>
[ { "answer_id": 103626, "author": "Pseudo Masochist", "author_id": 8529, "author_profile": "https://Stackoverflow.com/users/8529", "pm_score": 1, "selected": false, "text": "<p>Your issue is with the namespace (xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\"). You're receiv...
2008/09/19
[ "https://Stackoverflow.com/questions/103576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
I'm trying a very basic XPath on [this xml](http://pastebin.com/f14a20a30) (same as below), and it doesn't find anything. I'm trying both .NET and [this website](http://www.xmlme.com/XpathTool.aspx), and XPaths such as `//PropertyGroup`, `/PropertyGroup` and `//MSBuildCommunityTasksPath` are simply not working for me (they compiled but return zero results). Source XML: ``` <?xml version="1.0" encoding="utf-8"?> <Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <!-- $Id: FxCop.proj 114 2006-03-14 06:32:46Z pwelter34 $ --> <PropertyGroup> <MSBuildCommunityTasksPath>$(MSBuildProjectDirectory)\MSBuild.Community.Tasks\bin\Debug</MSBuildCommunityTasksPath> </PropertyGroup> <Import Project="$(MSBuildProjectDirectory)\MSBuild.Community.Tasks\MSBuild.Community.Tasks.Targets" /> <Target Name="DoFxCop"> <FxCop TargetAssemblies="$(MSBuildCommunityTasksPath)\MSBuild.Community.Tasks.dll" RuleLibraries="@(FxCopRuleAssemblies)" AnalysisReportFileName="Test.html" DependencyDirectories="$(MSBuildCommunityTasksPath)" FailOnError="True" ApplyOutXsl="True" OutputXslFileName="C:\Program Files\Microsoft FxCop 1.32\Xml\FxCopReport.xsl" /> </Target> </Project> ```
You can add namespaces in your code and all that, but you can effectively wildcard the namespace. Try the following XPath idiom. ``` //*[local-name()='PropertyGroup'] //*[local-name()='MSBuildCommunityTasksPath'] ``` name() usually works as well, as in: ``` //*[name()='PropertyGroup'] //*[name()='MSBuildCommunityTasksPath'] ``` EDIT: **Namespaces are great** and i'm not suggesting they're not important, but wildcarding them comes in handy when cobbling together prototype code, one-off desktop tools, experimenting with XSLT, and so forth. Balance your need for convenience against acceptable risk for the task at hand. FYI, if need be, you can also strip or reassign namespaces.
103,583
<p>This is written in PHP, but it's really language agnostic.</p> <pre><code>try { try { $issue = new DM_Issue($core-&gt;db-&gt;escape_string($_GET['issue'])); } catch(DM_Exception $e) { throw new Error_Page($tpl, ERR_NOT_FOUND, $e-&gt;getMessage()); } } catch(Error_Page $e) { die($e); } </code></pre> <p>Is nested try, catch blocks a good practice to follow? It seems a little bulky just for an error page - however my Issue Datamanager throws an Exception if an error occurs and I consider that to be a good way of error detecting.</p> <p>The Error_Page exception is simply an error page compiler.</p> <p>I might just be pedantic, but do you think this is a good way to report errors and if so can you suggest a better way to write this?</p> <p>Thanks</p>
[ { "answer_id": 103625, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 2, "selected": false, "text": "<p>I think you'd be better off not nesting. If you expect multiple exception types, have multiple catches.</p>\n\n<pre><co...
2008/09/19
[ "https://Stackoverflow.com/questions/103583", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
This is written in PHP, but it's really language agnostic. ``` try { try { $issue = new DM_Issue($core->db->escape_string($_GET['issue'])); } catch(DM_Exception $e) { throw new Error_Page($tpl, ERR_NOT_FOUND, $e->getMessage()); } } catch(Error_Page $e) { die($e); } ``` Is nested try, catch blocks a good practice to follow? It seems a little bulky just for an error page - however my Issue Datamanager throws an Exception if an error occurs and I consider that to be a good way of error detecting. The Error\_Page exception is simply an error page compiler. I might just be pedantic, but do you think this is a good way to report errors and if so can you suggest a better way to write this? Thanks
You're using Exceptions for page logic, and I personally think that's not a good thing. Exceptions should be used to signal when bad or unexpected things happen, not to control the output of an error page. If you want to generate an error page based on Exceptions, consider using [set\_exception\_handler](http://www.php.net/set_exception_handler). Any uncaught exceptions are run through whatever callback method you specify. Keep in mind that this doesn't stop the "fatalness" of an Exception. After an exception is passed through your callback, execution will stop like normal after any uncaught exception.
103,593
<p>I have:</p> <pre><code>&lt;?php $file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!"); if ($_POST["lastname"] &lt;&gt; "") { fwrite($file,$_POST["lastname"]."\n"); } fclose($file); ?&gt; </code></pre> <p>but it overwrites the beginning of the file. How do I make it insert?</p>
[ { "answer_id": 103609, "author": "ConroyP", "author_id": 2287, "author_profile": "https://Stackoverflow.com/users/2287", "pm_score": 6, "selected": true, "text": "<p>I'm not entirely sure of your question - do you want to write data and not have it over-write the beginning of an existing...
2008/09/19
[ "https://Stackoverflow.com/questions/103593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have: ``` <?php $file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!"); if ($_POST["lastname"] <> "") { fwrite($file,$_POST["lastname"]."\n"); } fclose($file); ?> ``` but it overwrites the beginning of the file. How do I make it insert?
I'm not entirely sure of your question - do you want to write data and not have it over-write the beginning of an existing file, or write new data to the start of an existing file, keeping the existing content after it? **To insert text without over-writing the beginning of the file**, you'll have to open it for appending ([`a+` rather than `r+`](http://ie.php.net/fopen)) ``` $file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!"); if ($_POST["lastname"] <> "") { fwrite($file,$_POST["lastname"]."\n"); } fclose($file); ``` **If you're trying to write to the start of the file**, you'll have to read in the file contents (see [`file_get_contents`](http://www.google.ie/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fwww.php.net%2Ffile_get_contents&ei=39jTSKOWEoyk1wbQ-vC6Dg&usg=AFQjCNHwFDwvy4v0p90sNfmfSB_jg7gR7Q&sig2=KyOdq6fGxuj8701pDDdXqA)) first, then write your new string followed by file contents to the output file. ``` $old_content = file_get_contents($file); fwrite($file, $new_content."\n".$old_content); ``` The above approach will work with small files, but you may run into memory limits trying to read a large file in using `file_get_conents`. In this case, consider using [`rewind($file)`](http://ie.php.net/rewind), which sets the file position indicator for handle to the beginning of the file stream. Note when using `rewind()`, not to open the file with the `a` (or `a+`) options, as: > > If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position. > > >
103,598
<p>Why was the <code>arguments.callee.caller</code> property deprecated in JavaScript?</p> <p>It was added and then deprecated in JavaScript, but it was omitted altogether by ECMAScript. Some browser (Mozilla, IE) have always supported it and don't have any plans on the map to remove support. Others (Safari, Opera) have adopted support for it, but support on older browsers is unreliable.</p> <p>Is there a good reason to put this valuable functionality in limbo?</p> <p>(Or alternately, is there a better way to grab a handle on the calling function?)</p>
[ { "answer_id": 103961, "author": "Zach", "author_id": 9128, "author_profile": "https://Stackoverflow.com/users/9128", "pm_score": 5, "selected": false, "text": "<p>It is better to use <strong>named functions</strong> than arguments.callee:</p>\n\n<pre><code> function foo () {\n ... f...
2008/09/19
[ "https://Stackoverflow.com/questions/103598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15992/" ]
Why was the `arguments.callee.caller` property deprecated in JavaScript? It was added and then deprecated in JavaScript, but it was omitted altogether by ECMAScript. Some browser (Mozilla, IE) have always supported it and don't have any plans on the map to remove support. Others (Safari, Opera) have adopted support for it, but support on older browsers is unreliable. Is there a good reason to put this valuable functionality in limbo? (Or alternately, is there a better way to grab a handle on the calling function?)
Early versions of JavaScript did not allow named function expressions, and because of that we could not make a recursive function expression: ``` // This snippet will work: function factorial(n) { return (!(n>1))? 1 : factorial(n-1)*n; } [1,2,3,4,5].map(factorial); // But this snippet will not: [1,2,3,4,5].map(function(n) { return (!(n>1))? 1 : /* what goes here? */ (n-1)*n; }); ``` To get around this, `arguments.callee` was added so we could do: ``` [1,2,3,4,5].map(function(n) { return (!(n>1))? 1 : arguments.callee(n-1)*n; }); ``` However this was actually a really bad solution as this (in conjunction with other arguments, callee, and caller issues) make inlining and tail recursion impossible in the general case (you can achieve it in select cases through tracing etc, but even the best code is sub optimal due to checks that would not otherwise be necessary). The other major issue is that the recursive call will get a different `this` value, for example: ``` var global = this; var sillyFunction = function (recursed) { if (!recursed) return arguments.callee(true); if (this !== global) alert("This is: " + this); else alert("This is the global"); } sillyFunction(); ``` Anyhow, EcmaScript 3 resolved these issues by allowing named function expressions, e.g.: ``` [1,2,3,4,5].map(function factorial(n) { return (!(n>1))? 1 : factorial(n-1)*n; }); ``` This has numerous benefits: * The function can be called like any other from inside your code. * It does not pollute the namespace. * The value of `this` does not change. * It's more performant (accessing the [arguments object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments) is expensive). ### Whoops, Just realised that in addition to everything else the question was about `arguments.callee.caller`, or more specifically [`Function.caller`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller). At any point in time you can find the deepest caller of any function on the stack, and as I said above, looking at the call stack has one single major effect: It makes a large number of optimizations impossible, or much much more difficult. Eg. if we can't guarantee that a function `f` will not call an unknown function, then it is not possible to inline `f`. Basically it means that any call site that may have been trivially inlinable accumulates a large number of guards, take: ``` function f(a, b, c, d, e) { return a ? b * c : d * e; } ``` If the js interpreter cannot guarantee that all the provided arguments are numbers at the point that the call is made, it needs to either insert checks for all the arguments before the inlined code, or it cannot inline the function. Now in this particular case a smart interpreter should be able to rearrange the checks to be more optimal and not check any values that would not be used. However in many cases that's just not possible and therefore it becomes impossible to inline.
103,616
<p>I have an Apex class (controller) originally developed under Developer Edition and need to upload it to production which is Enterprise Edition.</p> <p>The upload fails with following message</p> <pre><code>classes/RenewalController.cls(RenewalController):An error occurred on your page. package.xml(RenewalController):An object 'RenewalController' of type ApexClass was named in manifest but was not found in zipped directory </code></pre> <p>The same message when I try to use Force.com IDE: <em>Save error: An error occurred on your page.</em></p> <p>This class is working under Developer Edition but not with Enterprise.</p> <p>What can be the problem?</p>
[ { "answer_id": 177263, "author": "Dima Malenko", "author_id": 2586, "author_profile": "https://Stackoverflow.com/users/2586", "pm_score": 2, "selected": true, "text": "<p>Controller class may reference other custom SalesForce objects like pages. If controller is uploaded before these obj...
2008/09/19
[ "https://Stackoverflow.com/questions/103616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2586/" ]
I have an Apex class (controller) originally developed under Developer Edition and need to upload it to production which is Enterprise Edition. The upload fails with following message ``` classes/RenewalController.cls(RenewalController):An error occurred on your page. package.xml(RenewalController):An object 'RenewalController' of type ApexClass was named in manifest but was not found in zipped directory ``` The same message when I try to use Force.com IDE: *Save error: An error occurred on your page.* This class is working under Developer Edition but not with Enterprise. What can be the problem?
Controller class may reference other custom SalesForce objects like pages. If controller is uploaded before these objects *Save error: An error occurred on your page.* is reported. Correct order of uploading of custom components should be used.
103,622
<p>We have a java program that requires a large amount of heap space - we start it with (among other command line arguments) the argument -Xmx1500m, which specifies a maximum heap space of 1500 MB. When starting this program on a Windows XP box that has been freshly rebooted, it will start and run without issues. But if the program has run several times, the computer has been up for a while, etc., when it tries to start I get this error:</p> <pre> Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine. </pre> <p>I suspect that Windows itself is suffering from memory fragmentation, but I don't know how to confirm this suspicion. At the time that this happens, Task manager and sysinternals procexp report 2000MB free memory. I have looked at <a href="https://stackoverflow.com/questions/60871/how-to-solve-memory-fragmentation">this question related to internal fragmentation</a></p> <p>So the first question is, How do I confirm my suspicion? The second question is, if my suspicions are correct, does anyone know of any tools to solve this problem? I've looked around quite a bit, but I haven't found anything that helps, other than periodic reboots of the machine. </p> <p>ps - changing operating systems is also not currently a viable option. </p>
[ { "answer_id": 103830, "author": "kulakli", "author_id": 11131, "author_profile": "https://Stackoverflow.com/users/11131", "pm_score": 0, "selected": false, "text": "<p>Using Minimem (<a href=\"http://minimem.kerkia.net/\" rel=\"nofollow noreferrer\">http://minimem.kerkia.net/</a>) for t...
2008/09/19
[ "https://Stackoverflow.com/questions/103622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11051/" ]
We have a java program that requires a large amount of heap space - we start it with (among other command line arguments) the argument -Xmx1500m, which specifies a maximum heap space of 1500 MB. When starting this program on a Windows XP box that has been freshly rebooted, it will start and run without issues. But if the program has run several times, the computer has been up for a while, etc., when it tries to start I get this error: ``` Error occurred during initialization of VM Could not reserve enough space for object heap Could not create the Java virtual machine. ``` I suspect that Windows itself is suffering from memory fragmentation, but I don't know how to confirm this suspicion. At the time that this happens, Task manager and sysinternals procexp report 2000MB free memory. I have looked at [this question related to internal fragmentation](https://stackoverflow.com/questions/60871/how-to-solve-memory-fragmentation) So the first question is, How do I confirm my suspicion? The second question is, if my suspicions are correct, does anyone know of any tools to solve this problem? I've looked around quite a bit, but I haven't found anything that helps, other than periodic reboots of the machine. ps - changing operating systems is also not currently a viable option.
Agree with Torlack, a lot of this is because other DLLs are getting loaded and go into certain spots, breaking up the amount of memory you can get for the VM in one big chunk. You can do some work on WinXP if you have more than 3G of memory to get some of the windows stuff moved around, look up PAE here: <http://www.microsoft.com/whdc/system/platform/server/PAE/PAEdrv.mspx> Your best bet, if you really need more than 1.2G of memory for your java app, is to look at 64 bit windows or linux or OSX. If you're using any kind of native libraries with your app you'll have to recompile them for 64 bit, but its going to be a lot easier than trying to rebase dlls and stuff to maximize the memory you can get on 32 bit windows. Another option would be to split your program up into multiple VMs and have them communicate with eachother via RMI or messaging or something. That way each VM can have some subset of the memory you need. Without knowing what your app does, i'm not sure that this will help in any way, though...
103,630
<p>Is it possible to use an <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="noreferrer">ASP.NET</a> web.sitemap with a jQuery <a href="http://users.tpg.com.au/j_birch/plugins/superfish/" rel="noreferrer">Superfish</a> menu? </p> <p>If not, are there any standards based browser agnostic plugins available that work with the web.sitemap file?</p>
[ { "answer_id": 103789, "author": "Smallinov", "author_id": 8897, "author_profile": "https://Stackoverflow.com/users/8897", "pm_score": 0, "selected": false, "text": "<p>The SiteMapDataSource control should be able to bind to any hierarchical data bound control. I'm not familiar with supe...
2008/09/19
[ "https://Stackoverflow.com/questions/103630", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3742/" ]
Is it possible to use an [ASP.NET](http://en.wikipedia.org/wiki/ASP.NET) web.sitemap with a jQuery [Superfish](http://users.tpg.com.au/j_birch/plugins/superfish/) menu? If not, are there any standards based browser agnostic plugins available that work with the web.sitemap file?
I found this question while looking for the same answer... everyone *says* it's possible but no-one gives the actual solution! I seem to have it working now so thought I'd post my findings... Things I needed: * [Superfish](http://users.tpg.com.au/j_birch/plugins/superfish/#download) which also includes a version of [jQuery](http://jquery.com/) * [CSS Friendly Control Adaptors](http://cssfriendly.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=2159) download DLL and .browsers file (into /bin and /App\_Browsers folders respectively) * [ASP.NET SiteMap](http://msdn.microsoft.com/en-us/library/yy2ykkab.aspx) (a .sitemap XML file and `siteMap` provider entry in web.config) My finished `Masterpage.master` has the following `head` tag: ``` <head runat="server"> <script type="text/javascript" src="/script/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="/script/superfish.js"></script> <link href="~/css/superfish.css" type="text/css" rel="stylesheet" media="screen" runat="server" /> <script type="text/javascript"> $(document).ready(function() { $('ul.AspNet-Menu').superfish(); }); </script> </head> ``` Which is basically all the stuff needed for the jQuery Superfish menu to work. Inside the page (where the menu goes) looks like this (based on [these instructions](http://www.devx.com/asp/Article/31889)): ``` <asp:SiteMapDataSource ID="SiteMapDataSource" runat="server" ShowStartingNode="false" /> <asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource" Orientation="Horizontal" CssClass="sf-menu"> </asp:Menu> ``` Based on the documentation, this seems like it SHOULD work - but it doesn't. The reason is that the `CssClass="sf-menu"` gets overwritten when the Menu is rendered and the `<ul>` tag gets a `class="AspNet-Menu"`. I thought the line `$('ul.AspNet-Menu').superfish();` would help, but it didn't. **ONE MORE THING** Although it is a hack (and please someone point me to the correct solution) I was able to get it working by opening the `superfish.css` file and *search and replacing* **sf-menu** with **AspNet-Menu**... and voila! the menu appeared. I thought there would be some configuration setting in the `asp:Menu` control where I could set the `<ul>` class but didn't find any hints via google.
103,633
<p><a href="http://en.wikibooks.org/wiki/Combinatorics/Subsets_of_a_set-The_Binomial_Coefficient" rel="nofollow noreferrer">Pascal's rule</a> on counting the subset's of a set works great, when the set contains unique entities.</p> <p>Is there a modification to this rule for when the set contains duplicate items?</p> <p>For instance, when I try to find the count of the combinations of the letters A,B,C,D, it's easy to see that it's 1 + 4 + 6 + 4 + 1 (from Pascal's Triangle) = 16, or 15 if I remove the "use none of the letters" entry.</p> <p>Now, what if the set of letters is A,B,B,B,C,C,D? Computing by hand, I can determine that the sum of subsets is: 1 + 4 + 8 + 11 + 11 + 8 + 4 + 1 = 48, but this doesn't conform to the Triangle I know.</p> <p>Question: How do you modify Pascal's Triangle to take into account duplicate entities in the set?</p>
[ { "answer_id": 103651, "author": "Dima", "author_id": 13313, "author_profile": "https://Stackoverflow.com/users/13313", "pm_score": 2, "selected": false, "text": "<p>A set only contains unique items. If there are duplicates, then it is no longer a set.</p>\n" }, { "answer_id": 1...
2008/09/19
[ "https://Stackoverflow.com/questions/103633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13824/" ]
[Pascal's rule](http://en.wikibooks.org/wiki/Combinatorics/Subsets_of_a_set-The_Binomial_Coefficient) on counting the subset's of a set works great, when the set contains unique entities. Is there a modification to this rule for when the set contains duplicate items? For instance, when I try to find the count of the combinations of the letters A,B,C,D, it's easy to see that it's 1 + 4 + 6 + 4 + 1 (from Pascal's Triangle) = 16, or 15 if I remove the "use none of the letters" entry. Now, what if the set of letters is A,B,B,B,C,C,D? Computing by hand, I can determine that the sum of subsets is: 1 + 4 + 8 + 11 + 11 + 8 + 4 + 1 = 48, but this doesn't conform to the Triangle I know. Question: How do you modify Pascal's Triangle to take into account duplicate entities in the set?
It looks like you want to know how many sub-multi-sets have, say, 3 elements. The math for this gets very tricky, very quickly. The idea is that you want to add together all of the combinations of ways to get there. So you have C(3,4) = 4 ways of doing it with no duplicated elements. B can be repeated twice in C(1,3) = 3 ways. B can be repeated 3 times in 1 way. And C can be repeated twice in C(1,3) = 3 ways. For 11 total. (Your 10 you got by hand was wrong. Sorry.) In general trying to do that logic is too hard. The simpler way to keep track of it is to write out a polynomial whose coefficients have the terms you want which you multiply out. For Pascal's triangle this is easy, the polynomial is (1+x)^n. (You can use repeated squaring to calculate this more efficiently.) In your case if an element is repeated twice you would have a (1+x+x^2) factor. 3 times would be (1+x+x^2+x^3). So your specific problem would be solved as follows: ``` (1 + x) (1 + x + x^2 + x^3) (1 + x + x^2) (1 + x) = (1 + 2x + 2x^2 + 2x^3 + x^4)(1 + 2x + 2x^2 + x^3) = 1 + 2x + 2x^2 + x^3 + 2x + 4x^2 + 4x^3 + 2x^4 + 2x^2 + 4x^3 + 4x^4 + 2x^5 + 2x^3 + 4x^4 + 4x^5 + 2x^6 + x^4 + 2x^5 + 2x^6 + x^7 = 1 + 4x + 8x^2 + 11x^3 + 11x^4 + 8x^5 + 4x^6 + x^7 ``` If you want to produce those numbers in code, I would use the polynomial trick to organize your thinking and code. (You'd be working with arrays of coefficients.)
103,654
<p>In several modern programming languages (including C++, Java, and C#), the language allows <a href="http://en.wikipedia.org/wiki/Integer_overflow" rel="noreferrer">integer overflow</a> to occur at runtime without raising any kind of error condition.</p> <p>For example, consider this (contrived) C# method, which does not account for the possibility of overflow/underflow. (For brevity, the method also doesn't handle the case where the specified list is a null reference.)</p> <pre class="lang-c# prettyprint-override"><code>//Returns the sum of the values in the specified list. private static int sumList(List&lt;int&gt; list) { int sum = 0; foreach (int listItem in list) { sum += listItem; } return sum; } </code></pre> <p>If this method is called as follows:</p> <pre class="lang-c# prettyprint-override"><code>List&lt;int&gt; list = new List&lt;int&gt;(); list.Add(2000000000); list.Add(2000000000); int sum = sumList(list); </code></pre> <p>An overflow will occur in the <code>sumList()</code> method (because the <code>int</code> type in C# is a 32-bit signed integer, and the sum of the values in the list exceeds the value of the maximum 32-bit signed integer). The sum variable will have a value of -294967296 (not a value of 4000000000); this most likely is not what the (hypothetical) developer of the sumList method intended.</p> <p>Obviously, there are various techniques that can be used by developers to avoid the possibility of integer overflow, such as using a type like Java's <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html" rel="noreferrer"><code>BigInteger</code></a>, or the <a href="http://msdn.microsoft.com/en-us/library/74b4xzyw.aspx" rel="noreferrer"><code>checked</code></a> keyword and <a href="http://msdn.microsoft.com/en-us/library/h25wtyxf.aspx" rel="noreferrer"><code>/checked</code></a> compiler switch in C#.</p> <p>However, the question that I'm interested in is why these languages were designed to by default allow integer overflows to happen in the first place, instead of, for example, raising an exception when an operation is performed at runtime that would result in an overflow. It seems like such behavior would help avoid bugs in cases where a developer neglects to account for the possibility of overflow when writing code that performs an arithmetic operation that could result in overflow. (These languages could have included something like an "unchecked" keyword that could designate a block where integer overflow is permitted to occur without an exception being raised, in those cases where that behavior is explicitly intended by the developer; C# actually <a href="http://msdn.microsoft.com/en-us/library/a569z7k8.aspx" rel="noreferrer">does have this</a>.)</p> <p>Does the answer simply boil down to performance -- the language designers didn't want their respective languages to default to having "slow" arithmetic integer operations where the runtime would need to do extra work to check whether an overflow occurred, on every applicable arithmetic operation -- and this performance consideration outweighed the value of avoiding "silent" failures in the case that an inadvertent overflow occurs?</p> <p>Are there other reasons for this language design decision as well, other than performance considerations?</p>
[ { "answer_id": 103670, "author": "David Hill", "author_id": 1181217, "author_profile": "https://Stackoverflow.com/users/1181217", "pm_score": 5, "selected": false, "text": "<p>I think performance is a pretty good reason. If you consider every instruction in a typical program that increm...
2008/09/19
[ "https://Stackoverflow.com/questions/103654", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12484/" ]
In several modern programming languages (including C++, Java, and C#), the language allows [integer overflow](http://en.wikipedia.org/wiki/Integer_overflow) to occur at runtime without raising any kind of error condition. For example, consider this (contrived) C# method, which does not account for the possibility of overflow/underflow. (For brevity, the method also doesn't handle the case where the specified list is a null reference.) ```c# //Returns the sum of the values in the specified list. private static int sumList(List<int> list) { int sum = 0; foreach (int listItem in list) { sum += listItem; } return sum; } ``` If this method is called as follows: ```c# List<int> list = new List<int>(); list.Add(2000000000); list.Add(2000000000); int sum = sumList(list); ``` An overflow will occur in the `sumList()` method (because the `int` type in C# is a 32-bit signed integer, and the sum of the values in the list exceeds the value of the maximum 32-bit signed integer). The sum variable will have a value of -294967296 (not a value of 4000000000); this most likely is not what the (hypothetical) developer of the sumList method intended. Obviously, there are various techniques that can be used by developers to avoid the possibility of integer overflow, such as using a type like Java's [`BigInteger`](http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html), or the [`checked`](http://msdn.microsoft.com/en-us/library/74b4xzyw.aspx) keyword and [`/checked`](http://msdn.microsoft.com/en-us/library/h25wtyxf.aspx) compiler switch in C#. However, the question that I'm interested in is why these languages were designed to by default allow integer overflows to happen in the first place, instead of, for example, raising an exception when an operation is performed at runtime that would result in an overflow. It seems like such behavior would help avoid bugs in cases where a developer neglects to account for the possibility of overflow when writing code that performs an arithmetic operation that could result in overflow. (These languages could have included something like an "unchecked" keyword that could designate a block where integer overflow is permitted to occur without an exception being raised, in those cases where that behavior is explicitly intended by the developer; C# actually [does have this](http://msdn.microsoft.com/en-us/library/a569z7k8.aspx).) Does the answer simply boil down to performance -- the language designers didn't want their respective languages to default to having "slow" arithmetic integer operations where the runtime would need to do extra work to check whether an overflow occurred, on every applicable arithmetic operation -- and this performance consideration outweighed the value of avoiding "silent" failures in the case that an inadvertent overflow occurs? Are there other reasons for this language design decision as well, other than performance considerations?
In C#, it was a question of performance. Specifically, out-of-box benchmarking. When C# was new, Microsoft was hoping a lot of C++ developers would switch to it. They knew that many C++ folks thought of C++ as being fast, especially faster than languages that "wasted" time on automatic memory management and the like. Both potential adopters and magazine reviewers are likely to get a copy of the new C#, install it, build a trivial app that no one would ever write in the real world, run it in a tight loop, and measure how long it took. Then they'd make a decision for their company or publish an article based on that result. The fact that their test showed C# to be slower than natively compiled C++ is the kind of thing that would turn people off C# quickly. The fact that your C# app is going to catch overflow/underflow automatically is the kind of thing that they might miss. So, it's off by default. I think it's obvious that 99% of the time we want /checked to be on. It's an unfortunate compromise.
103,725
<p>I'm working on a project that generates PDFs that can contain fairly complex math and science formulas. The text is rendered in Times New Roman, which has pretty good Unicode coverage, but not complete. We have a system in place to swap in a more Unicode complete font for code points that don't have a glyph in TNR (like most of the "stranger" math symbols,) but I can't seem to find a way to query the *.ttf file to see if a given glyph is present. So far, I've just hard-coded a lookup table of which code points are present, but I'd much prefer an automatic solution.</p> <p>I'm using VB.Net in a web system under ASP.net, but solutions in any programming language/environment would be appreciated.</p> <p>Edit: The win32 solution looks excellent, but the specific case I'm trying to solve is in an ASP.Net web system. Is there a way to do this without including the windows API DLLs into my web site?</p>
[ { "answer_id": 103795, "author": "Stephen Deken", "author_id": 7154, "author_profile": "https://Stackoverflow.com/users/7154", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://www.freetype.org/\" rel=\"nofollow noreferrer\">FreeType</a> is a library that can read TrueType f...
2008/09/19
[ "https://Stackoverflow.com/questions/103725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19074/" ]
I'm working on a project that generates PDFs that can contain fairly complex math and science formulas. The text is rendered in Times New Roman, which has pretty good Unicode coverage, but not complete. We have a system in place to swap in a more Unicode complete font for code points that don't have a glyph in TNR (like most of the "stranger" math symbols,) but I can't seem to find a way to query the \*.ttf file to see if a given glyph is present. So far, I've just hard-coded a lookup table of which code points are present, but I'd much prefer an automatic solution. I'm using VB.Net in a web system under ASP.net, but solutions in any programming language/environment would be appreciated. Edit: The win32 solution looks excellent, but the specific case I'm trying to solve is in an ASP.Net web system. Is there a way to do this without including the windows API DLLs into my web site?
Here's a pass at it using c# and the windows API. ``` [DllImport("gdi32.dll")] public static extern uint GetFontUnicodeRanges(IntPtr hdc, IntPtr lpgs); [DllImport("gdi32.dll")] public extern static IntPtr SelectObject(IntPtr hDC, IntPtr hObject); public struct FontRange { public UInt16 Low; public UInt16 High; } public List<FontRange> GetUnicodeRangesForFont(Font font) { Graphics g = Graphics.FromHwnd(IntPtr.Zero); IntPtr hdc = g.GetHdc(); IntPtr hFont = font.ToHfont(); IntPtr old = SelectObject(hdc, hFont); uint size = GetFontUnicodeRanges(hdc, IntPtr.Zero); IntPtr glyphSet = Marshal.AllocHGlobal((int)size); GetFontUnicodeRanges(hdc, glyphSet); List<FontRange> fontRanges = new List<FontRange>(); int count = Marshal.ReadInt32(glyphSet, 12); for (int i = 0; i < count; i++) { FontRange range = new FontRange(); range.Low = (UInt16)Marshal.ReadInt16(glyphSet, 16 + i * 4); range.High = (UInt16)(range.Low + Marshal.ReadInt16(glyphSet, 18 + i * 4) - 1); fontRanges.Add(range); } SelectObject(hdc, old); Marshal.FreeHGlobal(glyphSet); g.ReleaseHdc(hdc); g.Dispose(); return fontRanges; } public bool CheckIfCharInFont(char character, Font font) { UInt16 intval = Convert.ToUInt16(character); List<FontRange> ranges = GetUnicodeRangesForFont(font); bool isCharacterPresent = false; foreach (FontRange range in ranges) { if (intval >= range.Low && intval <= range.High) { isCharacterPresent = true; break; } } return isCharacterPresent; } ``` Then, given a char toCheck that you want to check and a Font theFont to test it against... ``` if (!CheckIfCharInFont(toCheck, theFont) { // not present } ``` Same code using VB.Net ``` <DllImport("gdi32.dll")> _ Public Shared Function GetFontUnicodeRanges(ByVal hds As IntPtr, ByVal lpgs As IntPtr) As UInteger End Function <DllImport("gdi32.dll")> _ Public Shared Function SelectObject(ByVal hDc As IntPtr, ByVal hObject As IntPtr) As IntPtr End Function Public Structure FontRange Public Low As UInt16 Public High As UInt16 End Structure Public Function GetUnicodeRangesForFont(ByVal font As Font) As List(Of FontRange) Dim g As Graphics Dim hdc, hFont, old, glyphSet As IntPtr Dim size As UInteger Dim fontRanges As List(Of FontRange) Dim count As Integer g = Graphics.FromHwnd(IntPtr.Zero) hdc = g.GetHdc() hFont = font.ToHfont() old = SelectObject(hdc, hFont) size = GetFontUnicodeRanges(hdc, IntPtr.Zero) glyphSet = Marshal.AllocHGlobal(CInt(size)) GetFontUnicodeRanges(hdc, glyphSet) fontRanges = New List(Of FontRange) count = Marshal.ReadInt32(glyphSet, 12) For i = 0 To count - 1 Dim range As FontRange = New FontRange range.Low = Marshal.ReadInt16(glyphSet, 16 + (i * 4)) range.High = range.Low + Marshal.ReadInt16(glyphSet, 18 + (i * 4)) - 1 fontRanges.Add(range) Next SelectObject(hdc, old) Marshal.FreeHGlobal(glyphSet) g.ReleaseHdc(hdc) g.Dispose() Return fontRanges End Function Public Function CheckIfCharInFont(ByVal character As Char, ByVal font As Font) As Boolean Dim intval As UInt16 = Convert.ToUInt16(character) Dim ranges As List(Of FontRange) = GetUnicodeRangesForFont(font) Dim isCharacterPresent As Boolean = False For Each range In ranges If intval >= range.Low And intval <= range.High Then isCharacterPresent = True Exit For End If Next range Return isCharacterPresent End Function ```
103,765
<p>Here's the situation: I have a label's text set, immediately followed by a response.redirect() call as follows (this is just an example, but I believe it describes my situation accurately):</p> <p>aspx:</p> <pre><code>&lt;asp:Label runat="server" Text="default text" /&gt; </code></pre> <p>Code-behind (code called on an onclick event):</p> <pre><code>Label.Text = "foo"; Response.Redirect("Default.aspx"); </code></pre> <p>When the page renders, the label says "default text". What do I need to do differently? My understanding was that such changes would be done automatically behind the scenes, but apparently, not in this case. Thanks.</p> <p>For a little extra background, the code-behind snippet is called inside a method that's invoked upon an onclick event. There is more to it, but I only included that which is of interest to this issue.</p>
[ { "answer_id": 103813, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 1, "selected": false, "text": "<p>ASP and ASP.Net are inherently stateless unless state is explicitly specified. Normally between PostBacks informatio...
2008/09/19
[ "https://Stackoverflow.com/questions/103765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13578/" ]
Here's the situation: I have a label's text set, immediately followed by a response.redirect() call as follows (this is just an example, but I believe it describes my situation accurately): aspx: ``` <asp:Label runat="server" Text="default text" /> ``` Code-behind (code called on an onclick event): ``` Label.Text = "foo"; Response.Redirect("Default.aspx"); ``` When the page renders, the label says "default text". What do I need to do differently? My understanding was that such changes would be done automatically behind the scenes, but apparently, not in this case. Thanks. For a little extra background, the code-behind snippet is called inside a method that's invoked upon an onclick event. There is more to it, but I only included that which is of interest to this issue.
After a redirect you will loose any state information associated to your controls. If you simply want the page to refresh, remove the redirect. After the code has finished executing, the page will refresh and any state will be kept. Behind the scenes, this works because ASP.NET writes the state information to a hidden input field on the page. When you click a button, the form is posted and ASP.NET deciphers the viewstate. Your code runs, modifying the state, and after that the state is again written to the hidden field and the cycle continues, **until you change the page without a POST**. This can happen when clicking an hyperlink to another page, or via Response.Redirect(), which instructs the browser to follow the specified url.
103,829
<p>Given the following:</p> <pre><code>declare @a table ( pkid int, value int ) declare @b table ( otherID int, value int ) insert into @a values (1, 1000) insert into @a values (1, 1001) insert into @a values (2, 1000) insert into @a values (2, 1001) insert into @a values (2, 1002) insert into @b values (-1, 1000) insert into @b values (-1, 1001) insert into @b values (-1, 1002) </code></pre> <p>How do I query for all the values in @a that completely match up with @b? </p> <p><code>{@a.pkid = 1, @b.otherID = -1}</code> would not be returned (only 2 of 3 values match)</p> <p><code>{@a.pkid = 2, @b.otherID = -1}</code> would be returned (3 of 3 values match)</p> <p>Refactoring tables can be an option.</p> <p><strong>EDIT:</strong> I've had success with the answers from James and Tom H. </p> <p>When I add another case in @b, they fall a little short.</p> <pre><code>insert into @b values (-2, 1000) </code></pre> <p>Assuming this should return two additional rows (<code>{@a.pkid = 1, @b.otherID = -2}</code> and <code>{@a.pkid = 2, @b.otherID = -2}</code>, it doesn't work. However, for my project this is not an issue.</p>
[ { "answer_id": 103910, "author": "Cruachan", "author_id": 7315, "author_profile": "https://Stackoverflow.com/users/7315", "pm_score": 0, "selected": false, "text": "<p>Several ways of doing this, but a simple one is to create a union view as</p>\n\n<pre><code>create view qryMyUinion as\n...
2008/09/19
[ "https://Stackoverflow.com/questions/103829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4068/" ]
Given the following: ``` declare @a table ( pkid int, value int ) declare @b table ( otherID int, value int ) insert into @a values (1, 1000) insert into @a values (1, 1001) insert into @a values (2, 1000) insert into @a values (2, 1001) insert into @a values (2, 1002) insert into @b values (-1, 1000) insert into @b values (-1, 1001) insert into @b values (-1, 1002) ``` How do I query for all the values in @a that completely match up with @b? `{@a.pkid = 1, @b.otherID = -1}` would not be returned (only 2 of 3 values match) `{@a.pkid = 2, @b.otherID = -1}` would be returned (3 of 3 values match) Refactoring tables can be an option. **EDIT:** I've had success with the answers from James and Tom H. When I add another case in @b, they fall a little short. ``` insert into @b values (-2, 1000) ``` Assuming this should return two additional rows (`{@a.pkid = 1, @b.otherID = -2}` and `{@a.pkid = 2, @b.otherID = -2}`, it doesn't work. However, for my project this is not an issue.
Probably not the cheapest way to do it: ``` SELECT a.pkId,b.otherId FROM (SELECT a.pkId,CHECKSUM_AGG(DISTINCT a.value) as 'ValueHash' FROM @a a GROUP BY a.pkId) a INNER JOIN (SELECT b.otherId,CHECKSUM_AGG(DISTINCT b.value) as 'ValueHash' FROM @b b GROUP BY b.otherId) b ON a.ValueHash = b.ValueHash ``` You can see, basically I'm creating a new result set for each representing one value for each Id's set of values in each table and joining only where they match.
103,844
<p>List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers.</p> <p>Say, I have a 2D list:</p> <pre><code>li = [[0,1,2],[3,4,5],[6,7,8]] </code></pre> <p>I would like to merge this either into one long list</p> <pre><code>li2 = [0,1,2,3,4,5,6,7,8] </code></pre> <p>or into a string with separators:</p> <pre><code>s = "0,1,2,3,4,5,6,7,8" </code></pre> <p>Really, I'd like to know how to do both.</p>
[ { "answer_id": 103873, "author": "joeld", "author_id": 19104, "author_profile": "https://Stackoverflow.com/users/19104", "pm_score": 0, "selected": false, "text": "<pre><code>import itertools\nitertools.flatten( li )\n</code></pre>\n" }, { "answer_id": 103883, "author": "Eli ...
2008/09/19
[ "https://Stackoverflow.com/questions/103844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/577/" ]
List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers. Say, I have a 2D list: ``` li = [[0,1,2],[3,4,5],[6,7,8]] ``` I would like to merge this either into one long list ``` li2 = [0,1,2,3,4,5,6,7,8] ``` or into a string with separators: ``` s = "0,1,2,3,4,5,6,7,8" ``` Really, I'd like to know how to do both.
Like so: ``` [ item for innerlist in outerlist for item in innerlist ] ``` Turning that directly into a string with separators: ``` ','.join(str(item) for innerlist in outerlist for item in innerlist) ``` Yes, the order of 'for innerlist in outerlist' and 'for item in innerlist' is correct. Even though the "body" of the loop is at the start of the listcomp, the order of nested loops (and 'if' clauses) is still the same as when you would write the loop out: ``` for innerlist in outerlist: for item in innerlist: ... ```
103,918
<p>I am trying to install the ibm_db gem so that I can access DB2 from Ruby. When I try:</p> <pre><code>sudo gem install ibm_db </code></pre> <p>I get the following request for clarification:</p> <pre> Select which gem to install for your platform (i486-linux) 1. ibm_db 0.10.0 (ruby) 2. ibm_db 0.10.0 (mswin32) 3. ibm_db 0.9.5 (mswin32) 4. ibm_db 0.9.5 (ruby) 5. Skip this gem 6. Cancel installation </pre> <p>I am always going to be installing the linux version (which I assume is the "ruby" version), so is there a way to pick which one I will install straight from the gem install command?</p> <p>The reason this is a problem is that I need to automate this install via a bash script, so I would like to select that I want the "ruby" version ahead of time.</p>
[ { "answer_id": 104102, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 1, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>sudo gem install --platform ruby ibm_db\n</code></pre>\n\n<p>Note that you can get help o...
2008/09/19
[ "https://Stackoverflow.com/questions/103918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
I am trying to install the ibm\_db gem so that I can access DB2 from Ruby. When I try: ``` sudo gem install ibm_db ``` I get the following request for clarification: ``` Select which gem to install for your platform (i486-linux) 1. ibm_db 0.10.0 (ruby) 2. ibm_db 0.10.0 (mswin32) 3. ibm_db 0.9.5 (mswin32) 4. ibm_db 0.9.5 (ruby) 5. Skip this gem 6. Cancel installation ``` I am always going to be installing the linux version (which I assume is the "ruby" version), so is there a way to pick which one I will install straight from the gem install command? The reason this is a problem is that I need to automate this install via a bash script, so I would like to select that I want the "ruby" version ahead of time.
You can use a 'here document'. That is: ``` sudo gem install ibm_db <<heredoc 1 heredoc ``` What's between the \<\<\SOMETHING and SOMETHING gets inputted as entry to the previous command (somewhat like ruby's own heredocuments). The 1 there alone, of course, is the selection of the "ibm\_db 0.10.0 (ruby)" platform. Hope it's enough.
103,919
<p>I want to store the current URL in a session variable to reference the previous visited page.</p> <p>If I store every URL (via a before_filter on ApplicationController), also actions which end in a redirect (create, update, etc) are considered as last visited page.</p> <p>Is there a way to tell Rails only to execute a function if a template is rendered??</p> <p><strong>Update</strong></p> <p>Thanks for the after_filter tip... having written so many before_filters I didn't see the obvious. But the Trick with @performed_redirect doesn't work-</p> <p>This is what I got so far</p> <pre><code>class ApplicationController &lt; ActionController::Base after_filter :set_page_as_previous_page def set_page_as_previous_page unless @performed_redirect flash[:previous_page] = request.request_uri else flash[:previous_page] = flash[:previous_page] end end end </code></pre> <p>I need to implement a "Go Back" Link, without the use of Javascript, the HTTP Referer. Sorry If I should have mentioned that, I appreciate your help!</p> <p><strong>Update 2</strong></p> <p>I found a solution, which is not very elegant and only works if your app follows the standard naming scheme</p> <pre><code>def after_filter if File.exists?(File.join(Rails.root,"app","views", controller_path, action_name+".html.erb")) flash[:previous_page] = request.request_uri else flash[:previous_page] = flash[:previous_page] end end </code></pre>
[ { "answer_id": 103954, "author": "William Yeung", "author_id": 16371, "author_profile": "https://Stackoverflow.com/users/16371", "pm_score": 0, "selected": false, "text": "<p>Can be a bit more specific? I cant get your question- by template you means render :view, the layout? or only whe...
2008/09/19
[ "https://Stackoverflow.com/questions/103919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11231/" ]
I want to store the current URL in a session variable to reference the previous visited page. If I store every URL (via a before\_filter on ApplicationController), also actions which end in a redirect (create, update, etc) are considered as last visited page. Is there a way to tell Rails only to execute a function if a template is rendered?? **Update** Thanks for the after\_filter tip... having written so many before\_filters I didn't see the obvious. But the Trick with @performed\_redirect doesn't work- This is what I got so far ``` class ApplicationController < ActionController::Base after_filter :set_page_as_previous_page def set_page_as_previous_page unless @performed_redirect flash[:previous_page] = request.request_uri else flash[:previous_page] = flash[:previous_page] end end end ``` I need to implement a "Go Back" Link, without the use of Javascript, the HTTP Referer. Sorry If I should have mentioned that, I appreciate your help! **Update 2** I found a solution, which is not very elegant and only works if your app follows the standard naming scheme ``` def after_filter if File.exists?(File.join(Rails.root,"app","views", controller_path, action_name+".html.erb")) flash[:previous_page] = request.request_uri else flash[:previous_page] = flash[:previous_page] end end ```
Not sure why `@performed_redirect` isn't working, you can see that it does exist and have the desired values by calling the actions on this test controller: ``` class RedirController < ApplicationController after_filter :redir_raise def raise_true redirect_to :action => :whatever end def raise_false render :text => 'foo' end private def redir_raise raise @performed_redirect.to_s end end ``` As an aside, instead of doing ``` flash[:previous_page] = flash[:previous_page] ``` you can do ``` flash.keep :previous_page ``` (My patch, that. back in the days :P)
103,938
<p>I've been doing code review (mostly using tools like FindBugs) of one of our pet projects and FindBugs marked following code as erroneous (pseudocode):</p> <pre><code>Connection conn = dataSource.getConnection(); try{ PreparedStatement stmt = conn.prepareStatement(); //initialize the statement stmt.execute(); ResultSet rs = stmt.getResultSet(); //get data }finally{ conn.close(); } </code></pre> <p>The error was that this code might not release resources. I figured out that the ResultSet and Statement were not closed, so I closed them in finally:</p> <pre><code>finally{ try{ rs.close() }catch(SqlException se){ //log it } try{ stmt.close(); }catch(SqlException se){ //log it } conn.close(); } </code></pre> <p>But I encountered the above pattern in many projects (from quite a few companies), and no one was closing ResultSets or Statements.</p> <p>Did you have troubles with ResultSets and Statements not being closed when the Connection is closed? </p> <p>I found only <a href="http://www.theserverside.com/discussions/thread.tss?thread_id=41036" rel="noreferrer">this</a> and it refers to Oracle having problems with closing ResultSets when closing Connections (we use Oracle db, hence my corrections). java.sql.api says nothing in Connection.close() javadoc.</p>
[ { "answer_id": 103994, "author": "neu242", "author_id": 13365, "author_profile": "https://Stackoverflow.com/users/13365", "pm_score": 5, "selected": false, "text": "<p>I've had problems with unclosed ResultSets in Oracle, even though the connection was closed. The error I got was </p>\n...
2008/09/19
[ "https://Stackoverflow.com/questions/103938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7918/" ]
I've been doing code review (mostly using tools like FindBugs) of one of our pet projects and FindBugs marked following code as erroneous (pseudocode): ``` Connection conn = dataSource.getConnection(); try{ PreparedStatement stmt = conn.prepareStatement(); //initialize the statement stmt.execute(); ResultSet rs = stmt.getResultSet(); //get data }finally{ conn.close(); } ``` The error was that this code might not release resources. I figured out that the ResultSet and Statement were not closed, so I closed them in finally: ``` finally{ try{ rs.close() }catch(SqlException se){ //log it } try{ stmt.close(); }catch(SqlException se){ //log it } conn.close(); } ``` But I encountered the above pattern in many projects (from quite a few companies), and no one was closing ResultSets or Statements. Did you have troubles with ResultSets and Statements not being closed when the Connection is closed? I found only [this](http://www.theserverside.com/discussions/thread.tss?thread_id=41036) and it refers to Oracle having problems with closing ResultSets when closing Connections (we use Oracle db, hence my corrections). java.sql.api says nothing in Connection.close() javadoc.
One problem with ONLY closing the connection and not the result set, is that if your connection management code is using connection pooling, the `connection.close()` would just put the connection back in the pool. Additionally, some database have a cursor resource on the server that will not be freed properly unless it is explicitly closed.
103,945
<p>I've implemented a custom item renderer that I'm using with a combobox on a flex project I'm working on. It displays and icon and some text for each item. The only problem is that when the text is long the width of the menu is not being adjusted properly and the text is being truncated when displayed. I've tried tweaking all of the obvious properties to alleviate this problem but have not had any success. Does anyone know how to make the combobox menu width scale appropriately to whatever data it's rendering?</p> <p>My custom item renderer implementation is:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" styleName="plain" horizontalScrollPolicy="off"&gt; &lt;mx:Image source="{data.icon}" /&gt; &lt;mx:Label text="{data.label}" fontSize="11" fontWeight="bold" truncateToFit="false"/&gt; &lt;/mx:HBox&gt; </code></pre> <p>And my combobox uses it like so:</p> <pre><code> &lt;mx:ComboBox id="quicklinksMenu" change="quicklinkHandler(quicklinksMenu.selectedItem.data);" click="event.stopImmediatePropagation();" itemRenderer="renderers.QuickLinkItemRenderer" width="100%"/&gt; </code></pre> <p>EDIT: I should clarify on thing: I can set the dropdownWidth property on the combobox to some arbitrarily large value - this will make everything fit, but it will be too wide. Since the data being displayed in this combobox is generic, I want it to automatically size itself to the largest element in the dataprovider (the flex documentation says it will do this, but I have the feeling my custom item renderer is somehow breaking that behavior)</p>
[ { "answer_id": 104165, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 1, "selected": false, "text": "<p>Just a random thought (no clue if this will help):</p>\n\n<p>Try setting the parent HBox and the Label's widths to 100%. T...
2008/09/19
[ "https://Stackoverflow.com/questions/103945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2327/" ]
I've implemented a custom item renderer that I'm using with a combobox on a flex project I'm working on. It displays and icon and some text for each item. The only problem is that when the text is long the width of the menu is not being adjusted properly and the text is being truncated when displayed. I've tried tweaking all of the obvious properties to alleviate this problem but have not had any success. Does anyone know how to make the combobox menu width scale appropriately to whatever data it's rendering? My custom item renderer implementation is: ``` <?xml version="1.0" encoding="utf-8"?> <mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml" styleName="plain" horizontalScrollPolicy="off"> <mx:Image source="{data.icon}" /> <mx:Label text="{data.label}" fontSize="11" fontWeight="bold" truncateToFit="false"/> </mx:HBox> ``` And my combobox uses it like so: ``` <mx:ComboBox id="quicklinksMenu" change="quicklinkHandler(quicklinksMenu.selectedItem.data);" click="event.stopImmediatePropagation();" itemRenderer="renderers.QuickLinkItemRenderer" width="100%"/> ``` EDIT: I should clarify on thing: I can set the dropdownWidth property on the combobox to some arbitrarily large value - this will make everything fit, but it will be too wide. Since the data being displayed in this combobox is generic, I want it to automatically size itself to the largest element in the dataprovider (the flex documentation says it will do this, but I have the feeling my custom item renderer is somehow breaking that behavior)
Just a random thought (no clue if this will help): Try setting the parent HBox and the Label's widths to 100%. That's generally fixed any problems I've run into that were similar.
103,976
<p>How can you programmatically set the parameters for a subreport? For the top-level report, you can do the following:</p> <pre> reportViewer.LocalReport.SetParameters ( new Microsoft.Reporting.WebForms.ReportParameter[] { new Microsoft.Reporting.WebForms.ReportParameter("ParameterA", "Test"), new Microsoft.Reporting.WebForms.ReportParameter("ParameterB", "1/10/2009 10:30 AM"), new Microsoft.Reporting.WebForms.ReportParameter("ParameterC", "1234") } ); </pre> <p>Passing parameters like the above only seems to pass them to the top-level report, not the subreports.</p> <p>The LocalReport allows you to handle the SubreportProcessing event. That passes you an instance of SubreportProcessingEventArgs, which has a property of Type ReportParameterInfoCollection. The values in this collection are read-only.</p>
[ { "answer_id": 108859, "author": "John Hoven", "author_id": 1907, "author_profile": "https://Stackoverflow.com/users/1907", "pm_score": 1, "selected": false, "text": "<p>Add the parameter to the parent report and set the sub report parameter value from the parent report (in the actual re...
2008/09/19
[ "https://Stackoverflow.com/questions/103976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10834/" ]
How can you programmatically set the parameters for a subreport? For the top-level report, you can do the following: ``` reportViewer.LocalReport.SetParameters ( new Microsoft.Reporting.WebForms.ReportParameter[] { new Microsoft.Reporting.WebForms.ReportParameter("ParameterA", "Test"), new Microsoft.Reporting.WebForms.ReportParameter("ParameterB", "1/10/2009 10:30 AM"), new Microsoft.Reporting.WebForms.ReportParameter("ParameterC", "1234") } ); ``` Passing parameters like the above only seems to pass them to the top-level report, not the subreports. The LocalReport allows you to handle the SubreportProcessing event. That passes you an instance of SubreportProcessingEventArgs, which has a property of Type ReportParameterInfoCollection. The values in this collection are read-only.
Add the parameter to the parent report and set the sub report parameter value from the parent report (in the actual report definition). This is what I've read. Let me know if it works for you.
103,980
<p>I'm working on a document "wizard" for the company that I work for. It's a .dot file with a header consisting of some text and some form fields, and a lot of VBA code. The body of the document is pulled in as an OLE object from a separate .doc file.</p> <p>Currently, this is being done as a <code>Shape</code>, rather than an <code>InlineShape</code>. I did this because I can absolutely position the Shape, whereas the InlineShape always appears at the beginning of the document.</p> <p>The problem with this is that a <code>Shape</code> doesn't move when the size of the header changes. If someone needs to add or remove a line from the header due to a special case, they also need to move the object that defines the body. This is a pain, and I'd like to avoid it if possible.</p> <p>Long story short, how do I position an <code>InlineShape</code> using VBA in Word?</p> <p>The version I'm using is Word 97.</p>
[ { "answer_id": 104116, "author": "GSerg", "author_id": 11683, "author_profile": "https://Stackoverflow.com/users/11683", "pm_score": 3, "selected": true, "text": "<p>InlineShape is treated as a letter. Hence, the same technique.</p>\n\n<pre><code>ThisDocument.Range(15).InlineShapes.AddPi...
2008/09/19
[ "https://Stackoverflow.com/questions/103980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13894/" ]
I'm working on a document "wizard" for the company that I work for. It's a .dot file with a header consisting of some text and some form fields, and a lot of VBA code. The body of the document is pulled in as an OLE object from a separate .doc file. Currently, this is being done as a `Shape`, rather than an `InlineShape`. I did this because I can absolutely position the Shape, whereas the InlineShape always appears at the beginning of the document. The problem with this is that a `Shape` doesn't move when the size of the header changes. If someone needs to add or remove a line from the header due to a special case, they also need to move the object that defines the body. This is a pain, and I'd like to avoid it if possible. Long story short, how do I position an `InlineShape` using VBA in Word? The version I'm using is Word 97.
InlineShape is treated as a letter. Hence, the same technique. ``` ThisDocument.Range(15).InlineShapes.AddPicture "1.gif" ```
103,989
<p>I need to implement an in-memory tuple-of-strings matching feature in C. There will be large list of tuples associated with different actions and a high volume of events to be matched against the list.</p> <p>List of tuples:</p> <pre><code>("one", "four") ("one") ("three") ("four", "five") ("six") </code></pre> <p>event ("one", "two", "three", "four") should match list item ("one", "four") and ("one") and ("three") but not ("four", "five") and not ("six")</p> <p>my current approach uses a map of all tuple field values as keys for lists of each tuple using that value. there is a lot of redundant hashing and list insertion.</p> <p>is there a right or classic way to do this?</p>
[ { "answer_id": 104151, "author": "freespace", "author_id": 8297, "author_profile": "https://Stackoverflow.com/users/8297", "pm_score": 1, "selected": false, "text": "<p>I don't know of any classical or right way to do this, so here is what I would do :P</p>\n\n<p>It looks like you want t...
2008/09/19
[ "https://Stackoverflow.com/questions/103989", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7223/" ]
I need to implement an in-memory tuple-of-strings matching feature in C. There will be large list of tuples associated with different actions and a high volume of events to be matched against the list. List of tuples: ``` ("one", "four") ("one") ("three") ("four", "five") ("six") ``` event ("one", "two", "three", "four") should match list item ("one", "four") and ("one") and ("three") but not ("four", "five") and not ("six") my current approach uses a map of all tuple field values as keys for lists of each tuple using that value. there is a lot of redundant hashing and list insertion. is there a right or classic way to do this?
If you only have a small number of possible tuple values it would make sense to write some sort of hashing function which could turn them into integer indexes for quick searching. If there are < 32 values you could do something with bitmasks: ``` unsigned int hash(char *value){...} typedef struct _tuple { unsigned int bitvalues; void * data } tuple; tuple a,b,c,d; a.bitvalues = hash("one"); a.bitvalues |= hash("four"); //a.data = something; unsigned int event = 0; //foreach value in event; event |= hash(string_val); // foreach tuple if(x->bitvalues & test == test) { //matches } ``` If there are too many values to do a bitmask solution you could have an array of linked lists. Go through each item in the event. If the item matches key\_one, walk through the tuples with that first key and check the event for the second key: ``` typedef struct _tuple { unsigned int key_one; unsigned int key_two; _tuple *next; void * data; } tuple; tuple a,b,c,d; a.key_one = hash("one"); a.key_two = hash("four"); tuple * list = malloc(/*big enough for all hash indexes*/ memset(/*clear list*/); //foreach touple item if(list[item->key_one]) put item on the end of the list; else list[item->key_one] = item; //foreach event //foreach key if(item_ptr = list[key]) while(item_ptr.next) if(!item_ptr.key_two || /*item has key_two*/) //match item_ptr = item_ptr.next; ``` This code is in no way tested and probably has many small errors but you should get the idea. (one error that was corrected was the test condition for tuple match) --- If event processing speed is of utmost importance it would make sense to iterate through all of your constructed tuples, count the number of occurrences and go through possibly re-ordering the key one/key two of each tuple so the most unique value is listed first.
104,022
<p>I'm currently using <code>.resx</code> files to manage my server side resources for .NET.</p> <p>the application that I am dealing with also allows developers to plugin JavaScript into various event handlers for client side validation, etc.. What is the best way for me to localize my JavaScript messages and strings? </p> <p>Ideally, I would like to store the strings in the <code>.resx</code> files to keep them with the rest of the localized resources.</p> <p>I'm open to suggestions.</p>
[ { "answer_id": 104051, "author": "Diodeus - James MacFarlane", "author_id": 12579, "author_profile": "https://Stackoverflow.com/users/12579", "pm_score": 2, "selected": false, "text": "<p>I would use an object/array notation:</p>\n\n<pre><code>var phrases={};\nphrases['fatalError'] ='On ...
2008/09/19
[ "https://Stackoverflow.com/questions/104022", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7215/" ]
I'm currently using `.resx` files to manage my server side resources for .NET. the application that I am dealing with also allows developers to plugin JavaScript into various event handlers for client side validation, etc.. What is the best way for me to localize my JavaScript messages and strings? Ideally, I would like to store the strings in the `.resx` files to keep them with the rest of the localized resources. I'm open to suggestions.
A basic JavaScript object is an associative array, so it can easily be used to store key/value pairs. So using [JSON](http://www.json.org), you could create an object for each string to be localized like this: ``` var localizedStrings={ confirmMessage:{ 'en/US':'Are you sure?', 'fr/FR':'Est-ce que vous êtes certain?', ... }, ... } ``` Then you could get the locale version of each string like this: ``` var locale='en/US'; var confirm=localizedStrings['confirmMessage'][locale]; ```
104,055
<p>I know how to use rpm to list the contents of a package (<code>rpm -qpil package.rpm</code>). However, this requires knowing the location of the .rpm file on the filesystem. A more elegant solution would be to use the package manager, which in my case is YUM. How can YUM be used to achieve this?</p>
[ { "answer_id": 104087, "author": "Thomi", "author_id": 1304, "author_profile": "https://Stackoverflow.com/users/1304", "pm_score": 5, "selected": false, "text": "<p>I don't think you can list the contents of a package using yum, but if you have the .rpm file on your local system (as will...
2008/09/19
[ "https://Stackoverflow.com/questions/104055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
I know how to use rpm to list the contents of a package (`rpm -qpil package.rpm`). However, this requires knowing the location of the .rpm file on the filesystem. A more elegant solution would be to use the package manager, which in my case is YUM. How can YUM be used to achieve this?
There is a package called `yum-utils` that builds on YUM and contains a tool called `repoquery` that can do this. ``` $ repoquery --help | grep -E "list\ files" -l, --list list files in this package/group ``` Combined into one example: ``` $ repoquery -l time /usr/bin/time /usr/share/doc/time-1.7 /usr/share/doc/time-1.7/COPYING /usr/share/doc/time-1.7/NEWS /usr/share/doc/time-1.7/README /usr/share/info/time.info.gz ``` On at least one RH system, with rpm v4.8.0, yum v3.2.29, and repoquery v0.0.11, `repoquery -l rpm` prints nothing. If you are having this issue, try adding the `--installed` flag: `repoquery --installed -l rpm`. --- `DNF` Update: ------------- To use `dnf` instead of `yum-utils`, use the following command: ``` $ dnf repoquery -l time /usr/bin/time /usr/share/doc/time-1.7 /usr/share/doc/time-1.7/COPYING /usr/share/doc/time-1.7/NEWS /usr/share/doc/time-1.7/README /usr/share/info/time.info.gz ```
104,063
<p>I noticed in another post, someone had done something like:</p> <pre><code>double d = 3.1415; int i = Convert.ToInt32(Math.Floor(d)); </code></pre> <p>Why did they use the convert function, rather than:</p> <pre><code>double d = 3.1415; int i = (int)d; </code></pre> <p>which has an implicit floor and convert.</p> <p>Also, more concerning, I noticed in some production code I was reading:</p> <pre><code>double d = 3.1415; float f = Convert.ToSingle(d); </code></pre> <p>Is that the same as:</p> <pre><code>float f = (float)d; </code></pre> <p>Are all those otherwise implicit conversions just in the Convert class for completeness, or do they serve a purpose? I can understand a need for .ToString(), but not the rest.</p>
[ { "answer_id": 104180, "author": "NotDan", "author_id": 3291, "author_profile": "https://Stackoverflow.com/users/3291", "pm_score": 1, "selected": false, "text": "<p>You can use Convert when you have a string that you want to convert to an int </p>\n\n<pre><code>int i = Convert.ToInt32(\...
2008/09/19
[ "https://Stackoverflow.com/questions/104063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15261/" ]
I noticed in another post, someone had done something like: ``` double d = 3.1415; int i = Convert.ToInt32(Math.Floor(d)); ``` Why did they use the convert function, rather than: ``` double d = 3.1415; int i = (int)d; ``` which has an implicit floor and convert. Also, more concerning, I noticed in some production code I was reading: ``` double d = 3.1415; float f = Convert.ToSingle(d); ``` Is that the same as: ``` float f = (float)d; ``` Are all those otherwise implicit conversions just in the Convert class for completeness, or do they serve a purpose? I can understand a need for .ToString(), but not the rest.
Casting to int is implicit truncation, not implicit flooring: ``` double d = -3.14; int i = (int)d; // i == -3 ``` I choose Math.Floor or Math.Round to make my intentions more explicit.
104,066
<p>I have two insert statements, almost exactly the same, which run in two different schemas on the same Oracle instance. What the insert statement looks like doesn't matter - I'm looking for a troubleshooting strategy here.</p> <p>Both schemas have 99% the same structure. A few columns have slightly different names, other than that they're the same. The insert statements are almost exactly the same. The explain plan on one gives a cost of 6, the explain plan on the other gives a cost of 7. The tables involved in both sets of insert statements have exactly the same indexes. Statistics have been gathered for both schemas.</p> <p>One insert statement inserts 12,000 records in 5 seconds.</p> <p>The other insert statement inserts 25,000 records in 4 minutes 19 seconds.</p> <p>The number of records being insert is correct. It's the vast disparity in execution times that confuses me. Given that nothing stands out in the explain plan, how would you go about determining what's causing this disparity in runtimes?</p> <p>(I am using Oracle 10.2.0.4 on a Windows box).</p> <p><strong>Edit:</strong> The problem ended up being an inefficient query plan, involving a cartesian merge which didn't need to be done. Judicious use of index hints and a hash join hint solved the problem. It now takes 10 seconds. Sql Trace / TKProf gave me the direction, as I it showed me how many seconds each step in the plan took, and how many rows were being generated. Thus TKPROF showed me:-</p> <pre><code>Rows Row Source Operation ------- --------------------------------------------------- 23690 NESTED LOOPS OUTER (cr=3310466 pr=17 pw=0 time=174881374 us) 23690 NESTED LOOPS (cr=3310464 pr=17 pw=0 time=174478629 us) 2160900 MERGE JOIN CARTESIAN (cr=102 pr=0 pw=0 time=6491451 us) 1470 TABLE ACCESS BY INDEX ROWID TBL1 (cr=57 pr=0 pw=0 time=23978 us) 8820 INDEX RANGE SCAN XIF5TBL1 (cr=16 pr=0 pw=0 time=8859 us)(object id 272041) 2160900 BUFFER SORT (cr=45 pr=0 pw=0 time=4334777 us) 1470 TABLE ACCESS BY INDEX ROWID TBL1 (cr=45 pr=0 pw=0 time=2956 us) 8820 INDEX RANGE SCAN XIF5TBL1 (cr=10 pr=0 pw=0 time=8830 us)(object id 272041) 23690 MAT_VIEW ACCESS BY INDEX ROWID TBL2 (cr=3310362 pr=17 pw=0 time=235116546 us) 96565 INDEX RANGE SCAN XPK_TBL2 (cr=3219374 pr=3 pw=0 time=217869652 us)(object id 272084) 0 TABLE ACCESS BY INDEX ROWID TBL3 (cr=2 pr=0 pw=0 time=293390 us) 0 INDEX RANGE SCAN XIF1TBL3 (cr=2 pr=0 pw=0 time=180345 us)(object id 271983) </code></pre> <p>Notice the rows where the operations are MERGE JOIN CARTESIAN and BUFFER SORT. Things that keyed me into looking at this were the number of rows generated (over 2 million!), and the amount of time spent on each operation (compare to other operations).</p>
[ { "answer_id": 104103, "author": "Eddie Awad", "author_id": 17273, "author_profile": "https://Stackoverflow.com/users/17273", "pm_score": 3, "selected": true, "text": "<p>Use the <a href=\"http://docs.oracle.com/cd/B19306_01/server.102/b14211/sqltrace.htm#g33356\" rel=\"nofollow noreferr...
2008/09/19
[ "https://Stackoverflow.com/questions/104066", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16247/" ]
I have two insert statements, almost exactly the same, which run in two different schemas on the same Oracle instance. What the insert statement looks like doesn't matter - I'm looking for a troubleshooting strategy here. Both schemas have 99% the same structure. A few columns have slightly different names, other than that they're the same. The insert statements are almost exactly the same. The explain plan on one gives a cost of 6, the explain plan on the other gives a cost of 7. The tables involved in both sets of insert statements have exactly the same indexes. Statistics have been gathered for both schemas. One insert statement inserts 12,000 records in 5 seconds. The other insert statement inserts 25,000 records in 4 minutes 19 seconds. The number of records being insert is correct. It's the vast disparity in execution times that confuses me. Given that nothing stands out in the explain plan, how would you go about determining what's causing this disparity in runtimes? (I am using Oracle 10.2.0.4 on a Windows box). **Edit:** The problem ended up being an inefficient query plan, involving a cartesian merge which didn't need to be done. Judicious use of index hints and a hash join hint solved the problem. It now takes 10 seconds. Sql Trace / TKProf gave me the direction, as I it showed me how many seconds each step in the plan took, and how many rows were being generated. Thus TKPROF showed me:- ``` Rows Row Source Operation ------- --------------------------------------------------- 23690 NESTED LOOPS OUTER (cr=3310466 pr=17 pw=0 time=174881374 us) 23690 NESTED LOOPS (cr=3310464 pr=17 pw=0 time=174478629 us) 2160900 MERGE JOIN CARTESIAN (cr=102 pr=0 pw=0 time=6491451 us) 1470 TABLE ACCESS BY INDEX ROWID TBL1 (cr=57 pr=0 pw=0 time=23978 us) 8820 INDEX RANGE SCAN XIF5TBL1 (cr=16 pr=0 pw=0 time=8859 us)(object id 272041) 2160900 BUFFER SORT (cr=45 pr=0 pw=0 time=4334777 us) 1470 TABLE ACCESS BY INDEX ROWID TBL1 (cr=45 pr=0 pw=0 time=2956 us) 8820 INDEX RANGE SCAN XIF5TBL1 (cr=10 pr=0 pw=0 time=8830 us)(object id 272041) 23690 MAT_VIEW ACCESS BY INDEX ROWID TBL2 (cr=3310362 pr=17 pw=0 time=235116546 us) 96565 INDEX RANGE SCAN XPK_TBL2 (cr=3219374 pr=3 pw=0 time=217869652 us)(object id 272084) 0 TABLE ACCESS BY INDEX ROWID TBL3 (cr=2 pr=0 pw=0 time=293390 us) 0 INDEX RANGE SCAN XIF1TBL3 (cr=2 pr=0 pw=0 time=180345 us)(object id 271983) ``` Notice the rows where the operations are MERGE JOIN CARTESIAN and BUFFER SORT. Things that keyed me into looking at this were the number of rows generated (over 2 million!), and the amount of time spent on each operation (compare to other operations).
Use the [SQL Trace facility and TKPROF](http://docs.oracle.com/cd/B19306_01/server.102/b14211/sqltrace.htm#g33356).
104,068
<p>Let's say we have the following method declaration:</p> <pre><code>Public Function MyMethod(ByVal param1 As Integer, _ Optional ByVal param2 As Integer = 0, _ Optional ByVal param3 As Integer = 1) As Integer Return param1 + param2 + param3 End Function </code></pre> <p>How does VB.NET make the optional parameters work within the confines of the CLR? Are optional parameters CLS-Compliant?</p>
[ { "answer_id": 104094, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 3, "selected": false, "text": "<p>Contrary to popular belief, optional parameters do appear to be CLS-compliant. (However, my primary check for this wa...
2008/09/19
[ "https://Stackoverflow.com/questions/104068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14048/" ]
Let's say we have the following method declaration: ``` Public Function MyMethod(ByVal param1 As Integer, _ Optional ByVal param2 As Integer = 0, _ Optional ByVal param3 As Integer = 1) As Integer Return param1 + param2 + param3 End Function ``` How does VB.NET make the optional parameters work within the confines of the CLR? Are optional parameters CLS-Compliant?
Interestingly, this is the decompiled C# code, obtained via reflector. ``` public int MyMethod(int param1, [Optional, DefaultParameterValue(0)] int param2, [Optional, DefaultParameterValue(1)] int param3) { return ((param1 + param2) + param3); } ``` Notice the Optional and DefaultParameterValue attributes. Try putting them in C# methods. You will find that you are still required to pass values to the method. In VB code however, its turned into Default! That being said, I personally have never use Default even in VB code. It feels like a hack. Method overloading does the trick for me. Default does help though, when dealing with the Excel Interop, which is a pain in the ass to use straight out of the box in C#.
104,158
<p>I came across this recently, up until now I have been happily overriding the equality operator (<strong>==</strong>) and/or <strong>Equals</strong> method in order to see if two references types actually contained the same <strong>data</strong> (i.e. two different instances that look the same).</p> <p>I have been using this even more since I have been getting more in to automated testing (comparing reference/expected data against that returned).</p> <p>While looking over some of the <a href="http://msdn.microsoft.com/en-us/library/ms229042(VS.80).aspx" rel="noreferrer">coding standards guidelines in MSDN</a> I came across an <a href="http://msdn.microsoft.com/en-us/library/7h9bszxx(VS.80).aspx" rel="noreferrer">article</a> that advises against it. Now I understand <em>why</em> the article is saying this (because they are not the same <em>instance</em>) but it does not answer the question:</p> <ol> <li><strong>What is the best way to compare two reference types?</strong></li> <li>Should we implement <a href="http://msdn.microsoft.com/en-us/library/system.icomparable.aspx" rel="noreferrer">IComparable</a>? (I have also seen mention that this should be reserved for value types only).</li> <li>Is there some interface I don't know about?</li> <li>Should we just roll our own?!</li> </ol> <p>Many Thanks ^_^</p> <h2>Update</h2> <p>Looks like I had mis-read some of the documentation (it's been a long day) and overriding <a href="http://msdn.microsoft.com/en-us/library/336aedhh(VS.71).aspx" rel="noreferrer">Equals</a> may be the way to go..</p> <blockquote> <p>If you are implementing reference types, you should consider overriding the Equals method on a reference type if your type looks like a base type such as a Point, String, BigNumber, and so on. Most reference types should not overload the <strong>equality</strong> operator, even <strong>if they override Equals</strong>. However, if you are implementing a reference type that is intended to have value semantics, such as a complex number type, you should override the equality operator.</p> </blockquote>
[ { "answer_id": 104178, "author": "Paul Shannon", "author_id": 11503, "author_profile": "https://Stackoverflow.com/users/11503", "pm_score": 2, "selected": false, "text": "<p>For complex objects that will yield specific comparisons then implementing IComparable and defining the comparison...
2008/09/19
[ "https://Stackoverflow.com/questions/104158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/832/" ]
I came across this recently, up until now I have been happily overriding the equality operator (**==**) and/or **Equals** method in order to see if two references types actually contained the same **data** (i.e. two different instances that look the same). I have been using this even more since I have been getting more in to automated testing (comparing reference/expected data against that returned). While looking over some of the [coding standards guidelines in MSDN](http://msdn.microsoft.com/en-us/library/ms229042(VS.80).aspx) I came across an [article](http://msdn.microsoft.com/en-us/library/7h9bszxx(VS.80).aspx) that advises against it. Now I understand *why* the article is saying this (because they are not the same *instance*) but it does not answer the question: 1. **What is the best way to compare two reference types?** 2. Should we implement [IComparable](http://msdn.microsoft.com/en-us/library/system.icomparable.aspx)? (I have also seen mention that this should be reserved for value types only). 3. Is there some interface I don't know about? 4. Should we just roll our own?! Many Thanks ^\_^ Update ------ Looks like I had mis-read some of the documentation (it's been a long day) and overriding [Equals](http://msdn.microsoft.com/en-us/library/336aedhh(VS.71).aspx) may be the way to go.. > > If you are implementing reference > types, you should consider overriding > the Equals method on a reference type > if your type looks like a base type > such as a Point, String, BigNumber, > and so on. Most reference types should > not overload the **equality** operator, > even **if they override Equals**. However, > if you are implementing a reference > type that is intended to have value > semantics, such as a complex number > type, you should override the equality > operator. > > >
It looks like you're coding in C#, which has a method called Equals that your class should implement, should you want to compare two objects using some other metric than "are these two pointers (because object handles are just that, pointers) to the same memory address?". I grabbed some sample code from [here](http://msdn.microsoft.com/en-us/library/ms173147(VS.80).aspx): ``` class TwoDPoint : System.Object { public readonly int x, y; public TwoDPoint(int x, int y) //constructor { this.x = x; this.y = y; } public override bool Equals(System.Object obj) { // If parameter is null return false. if (obj == null) { return false; } // If parameter cannot be cast to Point return false. TwoDPoint p = obj as TwoDPoint; if ((System.Object)p == null) { return false; } // Return true if the fields match: return (x == p.x) && (y == p.y); } public bool Equals(TwoDPoint p) { // If parameter is null return false: if ((object)p == null) { return false; } // Return true if the fields match: return (x == p.x) && (y == p.y); } public override int GetHashCode() { return x ^ y; } } ``` Java has very similar mechanisms. The *equals()* method is part of the *Object* class, and your class overloads it if you want this type of functionality. The reason overloading '==' can be a bad idea for objects is that, usually, you still want to be able to do the "are these the same pointer" comparisons. These are usually relied upon for, for instance, inserting an element into a list where no duplicates are allowed, and some of your framework stuff may not work if this operator is overloaded in a non-standard way.
104,184
<p>There is a case where a map will be constructed, and once it is initialized, it will never be modified again. It will however, be accessed (via get(key) only) from multiple threads. Is it safe to use a <code>java.util.HashMap</code> in this way?</p> <p>(Currently, I'm happily using a <code>java.util.concurrent.ConcurrentHashMap</code>, and have no measured need to improve performance, but am simply curious if a simple <code>HashMap</code> would suffice. Hence, this question is <em>not</em> "Which one should I use?" nor is it a performance question. Rather, the question is "Would it be safe?")</p>
[ { "answer_id": 104251, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "<p><a href=\"http://www.docjar.com/html/api/java/util/HashMap.java.html\" rel=\"nofollow noreferrer\">http://www.docjar.com/...
2008/09/19
[ "https://Stackoverflow.com/questions/104184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3093/" ]
There is a case where a map will be constructed, and once it is initialized, it will never be modified again. It will however, be accessed (via get(key) only) from multiple threads. Is it safe to use a `java.util.HashMap` in this way? (Currently, I'm happily using a `java.util.concurrent.ConcurrentHashMap`, and have no measured need to improve performance, but am simply curious if a simple `HashMap` would suffice. Hence, this question is *not* "Which one should I use?" nor is it a performance question. Rather, the question is "Would it be safe?")
Your idiom is safe **if and only if** the reference to the `HashMap` is *safely published*. Rather than anything relating the internals of `HashMap` itself, *safe publication* deals with how the constructing thread makes the reference to the map visible to other threads. Basically, the only possible race here is between the construction of the `HashMap` and any reading threads that may access it before it is fully constructed. Most of the discussion is about what happens to the state of the map object, but this is irrelevant since you never modify it - so the only interesting part is how the `HashMap` reference is published. For example, imagine you publish the map like this: ``` class SomeClass { public static HashMap<Object, Object> MAP; public synchronized static setMap(HashMap<Object, Object> m) { MAP = m; } } ``` ... and at some point `setMap()` is called with a map, and other threads are using `SomeClass.MAP` to access the map, and check for null like this: ``` HashMap<Object,Object> map = SomeClass.MAP; if (map != null) { .. use the map } else { .. some default behavior } ``` This is **not safe** even though it probably appears as though it is. The problem is that there is no [*happens-before*](https://docs.oracle.com/javase/tutorial/essential/concurrency/memconsist.html) relationship between the set of `SomeObject.MAP` and the subsequent read on another thread, so the reading thread is free to see a partially constructed map. This can pretty much do *anything* and even in practice it does things like [put the reading thread into an infinite loop](http://mailinator.blogspot.com/2009/06/beautiful-race-condition.html). To safely publish the map, you need to establish a *happens-before* relationship between the *writing of the reference* to the `HashMap` (i.e., the *publication*) and the subsequent readers of that reference (i.e., the consumption). Conveniently, there are only a few easy-to-remember ways to [accomplish](https://stackoverflow.com/q/5458848/149138) that[1]: 1. Exchange the reference through a properly locked field ([JLS 17.4.5](http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5)) 2. Use static initializer to do the initializing stores ([JLS 12.4](http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4)) 3. Exchange the reference via a volatile field ([JLS 17.4.5](http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5)), or as the consequence of this rule, via the AtomicX classes 4. Initialize the value into a final field ([JLS 17.5](http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.5)). The ones most interesting for your scenario are (2), (3) and (4). In particular, (3) applies directly to the code I have above: if you transform the declaration of `MAP` to: ``` public static volatile HashMap<Object, Object> MAP; ``` then everything is kosher: readers who see a *non-null* value necessarily have a *happens-before* relationship with the store to `MAP` and hence see all the stores associated with the map initialization. The other methods change the semantics of your method, since both (2) (using the static initalizer) and (4) (using *final*) imply that you cannot set `MAP` dynamically at runtime. If you don't *need* to do that, then just declare `MAP` as a `static final HashMap<>` and you are guaranteed safe publication. In practice, the rules are simple for safe access to "never-modified objects": If you are publishing an object which is not *inherently immutable* (as in all fields declared `final`) and: * You already can create the object that will be assigned at the moment of declarationa: just use a `final` field (including `static final` for static members). * You want to assign the object later, after the reference is already visible: use a volatile fieldb. That's it! In practice, it is very efficient. The use of a `static final` field, for example, allows the JVM to assume the value is unchanged for the life of the program and optimize it heavily. The use of a `final` member field allows *most* architectures to read the field in a way equivalent to a normal field read and doesn't inhibit further optimizationsc. Finally, the use of `volatile` does have some impact: no hardware barrier is needed on many architectures (such as x86, specifically those that don't allow reads to pass reads), but some optimization and reordering may not occur at compile time - but this effect is generally small. In exchange, you actually get more than what you asked for - not only can you safely publish one `HashMap`, you can store as many more not-modified `HashMap`s as you want to the same reference and be assured that all readers will see a safely published map. For more gory details, refer to [Shipilev](https://shipilev.net/blog/2014/safe-public-construction/) or [this FAQ by Manson and Goetz](https://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#finalRight). --- [1] Directly quoting from [shipilev](https://shipilev.net/blog/2014/safe-public-construction/). --- a That sounds complicated, but what I mean is that you can assign the reference at construction time - either at the declaration point or in the constructor (member fields) or static initializer (static fields). b Optionally, you can use a `synchronized` method to get/set, or an `AtomicReference` or something, but we're talking about the minimum work you can do. c Some architectures with very weak memory models (I'm looking at *you*, Alpha) may require some type of read barrier before a `final` read - but these are very rare today.
104,223
<p>I have noticed that cURL in PHP returns different data when told to output to a file via <code>CURLOPT_FILE</code> as it does when told to send the output to a string via <code>CURLOPT_RETURNTRANSFER</code>.</p> <p><code>_RETURNTRANSFER</code> seems to strip newlines and extra white space as if parsing it for display as standard HTML code. <code>_FILE</code> on the other hand preserves the file exactly as it was intended.</p> <p>I have read through the documentation on php.net but haven't found anything that seems to solve my problem. Ideally, I would like to have <code>_RETURNTRANSFER</code> return the exact contents so I could eliminate an intermediate file, but I don't see any way of making this possible.</p> <p>Here is the code I am using. The data in question is a CSV file with \r\n line endings.</p> <pre><code>function update_roster() { $url = "http://example.com/"; $userID = "xx"; $apikey = "xxx"; $passfields = "userID=$userID&amp;apikey=$apikey"; $file = fopen("roster.csv","w+"); $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_POSTFIELDS, $passfields); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FILE, $file); $variable_in_question = curl_exec ($ch); curl_close ($ch); fclose($file); return $variable_in_question; } </code></pre> <hr> <p>Turns out, the error is not in what was being returned, but in the way I was going about parsing it. \r\n is not parsed the way I expected when put in single quotes, switching to double quotes solved my problem. I was not aware that this made a difference inside function calls like that.</p> <p>This works just fine:<code>$cresult = split("\r\n", $cresult);</code></p> <p>This does not: <code>$cresult = split('\r\n', $cresult);</code></p>
[ { "answer_id": 104750, "author": "p4bl0", "author_id": 12043, "author_profile": "https://Stackoverflow.com/users/12043", "pm_score": 0, "selected": false, "text": "<p>I didn't try to reproduce the \"bug\" (I think we can consider this as a bug if it is the actual behavior), but maybe you...
2008/09/19
[ "https://Stackoverflow.com/questions/104223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1536217/" ]
I have noticed that cURL in PHP returns different data when told to output to a file via `CURLOPT_FILE` as it does when told to send the output to a string via `CURLOPT_RETURNTRANSFER`. `_RETURNTRANSFER` seems to strip newlines and extra white space as if parsing it for display as standard HTML code. `_FILE` on the other hand preserves the file exactly as it was intended. I have read through the documentation on php.net but haven't found anything that seems to solve my problem. Ideally, I would like to have `_RETURNTRANSFER` return the exact contents so I could eliminate an intermediate file, but I don't see any way of making this possible. Here is the code I am using. The data in question is a CSV file with \r\n line endings. ``` function update_roster() { $url = "http://example.com/"; $userID = "xx"; $apikey = "xxx"; $passfields = "userID=$userID&apikey=$apikey"; $file = fopen("roster.csv","w+"); $ch = curl_init(); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_POSTFIELDS, $passfields); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FILE, $file); $variable_in_question = curl_exec ($ch); curl_close ($ch); fclose($file); return $variable_in_question; } ``` --- Turns out, the error is not in what was being returned, but in the way I was going about parsing it. \r\n is not parsed the way I expected when put in single quotes, switching to double quotes solved my problem. I was not aware that this made a difference inside function calls like that. This works just fine:`$cresult = split("\r\n", $cresult);` This does not: `$cresult = split('\r\n', $cresult);`
Turns out, the error is not in what was being returned, but in the way I was going about parsing it. \r\n is not parsed the way I expected when put in single quotes, switching to double quotes solved my problem. I was not aware that this made a difference inside function calls like that. This works just fine:`$cresult = split("\r\n", $cresult);` This does not: `$cresult = split('\r\n', $cresult);`
104,224
<p>I'm working on a WPF application that sometimes exhibits odd problems and appears to <em>hang</em> in the UI. It is inconsistent, it happens in different pages, but it happens often enough that it is a big problem. I should mention that it is not a true hang as described below.</p> <p>My first thought was that the animations of some buttons was the problem since they are used on most pages, but after removing them the hangs still occur, although seemingly a bit less often. I have tried to break into the debugger when the hang occurs; however there is never any code to view. No code of mine is running. I have also noticed that the "hang" is not complete. I have code that lets me drag the form around (it has no border or title) which continues to work. I also have my won close button which functions when I click it. Clicking on buttons appears to actually work as my code runs, but the UI simply never updates to show a new page.</p> <p>I'm looking for any advice, tools or techniques to track down this odd problem, so if you have any thoughts at all, I will greatly appreciate it.</p> <p>EDIT: It just happened again, so this time when I tried to break into the debugger I chose to "show disassembly". It brings me to MS.Win32.UnsafeNativeMethods.GetMessageW. The stack trace follows:</p> <pre><code>[Managed to Native Transition] </code></pre> <blockquote> <p>WindowsBase.dll!MS.Win32.UnsafeNativeMethods.GetMessageW(ref System.Windows.Interop.MSG msg, System.Runtime.InteropServices.HandleRef hWnd, int uMsgFilterMin, int uMsgFilterMax) + 0x15 bytes<br> WindowsBase.dll!System.Windows.Threading.Dispatcher.GetMessage(ref System.Windows.Interop.MSG msg, System.IntPtr hwnd, int minMessage, int maxMessage) + 0x48 bytes WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame = {System.Windows.Threading.DispatcherFrame}) + 0x8b bytes WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes<br> WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4c bytes<br> PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x1e bytes<br> PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes PresentationFramework.dll!System.Windows.Application.Run() + 0x19 bytes WinterGreen.exe!WinterGreen.App.Main() + 0x5e bytes C# [Native to Managed Transition]<br> [Managed to Native Transition]<br> mscorlib.dll!System.AppDomain.nExecuteAssembly(System.Reflection.Assembly assembly, string[] args) + 0x19 bytes mscorlib.dll!System.Runtime.Hosting.ManifestRunner.Run(bool checkAptModel) + 0x6e bytes mscorlib.dll!System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly() + 0x84 bytes mscorlib.dll!System.Runtime.Hosting.ApplicationActivator.CreateInstance(System.ActivationContext activationContext, string[] activationCustomData) + 0x65 bytes mscorlib.dll!System.Runtime.Hosting.ApplicationActivator.CreateInstance(System.ActivationContext activationContext) + 0xa bytes mscorlib.dll!System.Activator.CreateInstance(System.ActivationContext activationContext) + 0x3e bytes<br> Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone() + 0x23 bytes<br> mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x66 bytes<br> mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x6f bytes<br> mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x44 bytes </p> </blockquote>
[ { "answer_id": 104272, "author": "Bob King", "author_id": 6897, "author_profile": "https://Stackoverflow.com/users/6897", "pm_score": 4, "selected": true, "text": "<p>Try removing the borderless behavior of your window and see if that helps. Also, are you BeginInvoke()'ing or Invoke()'in...
2008/09/19
[ "https://Stackoverflow.com/questions/104224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/312/" ]
I'm working on a WPF application that sometimes exhibits odd problems and appears to *hang* in the UI. It is inconsistent, it happens in different pages, but it happens often enough that it is a big problem. I should mention that it is not a true hang as described below. My first thought was that the animations of some buttons was the problem since they are used on most pages, but after removing them the hangs still occur, although seemingly a bit less often. I have tried to break into the debugger when the hang occurs; however there is never any code to view. No code of mine is running. I have also noticed that the "hang" is not complete. I have code that lets me drag the form around (it has no border or title) which continues to work. I also have my won close button which functions when I click it. Clicking on buttons appears to actually work as my code runs, but the UI simply never updates to show a new page. I'm looking for any advice, tools or techniques to track down this odd problem, so if you have any thoughts at all, I will greatly appreciate it. EDIT: It just happened again, so this time when I tried to break into the debugger I chose to "show disassembly". It brings me to MS.Win32.UnsafeNativeMethods.GetMessageW. The stack trace follows: ``` [Managed to Native Transition] ``` > > WindowsBase.dll!MS.Win32.UnsafeNativeMethods.GetMessageW(ref System.Windows.Interop.MSG msg, System.Runtime.InteropServices.HandleRef hWnd, int uMsgFilterMin, int uMsgFilterMax) + 0x15 bytes > > WindowsBase.dll!System.Windows.Threading.Dispatcher.GetMessage(ref System.Windows.Interop.MSG msg, System.IntPtr hwnd, int minMessage, int maxMessage) + 0x48 bytes > WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame = {System.Windows.Threading.DispatcherFrame}) + 0x8b bytes > WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes > > WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4c bytes > > PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x1e bytes > > PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes > PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes > PresentationFramework.dll!System.Windows.Application.Run() + 0x19 bytes > WinterGreen.exe!WinterGreen.App.Main() + 0x5e bytes C# > [Native to Managed Transition] > > [Managed to Native Transition] > > mscorlib.dll!System.AppDomain.nExecuteAssembly(System.Reflection.Assembly assembly, string[] args) + 0x19 bytes > mscorlib.dll!System.Runtime.Hosting.ManifestRunner.Run(bool checkAptModel) + 0x6e bytes > mscorlib.dll!System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly() + 0x84 bytes > mscorlib.dll!System.Runtime.Hosting.ApplicationActivator.CreateInstance(System.ActivationContext activationContext, string[] activationCustomData) + 0x65 bytes > mscorlib.dll!System.Runtime.Hosting.ApplicationActivator.CreateInstance(System.ActivationContext activationContext) + 0xa bytes > mscorlib.dll!System.Activator.CreateInstance(System.ActivationContext activationContext) + 0x3e bytes > > Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone() + 0x23 bytes > > mscorlib.dll!System.Threading.ThreadHelper.ThreadStart\_Context(object state) + 0x66 bytes > > mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x6f bytes > > mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x44 bytes > > >
Try removing the borderless behavior of your window and see if that helps. Also, are you BeginInvoke()'ing or Invoke()'ing any long running operations? Another thing to look at: When you break into your code, try looking at threads other than your main thread. One of them may be blocking the UI thread.
104,230
<p>Situation: A PHP application with multiple installable modules creates a new table in database for each, in the style of mod_A, mod_B, mod_C etc. Each has the column section_id.</p> <p>Now, I am looking for all entries for a specific section_id, and I'm hoping there's another way besides "Select * from mod_a, mod_b, mod_c ... mod_xyzzy where section_id=value"... or even worse, using a separate query for each module.</p>
[ { "answer_id": 104257, "author": "borjab", "author_id": 16206, "author_profile": "https://Stackoverflow.com/users/16206", "pm_score": 1, "selected": false, "text": "<p>What about?</p>\n\n<pre><code>SELECT * FROM mod_a WHERE section_id=value\nUNION ALL\nSELECT * FROM mod_b WHERE section_i...
2008/09/19
[ "https://Stackoverflow.com/questions/104230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4224/" ]
Situation: A PHP application with multiple installable modules creates a new table in database for each, in the style of mod\_A, mod\_B, mod\_C etc. Each has the column section\_id. Now, I am looking for all entries for a specific section\_id, and I'm hoping there's another way besides "Select \* from mod\_a, mod\_b, mod\_c ... mod\_xyzzy where section\_id=value"... or even worse, using a separate query for each module.
If the tables are changing over time, you can inline code gen your solution in an SP (pseudo code - you'll have to fill in): ``` SET @sql = '' DECLARE CURSOR FOR SELECT t.[name] AS TABLE_NAME FROM sys.tables t WHERE t.[name] LIKE 'SOME_PATTERN_TO_IDENTIFY_THE_TABLES' ``` -- or this ``` DECLARE CURSOR FOR SELECT t.[name] AS TABLE_NAME FROM TABLE_OF_TABLES_TO_SEACRH t START LOOP IF @sql <> '' SET @sql = @sql + 'UNION ALL ' SET @sql = 'SELECT * FROM [' + @TABLE_NAME + '] WHERE section_id=value ' END LOOP EXEC(@sql) ``` I've used this technique occasionally, when there just isn't any obvious way to make it future-proof without dynamic SQL. Note: In your loop, you can use the COALESCE/NULL propagation trick and leave the string as NULL before the loop, but it's not as clear if you are unfamiliar with the idiom: ``` SET @sql = COALESCE(@sql + ' UNION ALL ', '') + 'SELECT * FROM [' + @TABLE_NAME + '] WHERE section_id=value ' ```
104,235
<p>What is the syntax and which namespace/class needs to be imported? Give me sample code if possible. It would be of great help.</p>
[ { "answer_id": 104262, "author": "MagicKat", "author_id": 8505, "author_profile": "https://Stackoverflow.com/users/8505", "pm_score": 5, "selected": false, "text": "<p>Put the following where you need it:</p>\n\n<pre><code>System.Diagnostics.Debugger.Break();\n</code></pre>\n" }, { ...
2008/09/19
[ "https://Stackoverflow.com/questions/104235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13432/" ]
What is the syntax and which namespace/class needs to be imported? Give me sample code if possible. It would be of great help.
Put the following where you need it: ``` System.Diagnostics.Debugger.Break(); ```
104,238
<p>I'm having an issue with my regex.</p> <p>I want to capture &lt;% some stuff %> and i need what's inside the &lt;% and the %></p> <p>This regex works quite well for that.</p> <pre><code>$matches = preg_split("/&lt;%[\s]*(.*?)[\s]*%&gt;/i",$markup,-1,(PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)); </code></pre> <p>I also want to catch <code>&amp;amp;% some stuff %&amp;amp;gt;</code> so I need to capture <code>&lt;% or &amp;amp;lt;% and %&gt; or %&amp;amp;gt;</code> respectively. </p> <p>If I put in a second set of parens, it makes preg_split function differently (because as you can see from the flag, I'm trying to capture what's inside the parens.</p> <p>Preferably, it would only match <code>&amp;amp;lt; to &amp;amp;gt; and &lt; to &gt;</code> as well, but that's not completely necessary</p> <p>EDIT: The SUBJECT may contain multiple matches, and I need all of them</p>
[ { "answer_id": 104295, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 4, "selected": true, "text": "<p>In your case, it's better to use preg_match with its additional parameter and parenthesis:</p>\n\n<pre><code>preg_match(\"...
2008/09/19
[ "https://Stackoverflow.com/questions/104238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144/" ]
I'm having an issue with my regex. I want to capture <% some stuff %> and i need what's inside the <% and the %> This regex works quite well for that. ``` $matches = preg_split("/<%[\s]*(.*?)[\s]*%>/i",$markup,-1,(PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE)); ``` I also want to catch `&amp;% some stuff %&amp;gt;` so I need to capture `<% or &amp;lt;% and %> or %&amp;gt;` respectively. If I put in a second set of parens, it makes preg\_split function differently (because as you can see from the flag, I'm trying to capture what's inside the parens. Preferably, it would only match `&amp;lt; to &amp;gt; and < to >` as well, but that's not completely necessary EDIT: The SUBJECT may contain multiple matches, and I need all of them
In your case, it's better to use preg\_match with its additional parameter and parenthesis: ``` preg_match("#((?:<|&lt;)%)([\s]*(?:[^ø]*)[\s]*?)(%(?:>|&gt;))#i",$markup, $out); print_r($out); Array ( [0] => <% your stuff %> [1] => <% [2] => your stuff [3] => %> ) ``` By the way, check this online tool to debug PHP regexp, it's so useful ! <http://regex.larsolavtorvik.com/> EDIT : I hacked the regexp a bit so it's faster. Tested it, it works :-) Now let's explain all that stuff : * preg\_match will store everything he captures in the var passed as third param (here $out) * if preg\_match matches something, it will be store in $out[0] * anything that is inside () but not (?:) in the pattern will be stored in $out The patten in details : ``` #((?:<|&lt;)%)([\s]*(?:[^ø]*)[\s]*?)(%(?:>|&gt;))#i can be viewed as ((?:<|&lt;)%) + ([\s]*(?:[^ø]*)[\s]*?) + (%(?:>|&gt;)). ((?:<|&lt;)%) is capturing < or &lt; then % (%(?:>|&gt;)) is capturing % then < or &gt; ([\s]*(?:[^ø]*)[\s]*?) means 0 or more spaces, then 0 or more times anything that is not the ø symbol, the 0 or more spaces. ``` Why do we use [^ø] instead of . ? It's because . is very time consuming, the regexp engine will check among all the existing characters. [^ø] just check if the char is not ø. Nobody uses ø, it's an international money symbol, but if you care, you can replace it by chr(7) wich is the shell bell char that's obviously will never be typed in a web page. EDIT2 : I just read your edit about capturing all the matches. In that case, you´ll use preg\_match\_all the same way.
104,254
<p>I use the Eclipse IDE to develop, compile, and run my Java projects. Today, I'm trying to use the <code>java.io.Console</code> class to manage output and, more importantly, user input.</p> <p>The problem is that <code>System.console()</code> returns <code>null</code> when an application is run "through" Eclipse. Eclipse run the program on a background process, rather than a top-level process with the console window we're familiar with.</p> <p>Is there a way to force Eclipse to run the program as a top level process, or at least create a Console that the JVM will recognize? Otherwise, I'm forced to jar the project up and run on a command-line environment external to Eclipse.</p>
[ { "answer_id": 104391, "author": "perimosocordiae", "author_id": 10601, "author_profile": "https://Stackoverflow.com/users/10601", "pm_score": 2, "selected": false, "text": "<p>As far as I can tell, there is no way to get a Console object from Eclipse. I'd just make sure that console !=...
2008/09/19
[ "https://Stackoverflow.com/questions/104254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19147/" ]
I use the Eclipse IDE to develop, compile, and run my Java projects. Today, I'm trying to use the `java.io.Console` class to manage output and, more importantly, user input. The problem is that `System.console()` returns `null` when an application is run "through" Eclipse. Eclipse run the program on a background process, rather than a top-level process with the console window we're familiar with. Is there a way to force Eclipse to run the program as a top level process, or at least create a Console that the JVM will recognize? Otherwise, I'm forced to jar the project up and run on a command-line environment external to Eclipse.
I assume you want to be able to use step-through debugging from Eclipse. You can just run the classes externally by setting the built classes in the bin directories on the JRE classpath. ``` java -cp workspace\p1\bin;workspace\p2\bin foo.Main ``` You can debug using the remote debugger and taking advantage of the class files built in your project. In this example, the Eclipse project structure looks like this: ``` workspace\project\ \.classpath \.project \debug.bat \bin\Main.class \src\Main.java ``` **1. Start the JVM Console in Debug Mode** **debug.bat** is a Windows batch file that should be run externally from a **cmd.exe** console. ``` @ECHO OFF SET A_PORT=8787 SET A_DBG=-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=%A_PORT%,server=y,suspend=y java.exe %A_DBG% -cp .\bin Main ``` In the arguments, the debug port has been set to *8787*. The *suspend=y* argument tells the JVM to wait until the debugger attaches. **2. Create a Debug Launch Configuration** In Eclipse, open the Debug dialog (Run > Open Debug Dialog...) and create a new **Remote Java Application** configuration with the following settings: * *Project:* your project name * *Connection Type:* Standard (Socket Attach) * *Host:* localhost * *Port:* 8787 **3. Debugging** So, all you have to do any time you want to debug the app is: * set a break point * launch the batch file in a console * launch the debug configuration --- You can track this issue in [bug 122429](https://bugs.eclipse.org/bugs/show_bug.cgi?id=122429). You can work round this issue in your application by using an abstraction layer as described [here](http://illegalargumentexception.blogspot.com/2010/09/java-systemconsole-ides-and-testing.html).
104,267
<p>in short: <strong>is there any way to find the current directory full path of a xul application?</strong></p> <p>long explanation:</p> <p>I would like to open some html files in a xul browser application. The path to the html files should be set programmatically from the xul application. The html files reside outside the folder of my xul application, but at the same level. (users will checkout both folders from SVN, no installation available for the xul app)</p> <p>It opened the files just fine if I set a full path like "file:///c:\temp\processing-sample\index.html"</p> <p>what i want to do is to open the file relative to my xul application. </p> <p>I found i can open the user's profile path:</p> <pre><code>var DIR_SERVICE = new Components.Constructor("@mozilla.org/file/directory_service;1", "nsIProperties"); var path = (new DIR_SERVICE()).get("UChrm", Components.interfaces.nsIFile).path; var appletPath; // find directory separator type if (path.search(/\\/) != -1) { appletPath = path + "\\myApp\\content\\applet.html" } else { appletPath = path + "/myApp/content/applet.html" } // Cargar el applet en el iframe var appletFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); appletFile.initWithPath(appletPath); var appletURL = Components.classes["@mozilla.org/network/protocol;1?name=file"].createInstance(Components.interfaces.nsIFileProtocolHandler).getURLSpecFromFile(appletFile); var appletFrame = document.getElementById("appletFrame"); appletFrame.setAttribute("src", appletURL); </code></pre> <p><strong>is there any way to find the current directory full path of a xul application?</strong></p>
[ { "answer_id": 104950, "author": "rec", "author_id": 14022, "author_profile": "https://Stackoverflow.com/users/14022", "pm_score": 3, "selected": true, "text": "<p>I found a workaround: <a href=\"http://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO\" rel=\"nofollow noreferrer\">ht...
2008/09/19
[ "https://Stackoverflow.com/questions/104267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14022/" ]
in short: **is there any way to find the current directory full path of a xul application?** long explanation: I would like to open some html files in a xul browser application. The path to the html files should be set programmatically from the xul application. The html files reside outside the folder of my xul application, but at the same level. (users will checkout both folders from SVN, no installation available for the xul app) It opened the files just fine if I set a full path like "file:///c:\temp\processing-sample\index.html" what i want to do is to open the file relative to my xul application. I found i can open the user's profile path: ``` var DIR_SERVICE = new Components.Constructor("@mozilla.org/file/directory_service;1", "nsIProperties"); var path = (new DIR_SERVICE()).get("UChrm", Components.interfaces.nsIFile).path; var appletPath; // find directory separator type if (path.search(/\\/) != -1) { appletPath = path + "\\myApp\\content\\applet.html" } else { appletPath = path + "/myApp/content/applet.html" } // Cargar el applet en el iframe var appletFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile); appletFile.initWithPath(appletPath); var appletURL = Components.classes["@mozilla.org/network/protocol;1?name=file"].createInstance(Components.interfaces.nsIFileProtocolHandler).getURLSpecFromFile(appletFile); var appletFrame = document.getElementById("appletFrame"); appletFrame.setAttribute("src", appletURL); ``` **is there any way to find the current directory full path of a xul application?**
I found a workaround: <http://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO> i cannot exactly open a file using a relative path "../../index.html" but i can get the app directory and work with that. ``` var DIR_SERVICE = new Components.Constructor("@mozilla.org/file/directory_service;1", "nsIProperties"); var path = (new DIR_SERVICE()).get(resource:app, Components.interfaces.nsIFile).path; var appletPath; ```
104,292
<p>I'm getting the following error when trying to build my app using Team Foundation Build:</p> <blockquote> <p>C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets(1682,9): error MSB3554: Cannot write to the output file "obj\Release\Company.Redacted.BlahBlah.Localization.Subsystems. Startup_Shutdown_Processing.StartupShutdownProcessingMessages.de.resources". The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.</p> </blockquote> <p>My project builds fine on my development machine as the source is only two folders deep, but TF Build seems to use a really deep directory that is causing it to break. How do I change the folders that are used?</p> <p><strong>Edit:</strong> I checked the .proj file for my build that is stored in source control and found the following:</p> <pre><code>&lt;!-- BUILD DIRECTORY This property is included only for backwards compatibility. The build directory used for a build definition is now stored in the database, as the BuildDirectory property of the definition's DefaultBuildAgent. For compatibility with V1 clients, keep this property in sync with the value in the database. --&gt; &lt;BuildDirectoryPath&gt;UNKNOWN&lt;/BuildDirectoryPath&gt; </code></pre> <p>If this is stored in the database how do I change it?</p> <p><strong>Edit:</strong> Found the following blog post which may be pointing me torward the solution. Now I just need to figure out how to change the setting in the Build Agent. <a href="http://blogs.msdn.com/jpricket/archive/2007/04/30/build-type-builddirectorypath-build-agent-working-directory.aspx" rel="noreferrer">http://blogs.msdn.com/jpricket/archive/2007/04/30/build-type-builddirectorypath-build-agent-working-directory.aspx</a></p> <p>Currently my working directory is "$(Temp)\$(BuildDefinitionPath)" but now I don't know what wildcards are available to specify a different folder.</p>
[ { "answer_id": 104302, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 0, "selected": false, "text": "<p>you have to checkout the build script file, from the source control explorer, and get your elbows dirty replacing...
2008/09/19
[ "https://Stackoverflow.com/questions/104292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
I'm getting the following error when trying to build my app using Team Foundation Build: > > C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets(1682,9): error MSB3554: Cannot write to the output file "obj\Release\Company.Redacted.BlahBlah.Localization.Subsystems. > Startup\_Shutdown\_Processing.StartupShutdownProcessingMessages.de.resources". The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters. > > > My project builds fine on my development machine as the source is only two folders deep, but TF Build seems to use a really deep directory that is causing it to break. How do I change the folders that are used? **Edit:** I checked the .proj file for my build that is stored in source control and found the following: ``` <!-- BUILD DIRECTORY This property is included only for backwards compatibility. The build directory used for a build definition is now stored in the database, as the BuildDirectory property of the definition's DefaultBuildAgent. For compatibility with V1 clients, keep this property in sync with the value in the database. --> <BuildDirectoryPath>UNKNOWN</BuildDirectoryPath> ``` If this is stored in the database how do I change it? **Edit:** Found the following blog post which may be pointing me torward the solution. Now I just need to figure out how to change the setting in the Build Agent. <http://blogs.msdn.com/jpricket/archive/2007/04/30/build-type-builddirectorypath-build-agent-working-directory.aspx> Currently my working directory is "$(Temp)\$(BuildDefinitionPath)" but now I don't know what wildcards are available to specify a different folder.
You need to edit the build working directory of your Build Agent so that the begging path is a little smaller. To edit the build agent, right click on the "Builds" node and select "Manage Build Agents..." I personally use something like c:\bw\$(BuildDefinitionId). $(BuildDefinitionId) translates into the id of the build definition (hence the name :-) ), which means you get a build path starting with something like c:\bw\36 rather than c:\Documents and Settings\tfsbuild\Local Settings\Temp\BuildDefinitionName Good luck, Martin.
104,293
<p>I'm getting a 404 error when trying to run another web service on an IIS 6 server which is also running Sharepoint 2003. I'm pretty sure this is an issue with sharepoint taking over IIS configuration. Is there a way to make a certain web service or web site be ignored by whatever Sharepoint is doing?</p>
[ { "answer_id": 104340, "author": "kemiller2002", "author_id": 1942, "author_profile": "https://Stackoverflow.com/users/1942", "pm_score": 0, "selected": false, "text": "<p>you'll have to go into the SharePoint admin console and explicitely allow that web application to run on on the same...
2008/09/19
[ "https://Stackoverflow.com/questions/104293", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8852/" ]
I'm getting a 404 error when trying to run another web service on an IIS 6 server which is also running Sharepoint 2003. I'm pretty sure this is an issue with sharepoint taking over IIS configuration. Is there a way to make a certain web service or web site be ignored by whatever Sharepoint is doing?
I found the command line solution. ``` STSADM.EXE -o addpath -url http://localhost/<your web service/app> -type exclusion ```
104,322
<p>How do you install Boost on MacOS? Right now I can't find bjam for the Mac.</p>
[ { "answer_id": 104389, "author": "dies", "author_id": 19170, "author_profile": "https://Stackoverflow.com/users/19170", "pm_score": 8, "selected": true, "text": "<p>Download <a href=\"https://www.macports.org/\" rel=\"noreferrer\">MacPorts</a>, and run the following command:</p>\n\n<pre>...
2008/09/19
[ "https://Stackoverflow.com/questions/104322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ]
How do you install Boost on MacOS? Right now I can't find bjam for the Mac.
Download [MacPorts](https://www.macports.org/), and run the following command: ``` sudo port install boost ```
104,323
<p>I am quite new to JavaScript libraries. I wanted to replace my current code with jQuery. My current code looks like this:</p> <pre><code>var req; function createRequest() { var key = document.getElementById("key"); var keypressed = document.getElementById("keypressed"); keypressed.value = key.value; var url = "/My_Servlet/response?key=" + escape(key.value); if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } req.open("Get", url, true); req.onreadystatechange = callback; req.send(null); } function callback() { if (req.readyState == 4) { if (req.status == 200) { var decimal = document.getElementById('decimal'); decimal.value = req.responseText; } } clear(); } </code></pre> <p>I wanted to replace my code with something a little friendlier like jQuery's</p> <pre><code>$.get(url, callback); </code></pre> <p>However it doesn't call my callback function.</p> <p>Also I would like to call a function called <code>createRequest</code> continuously. Does jQuery have a nice way of doing that? ­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 104343, "author": "Wes P", "author_id": 13611, "author_profile": "https://Stackoverflow.com/users/13611", "pm_score": 2, "selected": false, "text": "<p>I don't think jQuery implements a timeout function, but plain old javascript does it rather nicely :)</p>\n" }, { ...
2008/09/19
[ "https://Stackoverflow.com/questions/104323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I am quite new to JavaScript libraries. I wanted to replace my current code with jQuery. My current code looks like this: ``` var req; function createRequest() { var key = document.getElementById("key"); var keypressed = document.getElementById("keypressed"); keypressed.value = key.value; var url = "/My_Servlet/response?key=" + escape(key.value); if (window.XMLHttpRequest) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } req.open("Get", url, true); req.onreadystatechange = callback; req.send(null); } function callback() { if (req.readyState == 4) { if (req.status == 200) { var decimal = document.getElementById('decimal'); decimal.value = req.responseText; } } clear(); } ``` I wanted to replace my code with something a little friendlier like jQuery's ``` $.get(url, callback); ``` However it doesn't call my callback function. Also I would like to call a function called `createRequest` continuously. Does jQuery have a nice way of doing that? ­­­­­­­­­­­­­­­­­­­­­­­
``` $.get(url, {}, callback); ``` should do the trick. Your callback could be simplified like this: ``` function callback(content){ $('#decimal').val(content); } ``` Or even shorter: ``` $.get(url, {}, function(content){ $('#decimal').val(content); }); ``` And all in all I think this should work: ``` function createRequest() { var keyValue = $('#key').val(); $('#keypressed').val(keyValue); var url = "/My_Servlet/response"; $.get(url, {key: keyValue}, function(content){ $('#decimal').val(content); }); } ```
104,330
<p>I have a table with a "Date" column, and I would like to do a query that does the following:</p> <p>If the date is a <strong>Monday</strong>, <strong>Tuesday</strong>, <strong>Wednesday</strong>, or <strong>Thursday</strong>, the displayed date should be shifted up by 1 day, as in <pre>DATEADD(day, 1, [Date])</pre> On the other hand, if it is a <strong>Friday</strong>, the displayed date should be incremented by 3 days (i.e. so it becomes the following <em>Monday</em>).</p> <p>How do I do this in my SELECT statement? As in,</p> <pre>SELECT somewayofdoingthis([Date]) FROM myTable</pre> <p>(This is SQL Server 2000.)</p>
[ { "answer_id": 104357, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 0, "selected": false, "text": "<p>you need to create a SQL Function that does this transformation for you. </p>\n" }, { "answer_id": 104362, ...
2008/09/19
[ "https://Stackoverflow.com/questions/104330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10675/" ]
I have a table with a "Date" column, and I would like to do a query that does the following: If the date is a **Monday**, **Tuesday**, **Wednesday**, or **Thursday**, the displayed date should be shifted up by 1 day, as in ``` DATEADD(day, 1, [Date]) ``` On the other hand, if it is a **Friday**, the displayed date should be incremented by 3 days (i.e. so it becomes the following *Monday*). How do I do this in my SELECT statement? As in, ``` SELECT somewayofdoingthis([Date]) FROM myTable ``` (This is SQL Server 2000.)
Here is how I would do it. I do recommend a function like above if you will be using this in other places. ``` CASE WHEN DATEPART(dw, [Date]) IN (2,3,4,5) THEN DATEADD(d, 1, [Date]) WHEN DATEPART(dw, [Date]) = 6 THEN DATEADD(d, 3, [Date]) ELSE [Date] END AS [ConvertedDate] ```
104,339
<p>I'm doing some Objective-C programming that involves parsing an NSXmlDocument and populating an objects properties from the result.</p> <p>First version looked like this:</p> <pre><code>if([elementName compare:@"companyName"] == 0) [character setCorporationName:currentElementText]; else if([elementName compare:@"corporationID"] == 0) [character setCorporationID:currentElementText]; else if([elementName compare:@"name"] == 0) ... </code></pre> <p>But I don't like the <code>if-else-if-else</code> pattern this produces. Looking at the <code>switch</code> statement I see that i can only handle <code>ints</code>, <code>chars</code> etc and not objects... so is there a better implementation pattern I'm not aware of?</p> <p>BTW I did actually come up with a better solution for setting the object's properties, but I want to know specifically about the <code>if</code>-<code>else</code> vs <code>switch</code> pattern in Objective-C</p>
[ { "answer_id": 104584, "author": "Bradley Harris", "author_id": 10503, "author_profile": "https://Stackoverflow.com/users/10503", "pm_score": 2, "selected": false, "text": "<p>The most common refactoring suggested for eliminating if-else or switch statements is introducing polymorphism (...
2008/09/19
[ "https://Stackoverflow.com/questions/104339", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18590/" ]
I'm doing some Objective-C programming that involves parsing an NSXmlDocument and populating an objects properties from the result. First version looked like this: ``` if([elementName compare:@"companyName"] == 0) [character setCorporationName:currentElementText]; else if([elementName compare:@"corporationID"] == 0) [character setCorporationID:currentElementText]; else if([elementName compare:@"name"] == 0) ... ``` But I don't like the `if-else-if-else` pattern this produces. Looking at the `switch` statement I see that i can only handle `ints`, `chars` etc and not objects... so is there a better implementation pattern I'm not aware of? BTW I did actually come up with a better solution for setting the object's properties, but I want to know specifically about the `if`-`else` vs `switch` pattern in Objective-C
I hope you'll all forgive me for going out on a limb here, but I would like to address the more general question of parsing XML documents in Cocoa without the need of if-else statements. The question as originally stated assigns the current element text to an instance variable of the character object. As jmah pointed out, this can be solved using key-value coding. However, in a more complex XML document this might not be possible. Consider for example the following. ``` <xmlroot> <corporationID> <stockSymbol>EXAM</stockSymbol> <uuid>31337</uuid> </corporationID> <companyName>Example Inc.</companyName> </xmlroot> ``` There are multiple approaches to dealing with this. Off of the top of my head, I can think of two using NSXMLDocument. The first uses NSXMLElement. It is fairly straightforward and does not involve the if-else issue at all. You simply get the root element and go through its named elements one by one. ``` NSXMLElement* root = [xmlDocument rootElement]; // Assuming that we only have one of each element. [character setCorperationName:[[[root elementsForName:@"companyName"] objectAtIndex:0] stringValue]]; NSXMLElement* corperationId = [root elementsForName:@"corporationID"]; [character setCorperationStockSymbol:[[[corperationId elementsForName:@"stockSymbol"] objectAtIndex:0] stringValue]]; [character setCorperationUUID:[[[corperationId elementsForName:@"uuid"] objectAtIndex:0] stringValue]]; ``` The next one uses the more general NSXMLNode, walks through the tree, and directly uses the if-else structure. ``` // The first line is the same as the last example, because NSXMLElement inherits from NSXMLNode NSXMLNode* aNode = [xmlDocument rootElement]; while(aNode = [aNode nextNode]){ if([[aNode name] isEqualToString:@"companyName"]){ [character setCorperationName:[aNode stringValue]]; }else if([[aNode name] isEqualToString:@"corporationID"]){ NSXMLNode* correctParent = aNode; while((aNode = [aNode nextNode]) == nil && [aNode parent != correctParent){ if([[aNode name] isEqualToString:@"stockSymbol"]){ [character setCorperationStockSymbol:[aNode stringValue]]; }else if([[aNode name] isEqualToString:@"uuid"]){ [character setCorperationUUID:[aNode stringValue]]; } } } } ``` This is a good candidate for eliminating the if-else structure, but like the original problem, we can't simply use switch-case here. However, we can still eliminate if-else by using performSelector. The first step is to define the a method for each element. ``` - (NSNode*)parse_companyName:(NSNode*)aNode { [character setCorperationName:[aNode stringValue]]; return aNode; } - (NSNode*)parse_corporationID:(NSNode*)aNode { NSXMLNode* correctParent = aNode; while((aNode = [aNode nextNode]) == nil && [aNode parent != correctParent){ [self invokeMethodForNode:aNode prefix:@"parse_corporationID_"]; } return [aNode previousNode]; } - (NSNode*)parse_corporationID_stockSymbol:(NSNode*)aNode { [character setCorperationStockSymbol:[aNode stringValue]]; return aNode; } - (NSNode*)parse_corporationID_uuid:(NSNode*)aNode { [character setCorperationUUID:[aNode stringValue]]; return aNode; } ``` The magic happens in the invokeMethodForNode:prefix: method. We generate the selector based on the name of the element, and perform that selector with aNode as the only parameter. Presto bango, we've eliminated the need for an if-else statement. Here's the code for that method. ``` - (NSNode*)invokeMethodForNode:(NSNode*)aNode prefix:(NSString*)aPrefix { NSNode* ret = nil; NSString* methodName = [NSString stringWithFormat:@"%@%@:", prefix, [aNode name]]; SEL selector = NSSelectorFromString(methodName); if([self respondsToSelector:selector]) ret = [self performSelector:selector withObject:aNode]; return ret; } ``` Now, instead of our larger if-else statement (the one that differentiated between companyName and corporationID), we can simply write one line of code ``` NSXMLNode* aNode = [xmlDocument rootElement]; while(aNode = [aNode nextNode]){ aNode = [self invokeMethodForNode:aNode prefix:@"parse_"]; } ``` Now I apologize if I got any of this wrong, it's been a while since I've written anything with NSXMLDocument, it's late at night and I didn't actually test this code. So if you see anything wrong, please leave a comment or edit this answer. However, I believe I have just shown how properly-named selectors can be used in Cocoa to completely eliminate if-else statements in cases like this. There are a few gotchas and corner cases. The performSelector: family of methods only takes 0, 1, or 2 argument methods whose arguments and return types are objects, so if the types of the arguments and return type are not objects, or if there are more than two arguments, then you would have to use an NSInvocation to invoke it. You have to make sure that the method names you generate aren't going to call other methods, especially if the target of the call is another object, and this particular method naming scheme won't work on elements with non-alphanumeric characters. You could get around that by escaping the XML element names in your method names somehow, or by building an NSDictionary using the method names as the keys and the selectors as the values. This can get pretty memory intensive and end up taking a longer time. performSelector dispatch like I described is pretty fast. For very large if-else statements, this method may even be faster than an if-else statement.
104,363
<p>I'm trying to upgrade a package using yum on Fedora 8. The package is <code>elfutils</code>. Here's what I have installed locally:</p> <pre><code>$ yum info elfutils Installed Packages Name : elfutils Arch : x86_64 Version: 0.130 Release: 3.fc8 Size : 436 k Repo : installed Summary: A collection of utilities and DSOs to handle compiled objects </code></pre> <p>There's a bug in this version, and according to the <a href="https://bugzilla.redhat.com/show_bug.cgi?id=377241" rel="nofollow noreferrer">bug report</a>, a newer version has been pushed to the Fedora 8 stable repository. But, if I try to update:</p> <pre><code>$ yum update elfutils Setting up Update Process Could not find update match for elfutils No Packages marked for Update </code></pre> <p>Here are my repositories:</p> <pre><code>$ yum repolist enabled repo id repo name status InstallMedia Fedora 8 enabled fedora Fedora 8 - x86_64 enabled updates Fedora 8 - x86_64 - Updates enabled </code></pre> <p>What am I missing?</p>
[ { "answer_id": 104479, "author": "ethyreal", "author_id": 18159, "author_profile": "https://Stackoverflow.com/users/18159", "pm_score": 1, "selected": false, "text": "<p>i know this seems silly but did you try removing it and reinstalling?</p>\n\n<pre><code>yum remove elfutils\n</code></...
2008/09/19
[ "https://Stackoverflow.com/questions/104363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/742/" ]
I'm trying to upgrade a package using yum on Fedora 8. The package is `elfutils`. Here's what I have installed locally: ``` $ yum info elfutils Installed Packages Name : elfutils Arch : x86_64 Version: 0.130 Release: 3.fc8 Size : 436 k Repo : installed Summary: A collection of utilities and DSOs to handle compiled objects ``` There's a bug in this version, and according to the [bug report](https://bugzilla.redhat.com/show_bug.cgi?id=377241), a newer version has been pushed to the Fedora 8 stable repository. But, if I try to update: ``` $ yum update elfutils Setting up Update Process Could not find update match for elfutils No Packages marked for Update ``` Here are my repositories: ``` $ yum repolist enabled repo id repo name status InstallMedia Fedora 8 enabled fedora Fedora 8 - x86_64 enabled updates Fedora 8 - x86_64 - Updates enabled ``` What am I missing?
OK, I figured it out. I needed to upgrade the `fedora-release` package. That allowed me to see all of the updated packages. Thanks to ethyreal for pointing me to the Yum upgrade FAQ.
104,420
<p>How do I generate all the permutations of a list? For example:</p> <pre><code>permutations([]) [] permutations([1]) [1] permutations([1, 2]) [1, 2] [2, 1] permutations([1, 2, 3]) [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1] </code></pre>
[ { "answer_id": 104426, "author": "Ricardo Reyes", "author_id": 3399, "author_profile": "https://Stackoverflow.com/users/3399", "pm_score": 5, "selected": false, "text": "<p>This solution implements a generator, to avoid holding all the permutations on memory:</p>\n\n<pre><code>def permut...
2008/09/19
[ "https://Stackoverflow.com/questions/104420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3399/" ]
How do I generate all the permutations of a list? For example: ``` permutations([]) [] permutations([1]) [1] permutations([1, 2]) [1, 2] [2, 1] permutations([1, 2, 3]) [1, 2, 3] [1, 3, 2] [2, 1, 3] [2, 3, 1] [3, 1, 2] [3, 2, 1] ```
Use [`itertools.permutations`](https://docs.python.org/3/library/itertools.html#itertools.permutations) from the **standard library**: ``` import itertools list(itertools.permutations([1, 2, 3])) ``` --- Adapted from [here](http://code.activestate.com/recipes/252178/) is a demonstration of how `itertools.permutations` might be implemented: ``` def permutations(elements): if len(elements) <= 1: yield elements return for perm in permutations(elements[1:]): for i in range(len(elements)): # nb elements[0:1] works in both string and list contexts yield perm[:i] + elements[0:1] + perm[i:] ``` A couple of alternative approaches are listed in the documentation of `itertools.permutations`. Here's one: ``` def permutations(iterable, r=None): # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC # permutations(range(3)) --> 012 021 102 120 201 210 pool = tuple(iterable) n = len(pool) r = n if r is None else r if r > n: return indices = range(n) cycles = range(n, n-r, -1) yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i+1:] + indices[i:i+1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i in indices[:r]) break else: return ``` And another, based on `itertools.product`: ``` def permutations(iterable, r=None): pool = tuple(iterable) n = len(pool) r = n if r is None else r for indices in product(range(n), repeat=r): if len(set(indices)) == r: yield tuple(pool[i] for i in indices) ```
104,439
<p>The Eclipse projects are all stored in the Eclipse Foundation CVS servers. Using the source is a great way to debug your code and to figure out how to do new things. </p> <p>Unfortunately in a large software project like BIRT, it can be difficult to know which projects and versions are required for a particular build. So what is the best way to get the source for a particular build?</p>
[ { "answer_id": 104426, "author": "Ricardo Reyes", "author_id": 3399, "author_profile": "https://Stackoverflow.com/users/3399", "pm_score": 5, "selected": false, "text": "<p>This solution implements a generator, to avoid holding all the permutations on memory:</p>\n\n<pre><code>def permut...
2008/09/19
[ "https://Stackoverflow.com/questions/104439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5412/" ]
The Eclipse projects are all stored in the Eclipse Foundation CVS servers. Using the source is a great way to debug your code and to figure out how to do new things. Unfortunately in a large software project like BIRT, it can be difficult to know which projects and versions are required for a particular build. So what is the best way to get the source for a particular build?
Use [`itertools.permutations`](https://docs.python.org/3/library/itertools.html#itertools.permutations) from the **standard library**: ``` import itertools list(itertools.permutations([1, 2, 3])) ``` --- Adapted from [here](http://code.activestate.com/recipes/252178/) is a demonstration of how `itertools.permutations` might be implemented: ``` def permutations(elements): if len(elements) <= 1: yield elements return for perm in permutations(elements[1:]): for i in range(len(elements)): # nb elements[0:1] works in both string and list contexts yield perm[:i] + elements[0:1] + perm[i:] ``` A couple of alternative approaches are listed in the documentation of `itertools.permutations`. Here's one: ``` def permutations(iterable, r=None): # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC # permutations(range(3)) --> 012 021 102 120 201 210 pool = tuple(iterable) n = len(pool) r = n if r is None else r if r > n: return indices = range(n) cycles = range(n, n-r, -1) yield tuple(pool[i] for i in indices[:r]) while n: for i in reversed(range(r)): cycles[i] -= 1 if cycles[i] == 0: indices[i:] = indices[i+1:] + indices[i:i+1] cycles[i] = n - i else: j = cycles[i] indices[i], indices[-j] = indices[-j], indices[i] yield tuple(pool[i] for i in indices[:r]) break else: return ``` And another, based on `itertools.product`: ``` def permutations(iterable, r=None): pool = tuple(iterable) n = len(pool) r = n if r is None else r for indices in product(range(n), repeat=r): if len(set(indices)) == r: yield tuple(pool[i] for i in indices) ```
104,458
<p>How can styles be applied to CheckBoxList ListItems. Unlike other controls, such as the Repeater where you can specify <code>&lt;ItemStyle&gt;</code>, you can't seem to specify a style for each individual control.</p> <p>Is there some sort of work around?</p>
[ { "answer_id": 104502, "author": "Andrew Burgess", "author_id": 12096, "author_profile": "https://Stackoverflow.com/users/12096", "pm_score": 4, "selected": false, "text": "<p>It seems the best way to do this is to create a new CssClass. ASP.NET translates CheckBoxList into a table stru...
2008/09/19
[ "https://Stackoverflow.com/questions/104458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12096/" ]
How can styles be applied to CheckBoxList ListItems. Unlike other controls, such as the Repeater where you can specify `<ItemStyle>`, you can't seem to specify a style for each individual control. Is there some sort of work around?
You can add Attributes to ListItems programmatically as follows. Say you've got a CheckBoxList and you are adding ListItems. You can add Attributes along the way. ``` ListItem li = new ListItem("Richard Byrd", "11"); li.Selected = false; li.Attributes.Add("Style", "color: red;"); CheckBoxList1.Items.Add(li); ``` This will make the color of the listitem text red. Experiment and have fun.
104,485
<p>I'm trying to skin HTML output which I don't have control over. One of the elements is a <code>div</code> with a <code>style="overflow: auto"</code> attribute.<br> Is there a way in CSS to force that <code>div</code> to use <code>overflow: hidden;</code>?</p>
[ { "answer_id": 104497, "author": "17 of 26", "author_id": 2284, "author_profile": "https://Stackoverflow.com/users/2284", "pm_score": 0, "selected": false, "text": "<p>As far as I know, styles on the actual HTML elements override anything you can do in separate CSS style.</p>\n\n<p>You c...
2008/09/19
[ "https://Stackoverflow.com/questions/104485", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4898/" ]
I'm trying to skin HTML output which I don't have control over. One of the elements is a `div` with a `style="overflow: auto"` attribute. Is there a way in CSS to force that `div` to use `overflow: hidden;`?
You can add `!important` to the end of your style, like this: ```css element { overflow: hidden !important; } ``` This is something you should not rely on normally, but in your case that's the best option. Changing the value in Javascript strays from the best practice of separating markup, presentation, and behavior (html/css/javascript).
104,487
<p>Right now I'm doing something like this:</p> <pre><code>RewriteRule ^/?logout(/)?$ logout.php RewriteRule ^/?config(/)?$ config.php </code></pre> <p>I would much rather have one rules that would do the same thing for each url, so I don't have to keep adding them every time I add a new file.</p> <p>Also, I like to match things like '/config/new' to 'config_new.php' if that is possible. I am guessing some regexp would let me accomplish this?</p>
[ { "answer_id": 104573, "author": "Gabriel Ross", "author_id": 10751, "author_profile": "https://Stackoverflow.com/users/10751", "pm_score": 3, "selected": true, "text": "<p>Try:</p>\n\n<p>RewriteRule ^/?(\\w+)/?$ $1.php</p>\n\n<p>the $1 is the content of the first captured string in brac...
2008/09/19
[ "https://Stackoverflow.com/questions/104487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15000/" ]
Right now I'm doing something like this: ``` RewriteRule ^/?logout(/)?$ logout.php RewriteRule ^/?config(/)?$ config.php ``` I would much rather have one rules that would do the same thing for each url, so I don't have to keep adding them every time I add a new file. Also, I like to match things like '/config/new' to 'config\_new.php' if that is possible. I am guessing some regexp would let me accomplish this?
Try: RewriteRule ^/?(\w+)/?$ $1.php the $1 is the content of the first captured string in brackets. The brackets around the 2nd slash are not needed. edit: For the other match, try this: RewriteRule ^/?(\w+)/(\w+)/?$ $1\_$2.php
104,516
<p>In PHP, the HEREDOC string declarations are really useful for outputting a block of html. You can have it parse in variables just by prefixing them with $, but for more complicated syntax (like $var[2][3]), you have to put your expression inside {} braces.</p> <p>In PHP 5, it <em>is</em> possible to actually make function calls within {} braces inside a HEREDOC string, but you have to go through a bit of work. The function name itself has to be stored in a variable, and you have to call it like it is a dynamically-named function. For example:</p> <pre><code>$fn = 'testfunction'; function testfunction() { return 'ok'; } $string = &lt;&lt;&lt; heredoc plain text and now a function: {$fn()} heredoc; </code></pre> <p>As you can see, this is a bit more messy than just:</p> <pre><code>$string = &lt;&lt;&lt; heredoc plain text and now a function: {testfunction()} heredoc; </code></pre> <p>There are other ways besides the first code example, such as breaking out of the HEREDOC to call the function, or reversing the issue and doing something like:</p> <pre><code>?&gt; &lt;!-- directly output html and only breaking into php for the function --&gt; plain text and now a function: &lt;?PHP print testfunction(); ?&gt; </code></pre> <p>The latter has the disadvantage that the output is directly put into the output stream (unless I'm using output buffering), which might not be what I want.</p> <p>So, the essence of my question is: is there a more elegant way to approach this?</p> <p><b>Edit based on responses:</b> It certainly does seem like some kind of template engine would make my life much easier, but it would require me basically invert my usual PHP style. Not that that's a bad thing, but it explains my inertia.. I'm up for figuring out ways to make life easier though, so I'm looking into templates now.</p>
[ { "answer_id": 104556, "author": "boxxar", "author_id": 15732, "author_profile": "https://Stackoverflow.com/users/15732", "pm_score": 6, "selected": false, "text": "<p>I would do the following:</p>\n\n<pre><code>$string = &lt;&lt;&lt; heredoc\nplain text and now a function: %s\nheredoc;\...
2008/09/19
[ "https://Stackoverflow.com/questions/104516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9330/" ]
In PHP, the HEREDOC string declarations are really useful for outputting a block of html. You can have it parse in variables just by prefixing them with $, but for more complicated syntax (like $var[2][3]), you have to put your expression inside {} braces. In PHP 5, it *is* possible to actually make function calls within {} braces inside a HEREDOC string, but you have to go through a bit of work. The function name itself has to be stored in a variable, and you have to call it like it is a dynamically-named function. For example: ``` $fn = 'testfunction'; function testfunction() { return 'ok'; } $string = <<< heredoc plain text and now a function: {$fn()} heredoc; ``` As you can see, this is a bit more messy than just: ``` $string = <<< heredoc plain text and now a function: {testfunction()} heredoc; ``` There are other ways besides the first code example, such as breaking out of the HEREDOC to call the function, or reversing the issue and doing something like: ``` ?> <!-- directly output html and only breaking into php for the function --> plain text and now a function: <?PHP print testfunction(); ?> ``` The latter has the disadvantage that the output is directly put into the output stream (unless I'm using output buffering), which might not be what I want. So, the essence of my question is: is there a more elegant way to approach this? **Edit based on responses:** It certainly does seem like some kind of template engine would make my life much easier, but it would require me basically invert my usual PHP style. Not that that's a bad thing, but it explains my inertia.. I'm up for figuring out ways to make life easier though, so I'm looking into templates now.
I would not use HEREDOC at all for this, personally. It just doesn't make for a good "template building" system. All your HTML is locked down in a string which has several disadvantages * No option for WYSIWYG * No code completion for HTML from IDEs * Output (HTML) locked to logic files * You end up having to use hacks like what you're trying to do now to achieve more complex templating, such as looping Get a basic template engine, or just use PHP with includes - it's why the language has the `<?php` and `?>` delimiters. **template\_file.php** ``` <html> <head> <title><?php echo $page_title; ?></title> </head> <body> <?php echo getPageContent(); ?> </body> ``` **index.php** ``` <?php $page_title = "This is a simple demo"; function getPageContent() { return '<p>Hello World!</p>'; } include('template_file.php'); ```
104,520
<p>I have been seriously disappointed with WPF validation system. Anyway! How can I validate the complete form by clicking the "button"? </p> <p>For some reason everything in WPF is soo complicated! I can do the validation in 1 line of code in ASP.NET which requires like 10-20 lines of code in WPF!!</p> <p>I can do this using my own ValidationEngine framework: </p> <pre><code>Customer customer = new Customer(); customer.FirstName = "John"; customer.LastName = String.Empty; ValidationEngine.Validate(customer); if (customer.BrokenRules.Count &gt; 0) { // do something display the broken rules! } </code></pre>
[ { "answer_id": 104957, "author": "adriaanp", "author_id": 12230, "author_profile": "https://Stackoverflow.com/users/12230", "pm_score": 2, "selected": false, "text": "<p>I would suggest to look at the IDataErrorInfo interface on your business object. Also have a look at this article: <a ...
2008/09/19
[ "https://Stackoverflow.com/questions/104520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3797/" ]
I have been seriously disappointed with WPF validation system. Anyway! How can I validate the complete form by clicking the "button"? For some reason everything in WPF is soo complicated! I can do the validation in 1 line of code in ASP.NET which requires like 10-20 lines of code in WPF!! I can do this using my own ValidationEngine framework: ``` Customer customer = new Customer(); customer.FirstName = "John"; customer.LastName = String.Empty; ValidationEngine.Validate(customer); if (customer.BrokenRules.Count > 0) { // do something display the broken rules! } ```
A WPF application should disable the button to submit a form iff the entered data is not valid. You can achieve this by implementing the [IDataErrorInfo](http://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo.aspx) interface on your business object, using Bindings with [`ValidatesOnDataErrors`](http://msdn.microsoft.com/en-us/library/system.windows.data.binding.validatesondataerrors.aspx)`=true`. For customizing the look of individual controls in the case of errors, set a [`Validation.ErrorTemplate`](http://msdn.microsoft.com/en-us/library/system.windows.controls.validation.errortemplate.aspx). ### XAML: ``` <Window x:Class="Example.CustomerWindow" ...> <Window.CommandBindings> <CommandBinding Command="ApplicationCommands.Save" CanExecute="SaveCanExecute" Executed="SaveExecuted" /> </Window.CommandBindings> <StackPanel> <TextBox Text="{Binding FirstName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" /> <TextBox Text="{Binding LastName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" /> <Button Command="ApplicationCommands.Save" IsDefault="True">Save</Button> <TextBlock Text="{Binding Error}"/> </StackPanel> </Window> ``` This creates a `Window` with two `TextBox`es where you can edit the first and last name of a customer. The "Save" button is only enabled if no validation errors have occurred. The `TextBlock` beneath the button shows the current errors, so the user knows what's up. The default `ErrorTemplate` is a thin red border around the erroneous Control. If that doesn't fit into you visual concept, look at [Validation in Windows Presentation Foundation](http://www.codeproject.com/KB/WPF/wpfvalidation.aspx) article on CodeProject for an in-depth look into what can be done about that. To get the window to actually work, there has to be a bit infrastructure in the Window and the Customer. ### Code Behind ``` // The CustomerWindow class receives the Customer to display // and manages the Save command public class CustomerWindow : Window { private Customer CurrentCustomer; public CustomerWindow(Customer c) { // store the customer for the bindings DataContext = CurrentCustomer = c; InitializeComponent(); } private void SaveCanExecute(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = ValidationEngine.Validate(CurrentCustomer); } private void SaveExecuted(object sender, ExecutedRoutedEventArgs e) { CurrentCustomer.Save(); } } public class Customer : IDataErrorInfo, INotifyPropertyChanged { // holds the actual value of FirstName private string FirstNameBackingStore; // the accessor for FirstName. Only accepts valid values. public string FirstName { get { return FirstNameBackingStore; } set { FirstNameBackingStore = value; ValidationEngine.Validate(this); OnPropertyChanged("FirstName"); } } // similar for LastName string IDataErrorInfo.Error { get { return String.Join("\n", BrokenRules.Values); } } string IDataErrorInfo.this[string columnName] { get { return BrokenRules[columnName]; } } } ``` An obvious improvement would be to move the `IDataErrorInfo` implementation up the class hierarchy, since it only depends on the `ValidationEngine`, but not the business object. While this is indeed more code than the simple example you provided, it also has quite a bit more of functionality than only checking for validity. This gives you fine grained, and automatically updated indications to the user about validation problems and automatically disables the "Save" button as long as the user tries to enter invalid data.
104,525
<p>We have a warm sql backup. full backup nightly, txn logs shipped every so often during the day and restored. I need to move the data files to another disk. These DB's are in a "warm backup" state (such that I can't unmark them as read-only - "Error 5063: Database '&lt;dbname>' is in warm standby. A warm-standby database is read-only. ") and am worried about detaching and re-attaching. </p> <p>How do we obtain the "warm backup" status after detach/attach operations are complete?</p>
[ { "answer_id": 104762, "author": "boes", "author_id": 17746, "author_profile": "https://Stackoverflow.com/users/17746", "pm_score": 3, "selected": true, "text": "<p>The only solution I know is to create a complete backup of your active database and restore this backup to a copy of the da...
2008/09/19
[ "https://Stackoverflow.com/questions/104525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10235/" ]
We have a warm sql backup. full backup nightly, txn logs shipped every so often during the day and restored. I need to move the data files to another disk. These DB's are in a "warm backup" state (such that I can't unmark them as read-only - "Error 5063: Database '<dbname>' is in warm standby. A warm-standby database is read-only. ") and am worried about detaching and re-attaching. How do we obtain the "warm backup" status after detach/attach operations are complete?
The only solution I know is to create a complete backup of your active database and restore this backup to a copy of the database in a 'warm backup' state. First create a backup from the active db: ``` backup database activedb to disk='somefile' ``` Then restore the backup on another sql server. If needed you can use the WITH REPLACE option to change the default storage directory ``` restore database warmbackup from disk='somefile' with norecovery, replace .... ``` Now you can create backups of the logs and restore them to the warmbackup with the restore log statement.
104,568
<p>Is there any way that my script can retrieve metadata values that are declared in its own header? I don't see anything promising in the API, except perhaps <code>GM_getValue()</code>. That would of course involve a special name syntax. I have tried, for example: <code>GM_getValue("@name")</code>.</p> <p>The motivation here is to avoid redundant specification.</p> <p>If GM metadata is not directly accessible, perhaps there's a way to read the body of the script itself. It's certainly in memory somewhere, and it wouldn't be too awfully hard to parse for <code>"// @"</code>. (That may be necessary in my case any way, since the value I'm really interested in is <code>@version</code>, which is an extended value read by <a href="http://userscripts.org/" rel="noreferrer">userscripts.org</a>.)</p>
[ { "answer_id": 104814, "author": "Athena", "author_id": 17846, "author_profile": "https://Stackoverflow.com/users/17846", "pm_score": 4, "selected": true, "text": "<p><strong>This answer is out of date :</strong> As of Greasemonkey 0.9.16 (Feb 2012) please see <a href=\"https://stackover...
2008/09/19
[ "https://Stackoverflow.com/questions/104568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14749/" ]
Is there any way that my script can retrieve metadata values that are declared in its own header? I don't see anything promising in the API, except perhaps `GM_getValue()`. That would of course involve a special name syntax. I have tried, for example: `GM_getValue("@name")`. The motivation here is to avoid redundant specification. If GM metadata is not directly accessible, perhaps there's a way to read the body of the script itself. It's certainly in memory somewhere, and it wouldn't be too awfully hard to parse for `"// @"`. (That may be necessary in my case any way, since the value I'm really interested in is `@version`, which is an extended value read by [userscripts.org](http://userscripts.org/).)
**This answer is out of date :** As of Greasemonkey 0.9.16 (Feb 2012) please see [Brock's answer](https://stackoverflow.com/a/10475344/1820) regarding `GM_info` --- Yes. A very simple example is: ``` var metadata=<> // ==UserScript== // @name Reading metadata // @namespace http://www.afunamatata.com/greasemonkey/ // @description Read in metadata from the header // @version 0.9 // @include https://stackoverflow.com/questions/104568/accessing-greasemonkey-metadata-from-within-your-script // ==/UserScript== </>.toString(); GM_log(metadata); ``` See [this thread on the greasemonkey-users group](http://groups.google.com/group/greasemonkey-users/browse_thread/thread/2003daba08cc14b6/62a635f278d8f9fc) for more information. A more robust implementation can be found near the end.
104,587
<p>Everywhere I look always the same explanation pop ups.<br/> Configure the view resolver.</p> <pre><code>&lt;bean id="viewMappings" class="org.springframework.web.servlet.view.ResourceBundleViewResolver"&gt; &lt;property name="basename" value="views" /&gt; &lt;/bean&gt; </code></pre> <p>And then put a file in the classpath named view.properties with some key-value pairs (don't mind the names).<br/></p> <pre><code>logout.class=org.springframework.web.servlet.view.JstlView logout.url=WEB-INF/jsp/logout.jsp </code></pre> <p>What does <code>logout.class</code> and <code>logout.url</code> mean?<br/> How does <code>ResourceBundleViewResolver</code> uses the key-value pairs in the file?<br/> My goal is that when someone enters the URI <code>myserver/myapp/logout.htm</code> the file <code>logout.jsp</code> gets served.</p>
[ { "answer_id": 105481, "author": "Craig Day", "author_id": 5193, "author_profile": "https://Stackoverflow.com/users/5193", "pm_score": 4, "selected": true, "text": "<p>ResourceBundleViewResolver uses the key/vals in views.properties to create view beans (actually created in an internal a...
2008/09/19
[ "https://Stackoverflow.com/questions/104587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2024/" ]
Everywhere I look always the same explanation pop ups. Configure the view resolver. ``` <bean id="viewMappings" class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> <property name="basename" value="views" /> </bean> ``` And then put a file in the classpath named view.properties with some key-value pairs (don't mind the names). ``` logout.class=org.springframework.web.servlet.view.JstlView logout.url=WEB-INF/jsp/logout.jsp ``` What does `logout.class` and `logout.url` mean? How does `ResourceBundleViewResolver` uses the key-value pairs in the file? My goal is that when someone enters the URI `myserver/myapp/logout.htm` the file `logout.jsp` gets served.
ResourceBundleViewResolver uses the key/vals in views.properties to create view beans (actually created in an internal application context). The name of the view bean in your example will be "logout" and it will be a bean of type JstlView. JstlView has an attribute called URL which will be set to "WEB-INF/jsp/logout.jsp". You can set any attribute on the view class in a similar way. What you appear to be missing is your controller/handler layer. If you want /myapp/logout.htm to serve logout.jsp, you must map a Controller into /myapp/logout.htm and that Controller needs to return the view name "logout". The ResourceBundleViewResolver will then be consulted for a bean of that name, and return your instance of JstlView.
104,601
<p>I want to do a <code>Response.Redirect("MyPage.aspx")</code> but have it open in a new browser window. I've done this before without using the JavaScript register script method. I just can't remember how?</p>
[ { "answer_id": 104653, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 3, "selected": false, "text": "<p>This is not possible with Response.Redirect as it happens on the server side and cannot direct your browser to take ...
2008/09/19
[ "https://Stackoverflow.com/questions/104601", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I want to do a `Response.Redirect("MyPage.aspx")` but have it open in a new browser window. I've done this before without using the JavaScript register script method. I just can't remember how?
I just found the answer and it works :) You need to add the following to your server side link/button: ``` OnClientClick="aspnetForm.target ='_blank';" ``` My entire button code looks something like: ``` <asp:LinkButton ID="myButton" runat="server" Text="Click Me!" OnClick="myButton_Click" OnClientClick="aspnetForm.target ='_blank';"/> ``` In the server side OnClick I do a `Response.Redirect("MyPage.aspx");` and the page is opened in a new window. The other part you need to add is to fix the form's target otherwise every link will open in a new window. To do so add the following in the header of your POPUP window. ``` <script type="text/javascript"> function fixform() { if (opener.document.getElementById("aspnetForm").target != "_blank") return; opener.document.getElementById("aspnetForm").target = ""; opener.document.getElementById("aspnetForm").action = opener.location.href; } </script> ``` and ``` <body onload="fixform()"> ```
104,603
<p>Is there a way to iterate (through foreach preferably) over a collection using reflection? I'm iterating over the properties in an object using reflection, and when the program gets to a type that is a collection, I'd like it to iterate over the contents of the collection and be able to access the objects in the collection.</p> <p>At the moment I have an attribute set on all of my properties, with an IsCollection flag set to true on the properties that are collections. My code checks for this flag and if it's true, it gets the Type using reflection. Is there a way to invoke GetEnumerator or Items somehow on a collection to be able to iterate over the items?</p>
[ { "answer_id": 104655, "author": "Adam Driscoll", "author_id": 13688, "author_profile": "https://Stackoverflow.com/users/13688", "pm_score": 0, "selected": false, "text": "<p>When your using reflection you aren't necessarily using an instance of that object. You would have to create an i...
2008/09/19
[ "https://Stackoverflow.com/questions/104603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12999/" ]
Is there a way to iterate (through foreach preferably) over a collection using reflection? I'm iterating over the properties in an object using reflection, and when the program gets to a type that is a collection, I'd like it to iterate over the contents of the collection and be able to access the objects in the collection. At the moment I have an attribute set on all of my properties, with an IsCollection flag set to true on the properties that are collections. My code checks for this flag and if it's true, it gets the Type using reflection. Is there a way to invoke GetEnumerator or Items somehow on a collection to be able to iterate over the items?
I had this issue, but instead of using reflection, i ended up just checking if it was IEnumerable. All collections implement that. ``` if (item is IEnumerable) { foreach (object o in (item as IEnumerable)) { } } else { // reflect over item } ```
104,612
<p>I want to copy a live production database into my local development database. Is there a way to do this without locking the production database?</p> <p>I'm currently using:</p> <pre class="lang-none prettyprint-override"><code>mysqldump -u root --password=xxx -h xxx my_db1 | mysql -u root --password=xxx -h localhost my_db1 </code></pre> <p>But it's locking each table as it runs.</p>
[ { "answer_id": 104628, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 10, "selected": true, "text": "<p>Does the <code>--lock-tables=false</code> option work?</p>\n<p>According to the <a href=\"https://dev.mysql.com/doc...
2008/09/19
[ "https://Stackoverflow.com/questions/104612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13009/" ]
I want to copy a live production database into my local development database. Is there a way to do this without locking the production database? I'm currently using: ```none mysqldump -u root --password=xxx -h xxx my_db1 | mysql -u root --password=xxx -h localhost my_db1 ``` But it's locking each table as it runs.
Does the `--lock-tables=false` option work? According to the [man page](https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#option_mysqldump_lock-tables), if you are dumping InnoDB tables you can use the `--single-transaction` option: ```none --lock-tables, -l Lock all tables before dumping them. The tables are locked with READ LOCAL to allow concurrent inserts in the case of MyISAM tables. For transactional tables such as InnoDB and BDB, --single-transaction is a much better option, because it does not need to lock the tables at all. ``` For **innodb DB**: ``` mysqldump --single-transaction=TRUE -u username -p DB ```
104,618
<p>I've been trying to get into F# on and off for a while but I keep getting put off. Why?</p> <p>Because no matter which 'beginners' resource I try to look at I see very simple examples that start using the operator <code>-&gt;</code>.</p> <p>However, nowhere have I found as yet that provides a clear simple explanation of what this operator means. It's as though it must be so obvious that it doesn't need explanation even to complete newbies.</p> <p>I must therefore be really dense or perhaps it's nearly 3 decades of previous experience holding me back.</p> <p>Can someone please, explain it or point to a truly accessible resource that explains it?</p>
[ { "answer_id": 104744, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 4, "selected": false, "text": "<p>It basically means \"maps to\". Read it that way or as \"is transformed into\" or something like that.</p>\n\n<p>So,...
2008/09/19
[ "https://Stackoverflow.com/questions/104618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17516/" ]
I've been trying to get into F# on and off for a while but I keep getting put off. Why? Because no matter which 'beginners' resource I try to look at I see very simple examples that start using the operator `->`. However, nowhere have I found as yet that provides a clear simple explanation of what this operator means. It's as though it must be so obvious that it doesn't need explanation even to complete newbies. I must therefore be really dense or perhaps it's nearly 3 decades of previous experience holding me back. Can someone please, explain it or point to a truly accessible resource that explains it?
'->' is not an operator. It appears in the F# syntax in a number of places, and its meaning depends on how it is used as part of a larger construct. Inside a type, '->' describes function types as people have described above. For example ``` let f : int -> int = ... ``` says that 'f' is a function that takes an int and returns an int. Inside a lambda ("thing that starts with 'fun' keyword"), '->' is syntax that separates the arguments from the body. For example ``` fun x y -> x + y + 1 ``` is an expression that defines a two argument function with the given implementation. Inside a "match" construct, '->' is syntax that separates patterns from the code that should run if the pattern is matched. For example, in ``` match someList with | [] -> 0 | h::t -> 1 ``` the stuff to the left of each '->' are patterns, and the stuff on the right is what happens if the pattern on the left was matched. The difficulty in understanding may be rooted in the faulty assumption that '->' is "an operator" with a single meaning. An analogy might be "." in C#, if you have never seen any code before, and try to analyze the "." operator based on looking at "obj.Method" and "3.14" and "System.Collections", you may get very confused, because the symbol has different meanings in different contexts. Once you know enough of the language to recognize these contexts, however, things become clear.
104,747
<p>I have a members table in MySQL</p> <pre><code>CREATE TABLE `members` ( `id` int(10) unsigned NOT NULL auto_increment, `name` varchar(65) collate utf8_unicode_ci NOT NULL, `order` tinyint(3) unsigned NOT NULL default '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB; </code></pre> <p>And I would like to let users order the members how they like. I'm storing the order in <code>order</code> column.</p> <p>I'm wondering how to insert new user to be added to the bottom of the list. This is what I have today:</p> <pre><code>$db-&gt;query('insert into members VALUES (0, "new member", 0)'); $lastId = $db-&gt;lastInsertId(); $maxOrder = $db-&gt;fetchAll('select MAX(`order`) max_order FROM members'); $db-&gt;query('update members SET `order` = ? WHERE id = ?', array( $maxOrder[0]['max_order'] + 1, $lastId )); </code></pre> <p>But that's not really precise while when there are several users adding new members at the same time, it might happen the <code>MAX(order)</code> will return the same values.</p> <p>How do you handle such cases?</p>
[ { "answer_id": 104788, "author": "sebastiaan", "author_id": 5018, "author_profile": "https://Stackoverflow.com/users/5018", "pm_score": 2, "selected": false, "text": "<p>Since you already automatically increment the id for each new member, you can order by id.</p>\n" }, { "answer...
2008/09/19
[ "https://Stackoverflow.com/questions/104747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19217/" ]
I have a members table in MySQL ``` CREATE TABLE `members` ( `id` int(10) unsigned NOT NULL auto_increment, `name` varchar(65) collate utf8_unicode_ci NOT NULL, `order` tinyint(3) unsigned NOT NULL default '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB; ``` And I would like to let users order the members how they like. I'm storing the order in `order` column. I'm wondering how to insert new user to be added to the bottom of the list. This is what I have today: ``` $db->query('insert into members VALUES (0, "new member", 0)'); $lastId = $db->lastInsertId(); $maxOrder = $db->fetchAll('select MAX(`order`) max_order FROM members'); $db->query('update members SET `order` = ? WHERE id = ?', array( $maxOrder[0]['max_order'] + 1, $lastId )); ``` But that's not really precise while when there are several users adding new members at the same time, it might happen the `MAX(order)` will return the same values. How do you handle such cases?
You can do the SELECT as part of the INSERT, such as: ``` INSERT INTO members SELECT 0, "new member", max(`order`)+1 FROM members; ``` Keep in mind that you are going to want to have an index on the `order` column to make the SELECT part optimized. In addition, you might want to reconsider the tinyint for order, unless you only expect to only have 255 orders ever. Also order is a reserved word and you will always need to write it as `order`, so you might consider renaming that column as well.
104,791
<p>The SQL-LDR documentation states that you need to do a convetional Path Load:</p> <blockquote> <p>When you want to apply SQL functions to data fields. SQL functions are not available during a direct path load</p> </blockquote> <p>I have TimeStamp data stored in a CSV file that I'm loading with SQL-LDR by describing the fields as such:</p> <pre><code>STARTTIME "To_TimeStamp(:STARTTIME,'YYYY-MM-DD HH24:MI:SS.FF6')", COMPLETIONTIME "To_TimeStamp(:COMPLETIONTIME,'YYYY-MM-DD HH24:MI:SS.FF6')" </code></pre> <p>So my question is: Can you load timestamp data without a function, or is it the case that you can not do a Direct Path Load when Loading TimeStamp data?</p>
[ { "answer_id": 104783, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 0, "selected": false, "text": "<p>A little more information please; do you want to log IPs or lock access via IP? Both those functions are built into IIS ...
2008/09/19
[ "https://Stackoverflow.com/questions/104791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
The SQL-LDR documentation states that you need to do a convetional Path Load: > > When you want to apply SQL functions > to data fields. SQL functions are not > available during a direct path load > > > I have TimeStamp data stored in a CSV file that I'm loading with SQL-LDR by describing the fields as such: ``` STARTTIME "To_TimeStamp(:STARTTIME,'YYYY-MM-DD HH24:MI:SS.FF6')", COMPLETIONTIME "To_TimeStamp(:COMPLETIONTIME,'YYYY-MM-DD HH24:MI:SS.FF6')" ``` So my question is: Can you load timestamp data without a function, or is it the case that you can not do a Direct Path Load when Loading TimeStamp data?
As blowdart said, simple IP Address logging is handled by IIS already. Simply right-click on the Website in Internet Information Services (IIS) Manager tool, go to the Web Site tab, and check the Enable Logging box. You can customize what information is logged also. If you want to restrict the site or even a folder of the site to specific IP's, just go to the IIS Site or Folder properties that you want to protect in the IIS Manager, right click and select Properties. Choose the Directory Security tab. In the middle you should see the "IP Addresses and domain name restrictions. This will be where you can setup which IP's to block or allow. If you want to do this programatically in the code-behind of ASP.Net, you could use the page preinit event.
104,797
<p>What is the best way to create a webservice for accepting an image. The image might be quite big and I do not want to change the default receive size for the web application. I have written one that accepts a binary image but that I feel that there has to be a better alternative.</p>
[ { "answer_id": 104902, "author": "core", "author_id": 11574, "author_profile": "https://Stackoverflow.com/users/11574", "pm_score": 3, "selected": true, "text": "<p>Where does this image \"live?\" Is it accessible in the local file system or on the web? If so, I would suggest having your...
2008/09/19
[ "https://Stackoverflow.com/questions/104797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/403/" ]
What is the best way to create a webservice for accepting an image. The image might be quite big and I do not want to change the default receive size for the web application. I have written one that accepts a binary image but that I feel that there has to be a better alternative.
Where does this image "live?" Is it accessible in the local file system or on the web? If so, I would suggest having your WebService accepting a URI (can be a URL or a local file) and opening it as a Stream, then using a StreamReader to read the contents of it. Example (but wrap the exceptions in FaultExceptions, and add FaultContractAttributes): ``` using System.Drawing; using System.IO; using System.Net; using System.Net.Sockets; [OperationContract] public void FetchImage(Uri url) { // Validate url if (url == null) { throw new ArgumentNullException(url); } // If the service doesn't know how to resolve relative URI paths /*if (!uri.IsAbsoluteUri) { throw new ArgumentException("Must be absolute.", url); }*/ // Download and load the image Image image = new Func<Bitmap>(() => { try { using (WebClient downloader = new WebClient()) { return new Bitmap(downloader.OpenRead(url)); } } catch (ArgumentException exception) { throw new ResourceNotImageException(url, exception); } catch (WebException exception) { throw new ImageDownloadFailedException(url, exception); } // IOException and SocketException are not wrapped by WebException :( catch (IOException exception) { throw new ImageDownloadFailedException(url, exception); } catch (SocketException exception) { throw new ImageDownloadFailedException(url, exception); } })(); // Do something with image } ```
104,803
<p>I've got a (mostly) working plugin developed, but since its function is directly related to the project it processes, how do you develop unit and integration tests for the plugin. The best idea I've had is to create an integration test project for the plugin that uses the plugin during its lifecycle and has tests that report on the plugins success or failure in processing the data.</p> <p>Anyone with better ideas?</p>
[ { "answer_id": 105259, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 4, "selected": true, "text": "<p>You need to use the <a href=\"http://maven.apache.org/shared/maven-plugin-testing-harness/\" rel=\"noreferrer\">mav...
2008/09/19
[ "https://Stackoverflow.com/questions/104803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17008/" ]
I've got a (mostly) working plugin developed, but since its function is directly related to the project it processes, how do you develop unit and integration tests for the plugin. The best idea I've had is to create an integration test project for the plugin that uses the plugin during its lifecycle and has tests that report on the plugins success or failure in processing the data. Anyone with better ideas?
You need to use the [maven-plugin-testing-harness](http://maven.apache.org/shared/maven-plugin-testing-harness/), ``` <dependency> <groupId>org.apache.maven.shared</groupId> <artifactId>maven-plugin-testing-harness</artifactId> <version>1.1</version> <scope>test</scope> </dependency> ``` You derive your unit test classes from [AbstractMojoTestCase](http://maven.apache.org/shared/maven-plugin-testing-harness/apidocs/org/apache/maven/plugin/testing/AbstractMojoTestCase.html). You need to create a bare bones POM, usually in the `src/test/resources` folder. ``` <project> <build> <plugins> <plugin> <groupId>com.mydomain,mytools</groupId> <artifactId>mytool-maven-plugin</artifactId> <configuration> <!-- Insert configuration settings here --> </configuration> <executions> <execution> <goals> <goal>mygoal</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project> ``` Use the AbstractMojoTest.lookupMojo(String,File) (or one of the other variations) to load the Mojo for a specific goal and execute it. ``` final File testPom = new File(PlexusTestCase.getBasedir(), "/target/test-classes/mytools-plugin-config.xml"); Mojo mojo = this.lookupMojo("mygoal", testPom); // Insert assertions to validate that your plugin was initialised correctly mojo.execute(); // Insert assertions to validate that your plugin behaved as expected ``` I created my a plugin of my own that you can refer to for clarification <http://ldap-plugin.btmatthews.com>,
104,844
<p>I'm looking for a way to find the name of the Windows default printer using unmanaged C++ (found plenty of .NET examples, but no success unmanaged). Thanks.</p>
[ { "answer_id": 104882, "author": "Doug T.", "author_id": 8123, "author_profile": "https://Stackoverflow.com/users/8123", "pm_score": 3, "selected": true, "text": "<p>The following works great for printing with the win32api from C++</p>\n\n<pre><code>char szPrinterName[255];\nunsigned lon...
2008/09/19
[ "https://Stackoverflow.com/questions/104844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8117/" ]
I'm looking for a way to find the name of the Windows default printer using unmanaged C++ (found plenty of .NET examples, but no success unmanaged). Thanks.
The following works great for printing with the win32api from C++ ``` char szPrinterName[255]; unsigned long lPrinterNameLength; GetDefaultPrinter( szPrinterName, &lPrinterNameLength ); HDC hPrinterDC; hPrinterDC = CreateDC("WINSPOOL\0", szPrinterName, NULL, NULL); ``` In the future instead of googling "unmanaged" try googling "win32 /subject/" or "win32 api /subject/"
104,850
<p>I want to try to convert a string to a Guid, but I don't want to rely on catching exceptions (</p> <ul> <li>for performance reasons - exceptions are expensive</li> <li>for usability reasons - the debugger pops up </li> <li>for design reasons - the expected is not exceptional</li> </ul> <p>In other words the code:</p> <pre><code>public static Boolean TryStrToGuid(String s, out Guid value) { try { value = new Guid(s); return true; } catch (FormatException) { value = Guid.Empty; return false; } } </code></pre> <p>is not suitable.</p> <p>I would try using RegEx, but since the guid can be parenthesis wrapped, brace wrapped, none wrapped, makes it hard. </p> <p>Additionally, I thought certain Guid values are invalid(?)</p> <hr> <p><strong>Update 1</strong></p> <p><a href="https://stackoverflow.com/questions/104850/c-test-if-string-is-a-guid-without-throwing-exceptions#137829">ChristianK</a> had a good idea to catch only <code>FormatException</code>, rather than all. Changed the question's code sample to include suggestion.</p> <hr> <p><strong>Update 2</strong></p> <p>Why worry about thrown exceptions? Am I really expecting invalid GUIDs all that often? </p> <p>The answer is <em>yes</em>. That is why I am using TryStrToGuid - I <strong>am</strong> expecting bad data.</p> <p><strong>Example 1</strong> <a href="http://msdn.microsoft.com/en-us/library/cc144096(VS.85).aspx" rel="noreferrer">Namespace extensions can be specified by appending a GUID to a folder name</a>. I might be parsing folder names, checking to see if the text after the final <strong>.</strong> is a GUID.</p> <pre><code>c:\Program Files c:\Program Files.old c:\Users c:\Users.old c:\UserManager.{CE7F5AA5-6832-43FE-BAE1-80D14CD8F666} c:\Windows c:\Windows.old </code></pre> <p><strong>Example 2</strong> I might be running a heavily used web-server wants to check the validity of some posted back data. I don't want invalid data tying up resources 2-3 orders of magnitude higher than it needs to be.</p> <p><strong>Example 3</strong> I might be parsing a search expression entered by a user. </p> <p><img src="https://i.stack.imgur.com/Ghb12.png" alt="enter image description here"></p> <p>If they enter GUID's I want to process them specially (such as specifically searching for that object, or highlight and format that specific search term in the response text.)</p> <hr> <p><strong>Update 3 - Performance benchmarks</strong></p> <p>Test converting 10,000 good Guids, and 10,000 bad Guids.</p> <pre><code>Catch FormatException: 10,000 good: 63,668 ticks 10,000 bad: 6,435,609 ticks Regex Pre-Screen with try-catch: 10,000 good: 637,633 ticks 10,000 bad: 717,894 ticks COM Interop CLSIDFromString 10,000 good: 126,120 ticks 10,000 bad: 23,134 ticks </code></pre> <p><em>p.s. I shouldn't have to justify a question.</em></p>
[ { "answer_id": 104893, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>Run the potential GUID though a RegEx or some custom code that does a sanity check to ensure the strig at least l...
2008/09/19
[ "https://Stackoverflow.com/questions/104850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12597/" ]
I want to try to convert a string to a Guid, but I don't want to rely on catching exceptions ( * for performance reasons - exceptions are expensive * for usability reasons - the debugger pops up * for design reasons - the expected is not exceptional In other words the code: ``` public static Boolean TryStrToGuid(String s, out Guid value) { try { value = new Guid(s); return true; } catch (FormatException) { value = Guid.Empty; return false; } } ``` is not suitable. I would try using RegEx, but since the guid can be parenthesis wrapped, brace wrapped, none wrapped, makes it hard. Additionally, I thought certain Guid values are invalid(?) --- **Update 1** [ChristianK](https://stackoverflow.com/questions/104850/c-test-if-string-is-a-guid-without-throwing-exceptions#137829) had a good idea to catch only `FormatException`, rather than all. Changed the question's code sample to include suggestion. --- **Update 2** Why worry about thrown exceptions? Am I really expecting invalid GUIDs all that often? The answer is *yes*. That is why I am using TryStrToGuid - I **am** expecting bad data. **Example 1** [Namespace extensions can be specified by appending a GUID to a folder name](http://msdn.microsoft.com/en-us/library/cc144096(VS.85).aspx). I might be parsing folder names, checking to see if the text after the final **.** is a GUID. ``` c:\Program Files c:\Program Files.old c:\Users c:\Users.old c:\UserManager.{CE7F5AA5-6832-43FE-BAE1-80D14CD8F666} c:\Windows c:\Windows.old ``` **Example 2** I might be running a heavily used web-server wants to check the validity of some posted back data. I don't want invalid data tying up resources 2-3 orders of magnitude higher than it needs to be. **Example 3** I might be parsing a search expression entered by a user. ![enter image description here](https://i.stack.imgur.com/Ghb12.png) If they enter GUID's I want to process them specially (such as specifically searching for that object, or highlight and format that specific search term in the response text.) --- **Update 3 - Performance benchmarks** Test converting 10,000 good Guids, and 10,000 bad Guids. ``` Catch FormatException: 10,000 good: 63,668 ticks 10,000 bad: 6,435,609 ticks Regex Pre-Screen with try-catch: 10,000 good: 637,633 ticks 10,000 bad: 717,894 ticks COM Interop CLSIDFromString 10,000 good: 126,120 ticks 10,000 bad: 23,134 ticks ``` *p.s. I shouldn't have to justify a question.*
**Performance Benchmarks** ``` Catch exception: 10,000 good: 63,668 ticks 10,000 bad: 6,435,609 ticks Regex Pre-Screen: 10,000 good: 637,633 ticks 10,000 bad: 717,894 ticks COM Interop CLSIDFromString 10,000 good: 126,120 ticks 10,000 bad: 23,134 ticks ``` **COM Intertop (Fastest) Answer:** ``` /// <summary> /// Attempts to convert a string to a guid. /// </summary> /// <param name="s">The string to try to convert</param> /// <param name="value">Upon return will contain the Guid</param> /// <returns>Returns true if successful, otherwise false</returns> public static Boolean TryStrToGuid(String s, out Guid value) { //ClsidFromString returns the empty guid for null strings if ((s == null) || (s == "")) { value = Guid.Empty; return false; } int hresult = PInvoke.ObjBase.CLSIDFromString(s, out value); if (hresult >= 0) { return true; } else { value = Guid.Empty; return false; } } namespace PInvoke { class ObjBase { /// <summary> /// This function converts a string generated by the StringFromCLSID function back into the original class identifier. /// </summary> /// <param name="sz">String that represents the class identifier</param> /// <param name="clsid">On return will contain the class identifier</param> /// <returns> /// Positive or zero if class identifier was obtained successfully /// Negative if the call failed /// </returns> [DllImport("ole32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true)] public static extern int CLSIDFromString(string sz, out Guid clsid); } } ``` --- Bottom line: If you need to check if a string is a guid, and you care about performance, use COM Interop. If you need to convert a guid in String representation to a Guid, use ``` new Guid(someString); ```
104,872
<p>I'm working on a <code>PHP</code> application that links into the <code>Protx VSP Direct payment gateway</code>. To handle "3D Secure" requests from the credit card processing company, I need to forward the user to a different website, mimicking a form that has been posted. I'm trying to use the <code>cURL</code> libraries, but seem to have hit a problem. My code is the following: </p> <pre><code>&lt;?php $ch = curl_init(); // Set the URL curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/'); // Perform a POST curl_setopt($ch, CURLOPT_POST, 1); // If not set, curl prints output to the browser curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); // Set the "form fields" curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); $output = curl_exec($ch); curl_close($ch); ?&gt; </code></pre> <p>All this does is grab the content of the URL passed through, and doesn't forward the user anywhere. I've tried Googling and reading up as much as I can, but can't figure out what i'm missing. Any ideas? I don't want to have to create a HTML form that auto-submits itself if I can avoid it.</p> <p>Thanks for any help :-)</p>
[ { "answer_id": 104887, "author": "neu242", "author_id": 13365, "author_profile": "https://Stackoverflow.com/users/13365", "pm_score": 3, "selected": true, "text": "<p>The 3D Secure API doesn't allow you to do the request in the background. You need to forward the user to the 3D secure s...
2008/09/19
[ "https://Stackoverflow.com/questions/104872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19232/" ]
I'm working on a `PHP` application that links into the `Protx VSP Direct payment gateway`. To handle "3D Secure" requests from the credit card processing company, I need to forward the user to a different website, mimicking a form that has been posted. I'm trying to use the `cURL` libraries, but seem to have hit a problem. My code is the following: ``` <?php $ch = curl_init(); // Set the URL curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/'); // Perform a POST curl_setopt($ch, CURLOPT_POST, 1); // If not set, curl prints output to the browser curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); // Set the "form fields" curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); $output = curl_exec($ch); curl_close($ch); ?> ``` All this does is grab the content of the URL passed through, and doesn't forward the user anywhere. I've tried Googling and reading up as much as I can, but can't figure out what i'm missing. Any ideas? I don't want to have to create a HTML form that auto-submits itself if I can avoid it. Thanks for any help :-)
The 3D Secure API doesn't allow you to do the request in the background. You need to forward the user to the 3D secure site. Use javascript to automatically submit your form. Here's what our provider suggests: ``` <html> <head> <title>Processing your request...</title> </head> <body OnLoad="OnLoadEvent();"> <form name="downloadForm" action="<%=RedirURL%>" method="POST"> <noscript> <br> <br> <div align="center"> <h1>Processing your 3-D Secure Transaction</h1> <h2>JavaScript is currently disabled or is not supported by your browser.</h2><BR> <h3>Please click Submit to continue the processing of your 3-D Secure transaction.</h3><BR> <input type="submit" value="Submit"> </div> </noscript> <input type="hidden" name="PaReq" value="<%=PAREQ%>"> <input type="hidden" name="MD" value="<%=TransactionID%>"> <input type="hidden" name="TermUrl" value="<%=TermUrl%>"> </form> <SCRIPT LANGUAGE="Javascript"> <!-- function OnLoadEvent() { document.downloadForm.submit(); } //--> </SCRIPT> </body> </html> ```
104,918
<p>My question is related to the command pattern, where we have the following abstraction (C# code) :</p> <pre><code>public interface ICommand { void Execute(); } </code></pre> <p>Let's take a simple concrete command, which aims to delete an entity from our application. A <code>Person</code> instance, for example.</p> <p>I'll have a <code>DeletePersonCommand</code>, which implements <code>ICommand</code>. This command needs the <code>Person</code> to delete as a parameter, in order to delete it when <code>Execute</code> method is called.</p> <p>What is the best way to manage parametrized commands ? How to pass parameters to commands, before executing them ?</p>
[ { "answer_id": 104934, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 3, "selected": false, "text": "<p>In the constructor and stored as fields.</p>\n\n<p>You will also want to eventually make your ICommands serializable ...
2008/09/19
[ "https://Stackoverflow.com/questions/104918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4687/" ]
My question is related to the command pattern, where we have the following abstraction (C# code) : ``` public interface ICommand { void Execute(); } ``` Let's take a simple concrete command, which aims to delete an entity from our application. A `Person` instance, for example. I'll have a `DeletePersonCommand`, which implements `ICommand`. This command needs the `Person` to delete as a parameter, in order to delete it when `Execute` method is called. What is the best way to manage parametrized commands ? How to pass parameters to commands, before executing them ?
You'll need to associate the parameters with the command object, either by constructor or setter injection (or equivalent). Perhaps something like this: ``` public class DeletePersonCommand: ICommand { private Person personToDelete; public DeletePersonCommand(Person personToDelete) { this.personToDelete = personToDelete; } public void Execute() { doSomethingWith(personToDelete); } } ```