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
16,178
<p>I need to programatically determine whether .NET 3.5 is installed. I thought it would be easy:</p> <pre><code>&lt;% Response.Write(Environment.Version.ToString()); %&gt; </code></pre> <p>Which returns "2.0.50727.1434" so no such luck...</p> <p>In my research I have that there are some rather obscure registry keys I can look at but I'm not sure if that is the route to go. Does anyone have any suggestions?</p>
[ { "answer_id": 16187, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 2, "selected": false, "text": "<p>That is because technically .NET 3.5 is an extension of the 2.0 framework. The quickest way is to include an assembly fr...
2008/08/19
[ "https://Stackoverflow.com/questions/16178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/285/" ]
I need to programatically determine whether .NET 3.5 is installed. I thought it would be easy: ``` <% Response.Write(Environment.Version.ToString()); %> ``` Which returns "2.0.50727.1434" so no such luck... In my research I have that there are some rather obscure registry keys I can look at but I'm not sure if that is the route to go. Does anyone have any suggestions?
You could try: ``` static bool HasNet35() { try { AppDomain.CurrentDomain.Load( "System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); return true; } catch { return false; } } ``` @[Nick](https://stackoverflow.com/questions/16178/best-way-to-determine-if-net-35-is-installed#16253): Good question, I'll try it in a bit. Kev
16,265
<p>I'm working with LINQ for the first time and wanted to get the Mapping to work when I have a money type in SQL, but my domain object property is of type double. How can I express this in the XML file, or in code so that the mapping does not throw the usual "invalid cast" exception?</p>
[ { "answer_id": 16270, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 1, "selected": false, "text": "<p>pretty sure Money maps to System.Decimal</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/bb386947.aspx\" r...
2008/08/19
[ "https://Stackoverflow.com/questions/16265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I'm working with LINQ for the first time and wanted to get the Mapping to work when I have a money type in SQL, but my domain object property is of type double. How can I express this in the XML file, or in code so that the mapping does not throw the usual "invalid cast" exception?
In the DBML XML file, you can set the Expression attribute of a Column element to something like this: ``` <Column Name="Table1.Amount" DbType="smallint" Type="System.Int32" Expression="CAST(Table1.Amount as int)" /> ```
16,298
<p>I have 2 hosts and I would like to point a subdomain on host one to a subdomain on host two:</p> <pre><code>subdomain.hostone.com --&gt; subdomain.hosttwo.com </code></pre> <p>I added a CNAME record to host one that points to subdomain.hosttwo.com but all I get is a '<strong>400 Bad Request</strong>' Error.</p> <p>Can anyone see what I'm doing wrong?</p>
[ { "answer_id": 16307, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 2, "selected": false, "text": "<p>It sounds like the web server on hosttwo.com doesn't allow undefined domains to be passed through. You also said you wan...
2008/08/19
[ "https://Stackoverflow.com/questions/16298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/117/" ]
I have 2 hosts and I would like to point a subdomain on host one to a subdomain on host two: ``` subdomain.hostone.com --> subdomain.hosttwo.com ``` I added a CNAME record to host one that points to subdomain.hosttwo.com but all I get is a '**400 Bad Request**' Error. Can anyone see what I'm doing wrong?
Try changing it to "subdomain -> subdomain.hosttwo.com" The `CNAME` is an alias for a certain domain, so when you go to the control panel for hostone.com, you shouldn't have to enter the whole name into the `CNAME` alias. As far as the error you are getting, can you log onto subdomain.hostwo.com and check the logs?
16,306
<p>What would be the easiest way to separate the directory name from the file name when dealing with <code>SaveFileDialog.FileName</code> in C#?</p>
[ { "answer_id": 16313, "author": "rjzii", "author_id": 1185, "author_profile": "https://Stackoverflow.com/users/1185", "pm_score": 0, "selected": false, "text": "<p>Since the forward slash is not allowed in the filename, one simple way is to divide the SaveFileDialog.Filename using String...
2008/08/19
[ "https://Stackoverflow.com/questions/16306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41/" ]
What would be the easiest way to separate the directory name from the file name when dealing with `SaveFileDialog.FileName` in C#?
Use: ``` System.IO.Path.GetDirectoryName(saveDialog.FileName) ``` (and the corresponding `System.IO.Path.GetFileName`). The Path class is really rather useful.
16,320
<p>I've seen projects where the classes in the DB layer have just static functions in them and other projects where those classes need to be instantiated to get access to the member functions. </p> <blockquote> <p>Which is "better" and why?</p> </blockquote>
[ { "answer_id": 16342, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 1, "selected": false, "text": "<p>It's all about the purpose of the DB Layer.\nIf you use an instance to access the DB layer, you are allowing multiple version...
2008/08/19
[ "https://Stackoverflow.com/questions/16320", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
I've seen projects where the classes in the DB layer have just static functions in them and other projects where those classes need to be instantiated to get access to the member functions. > > Which is "better" and why? > > >
I like a single object to be correlated to a single record in the database, i.e. an object must be instantiated. This is your basic [ActiveRecord](http://martinfowler.com/eaaCatalog/activeRecord.html) pattern. In my experience, the one-object-to-one-row approach creates a much more fluid and literate presentation in code. Also, I like to treat objects as records and the class as the table. For example to change the name of a record I do: ``` objPerson = new Person(id) objPerson.name = "George" objPerson.save() ``` while to get all people who live in Louisiana I might do ``` aryPeople = Person::getPeopleFromState("LA") ``` There are plenty of criticisms of Active Record. You can especially run into problems where you are querying the database for each record or your classes are tightly coupled to your database, creating inflexibility in both. In that case you can move up a level and go with something like [DataMapper](http://martinfowler.com/eaaCatalog/dataMapper.html). Many of the modern frameworks and [ORM's](http://en.wikipedia.org/wiki/Object-relational_mapping) are aware of some of these drawbacks and provide solutions for them. Do a little research and you will start to see that this is a problem that has a number of solutions and it all depend on your needs.
16,340
<p>Say I have an object that stores a byte array and I want to be able to efficiently generate a hashcode for it. I've used the cryptographic hash functions for this in the past because they are easy to implement, but they are doing a lot more work than they should to be cryptographically oneway, and I don't care about that (I'm just using the hashcode as a key into a hashtable).</p> <p>Here's what I have today:</p> <pre><code>struct SomeData : IEquatable&lt;SomeData&gt; { private readonly byte[] data; public SomeData(byte[] data) { if (null == data || data.Length &lt;= 0) { throw new ArgumentException("data"); } this.data = new byte[data.Length]; Array.Copy(data, this.data, data.Length); } public override bool Equals(object obj) { return obj is SomeData &amp;&amp; Equals((SomeData)obj); } public bool Equals(SomeData other) { if (other.data.Length != data.Length) { return false; } for (int i = 0; i &lt; data.Length; ++i) { if (data[i] != other.data[i]) { return false; } } return true; } public override int GetHashCode() { return BitConverter.ToInt32(new MD5CryptoServiceProvider().ComputeHash(data), 0); } } </code></pre> <p>Any thoughts?</p> <hr> <p>dp: You are right that I missed a check in Equals, I have updated it. Using the existing hashcode from the byte array will result in reference equality (or at least that same concept translated to hashcodes). for example:</p> <pre><code>byte[] b1 = new byte[] { 1 }; byte[] b2 = new byte[] { 1 }; int h1 = b1.GetHashCode(); int h2 = b2.GetHashCode(); </code></pre> <p>With that code, despite the two byte arrays having the same values within them, they are referring to different parts of memory and will result in (probably) different hash codes. I need the hash codes for two byte arrays with the same contents to be equal.</p>
[ { "answer_id": 16378, "author": "fulmicoton", "author_id": 446497, "author_profile": "https://Stackoverflow.com/users/446497", "pm_score": 2, "selected": false, "text": "<p>If you are looking for performance, I tested a few hash keys, and \nI recommend <a href=\"http://burtleburtle.net/b...
2008/08/19
[ "https://Stackoverflow.com/questions/16340", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1948/" ]
Say I have an object that stores a byte array and I want to be able to efficiently generate a hashcode for it. I've used the cryptographic hash functions for this in the past because they are easy to implement, but they are doing a lot more work than they should to be cryptographically oneway, and I don't care about that (I'm just using the hashcode as a key into a hashtable). Here's what I have today: ``` struct SomeData : IEquatable<SomeData> { private readonly byte[] data; public SomeData(byte[] data) { if (null == data || data.Length <= 0) { throw new ArgumentException("data"); } this.data = new byte[data.Length]; Array.Copy(data, this.data, data.Length); } public override bool Equals(object obj) { return obj is SomeData && Equals((SomeData)obj); } public bool Equals(SomeData other) { if (other.data.Length != data.Length) { return false; } for (int i = 0; i < data.Length; ++i) { if (data[i] != other.data[i]) { return false; } } return true; } public override int GetHashCode() { return BitConverter.ToInt32(new MD5CryptoServiceProvider().ComputeHash(data), 0); } } ``` Any thoughts? --- dp: You are right that I missed a check in Equals, I have updated it. Using the existing hashcode from the byte array will result in reference equality (or at least that same concept translated to hashcodes). for example: ``` byte[] b1 = new byte[] { 1 }; byte[] b2 = new byte[] { 1 }; int h1 = b1.GetHashCode(); int h2 = b2.GetHashCode(); ``` With that code, despite the two byte arrays having the same values within them, they are referring to different parts of memory and will result in (probably) different hash codes. I need the hash codes for two byte arrays with the same contents to be equal.
The hash code of an object does not need to be unique. The checking rule is: * Are the hash codes equal? Then call the full (slow) `Equals` method. * Are the hash codes not equal? Then the two items are definitely not equal. All you want is a `GetHashCode` algorithm that splits up your collection into roughly even groups - it shouldn't form the key as the `HashTable` or `Dictionary<>` will need to use the hash to optimise retrieval. How long do you expect the data to be? How random? If lengths vary greatly (say for files) then just return the length. If lengths are likely to be similar look at a subset of the bytes that varies. `GetHashCode` should be a lot quicker than `Equals`, but doesn't need to be unique. Two identical things *must never* have different hash codes. Two different objects *should not* have the same hash code, but some collisions are to be expected (after all, there are more permutations than possible 32 bit integers).
16,403
<p>One of my biggest typographical frustrations about HTML is the way that it mangles conjoined whitespace. For example if I have:</p> <pre><code>&lt;span&gt;Following punctuation rules. With two spaces after the period. &lt;/span&gt; </code></pre> <p>One of the two spaces following the period will be considered to be insignificant whitespace and be removed. I can of course, force the whitespace to be significant with: </p> <pre><code>&lt;span&gt;Following punctuation rules.&amp;nbsp; With two spaces after the period. &lt;/span&gt; </code></pre> <p>but it just irks me to have to do that and I usually don't bother. Does anyone out there automatically insert significant whitespace into external content submissions that are intended for a web page?</p>
[ { "answer_id": 16410, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 1, "selected": false, "text": "<p>You can use a styled pre block to preserve whitespace. Most WYSIWYG editors also insert &amp;nbsp; for you...</p>\n\n<p>Overall...
2008/08/19
[ "https://Stackoverflow.com/questions/16403", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1948/" ]
One of my biggest typographical frustrations about HTML is the way that it mangles conjoined whitespace. For example if I have: ``` <span>Following punctuation rules. With two spaces after the period. </span> ``` One of the two spaces following the period will be considered to be insignificant whitespace and be removed. I can of course, force the whitespace to be significant with: ``` <span>Following punctuation rules.&nbsp; With two spaces after the period. </span> ``` but it just irks me to have to do that and I usually don't bother. Does anyone out there automatically insert significant whitespace into external content submissions that are intended for a web page?
For your specific example, there is no need to worry about it. Web browsers perform typographical rendering and place the correct amount of space between periods and whatever character follows (and it's different depending on the next character, according to kerning rules.) If you want line breaks, <br/> isn't really a big deal, is it? --- Not sure what's worthy of a downmod here... You should not be forcing two spaces after a period, unless you're using a monospace font. For proportional fonts, the rederer kerns the right amount of space after a period. See [here](http://www.webword.com/reports/period.html) and [here](http://everything2.com/node/540926) for detailed discussions.
16,432
<p>Let's say that you want to output or concat strings. Which of the following styles do you prefer?</p> <ul> <li><p><code>var p = new { FirstName = "Bill", LastName = "Gates" };</code></p></li> <li><p><code>Console.WriteLine("{0} {1}", p.FirstName, p.LastName);</code></p></li> <li><p><code>Console.WriteLine(p.FirstName + " " + p.LastName);</code></p></li> </ul> <p>Do you rather use format or do you simply concat strings? What is your favorite? Is one of these hurting your eyes?</p> <p>Do you have any rational arguments to use one and not the other?</p> <p>I'd go for the second one.</p>
[ { "answer_id": 16436, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 1, "selected": false, "text": "<p>Personally, the second one as everything you are using is in the direct order it will be output in. Whereas with the fir...
2008/08/19
[ "https://Stackoverflow.com/questions/16432", "https://Stackoverflow.com", "https://Stackoverflow.com/users/920/" ]
Let's say that you want to output or concat strings. Which of the following styles do you prefer? * `var p = new { FirstName = "Bill", LastName = "Gates" };` * `Console.WriteLine("{0} {1}", p.FirstName, p.LastName);` * `Console.WriteLine(p.FirstName + " " + p.LastName);` Do you rather use format or do you simply concat strings? What is your favorite? Is one of these hurting your eyes? Do you have any rational arguments to use one and not the other? I'd go for the second one.
Try this code. It's a slightly modified version of your code. 1. I removed Console.WriteLine as it's probably a few orders of magnitude slower than what I'm trying to measure. 2. I'm starting the Stopwatch before the loop and stopping it right after, this way I'm not losing precision if the function takes for example 26.4 ticks to execute. 3. The way you divided the result by some iterations was wrong. See what happens if you have 1,000 milliseconds and 100 milliseconds. In both situations, you will get 0 ms after dividing it by 1,000,000. Code: ``` Stopwatch s = new Stopwatch(); var p = new { FirstName = "Bill", LastName = "Gates" }; int n = 1000000; long fElapsedMilliseconds = 0, fElapsedTicks = 0, cElapsedMilliseconds = 0, cElapsedTicks = 0; string result; s.Start(); for (var i = 0; i < n; i++) result = (p.FirstName + " " + p.LastName); s.Stop(); cElapsedMilliseconds = s.ElapsedMilliseconds; cElapsedTicks = s.ElapsedTicks; s.Reset(); s.Start(); for (var i = 0; i < n; i++) result = string.Format("{0} {1}", p.FirstName, p.LastName); s.Stop(); fElapsedMilliseconds = s.ElapsedMilliseconds; fElapsedTicks = s.ElapsedTicks; s.Reset(); Console.Clear(); Console.WriteLine(n.ToString()+" x result = string.Format(\"{0} {1}\", p.FirstName, p.LastName); took: " + (fElapsedMilliseconds) + "ms - " + (fElapsedTicks) + " ticks"); Console.WriteLine(n.ToString() + " x result = (p.FirstName + \" \" + p.LastName); took: " + (cElapsedMilliseconds) + "ms - " + (cElapsedTicks) + " ticks"); Thread.Sleep(4000); ``` Those are my results: > > 1000000 x result = string.Format("{0} {1}", p.FirstName, p.LastName); took: 618ms - 2213706 ticks > > > >
16,447
<p>I am trying to generate a report by querying 2 databases (Sybase) in classic ASP.</p> <p>I have created 2 connection strings:<br></p> <blockquote> <p>connA for databaseA<br> connB for databaseB</p> </blockquote> <p>Both databases are present on the same server (don't know if this matters)<br></p> <p>Queries:</p> <p><code>q1 = SELECT column1 INTO #temp FROM databaseA..table1 WHERE xyz=&quot;A&quot;</code></p> <p><code>q2 = SELECT columnA,columnB,...,columnZ FROM table2 a #temp b WHERE b.column1=a.columnB</code></p> <p>followed by:</p> <pre><code>response.Write(rstsql) &lt;br&gt; set rstSQL = CreateObject(&quot;ADODB.Recordset&quot;)&lt;br&gt; rstSQL.Open q1, connA&lt;br&gt; rstSQL.Open q2, connB </code></pre> <p>When I try to open up this page in a browser, I get error message:</p> <blockquote> <p>Microsoft OLE DB Provider for ODBC Drivers error '80040e37'</p> <p>[DataDirect][ODBC Sybase Wire Protocol driver][SQL Server]#temp not found. Specify owner.objectname or use sp_help to check whether the object exists (sp_help may produce lots of output).</p> </blockquote> <p>Could anyone please help me understand what the problem is and help me fix it?</p> <p>Thanks.</p>
[ { "answer_id": 16461, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 2, "selected": false, "text": "<p>your temp table is out of scope, it is only 'alive' during the first connection and will not be available in the 2nd conne...
2008/08/19
[ "https://Stackoverflow.com/questions/16447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1311/" ]
I am trying to generate a report by querying 2 databases (Sybase) in classic ASP. I have created 2 connection strings: > > connA for databaseA > > connB for databaseB > > > Both databases are present on the same server (don't know if this matters) Queries: `q1 = SELECT column1 INTO #temp FROM databaseA..table1 WHERE xyz="A"` `q2 = SELECT columnA,columnB,...,columnZ FROM table2 a #temp b WHERE b.column1=a.columnB` followed by: ``` response.Write(rstsql) <br> set rstSQL = CreateObject("ADODB.Recordset")<br> rstSQL.Open q1, connA<br> rstSQL.Open q2, connB ``` When I try to open up this page in a browser, I get error message: > > Microsoft OLE DB Provider for ODBC Drivers error '80040e37' > > > [DataDirect][ODBC Sybase Wire Protocol driver][SQL Server]#temp not found. Specify owner.objectname or use sp\_help to check whether the object exists (sp\_help may produce lots of output). > > > Could anyone please help me understand what the problem is and help me fix it? Thanks.
With both queries, it looks like you are trying to insert into #temp. #temp is located on one of the databases (for arguments sake, databaseA). So when you try to insert into #temp from databaseB, it reports that it does not exist. Try changing it from *Into **#temp** From* to *Into **databaseA.dbo.#temp** From* in both statements. Also, make sure that the connection strings have permissions on the other DB, otherwise this will not work. Update: relating to the temp table going out of scope - if you have one connection string that has permissions on both databases, then you could use this for both queries (while keeping the connection alive). While querying the table in the other DB, be sure to use [DBName].[Owner].[TableName] format when referring to the table.
16,458
<p>I'm using <code>ColdFusion</code> to return a result set from a SQL database and turn it into a list.</p> <p>I need some way to generate an alphabetical navigation bar for that list. I have ColdFusion and the jQuery library available.</p> <p>I'm looking to generate something like this:</p> <pre><code>A | B | C | ...      - A - A - B - B - B - C - D </code></pre> <p>Where clicking on one of the letters drops you down the page to the first item for that letter. Not all 26 letters of the alphabet are necessarily in use.</p>
[ { "answer_id": 16545, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>I would get the SQL result set to return the list in the first place, you can easily just take the first letter of the requi...
2008/08/19
[ "https://Stackoverflow.com/questions/16458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/666/" ]
I'm using `ColdFusion` to return a result set from a SQL database and turn it into a list. I need some way to generate an alphabetical navigation bar for that list. I have ColdFusion and the jQuery library available. I'm looking to generate something like this: ``` A | B | C | ...      - A - A - B - B - B - C - D ``` Where clicking on one of the letters drops you down the page to the first item for that letter. Not all 26 letters of the alphabet are necessarily in use.
So, there were plenty of good suggestions, but none did exactly what I wanted. Fortunately I was able to use them to figure out what I really wanted to do. The only thing the following doesn't do is print the last few unused letters (if there are any). That's why I have that cfif statement checking for 'W' as that's the last letter I use, otherwise it should check for Z. ``` <cfquery datasource="#application.dsn#" name="qTitles"> SELECT title, url, substr(titles,1,1) as indexLetter FROM list ORDER BY indexLetter,title </cfquery> <cfset linkLetter = "#asc('A')#"> <cfoutput query="titles" group="indexletter"> <cfif chr(linkLetter) eq #qTitles.indexletter#> <a href="###ucase(qTitles.indexletter)#">#ucase(qTitles.indexletter)#</a> <cfif asc('W') neq linkLetter>|</cfif> <cfset linkLetter = ++LinkLetter> <cfelse> <cfscript> while(chr(linkLetter) != qTitles.indexletter) { WriteOutput(" " & chr(linkLetter) & " "); IF(linkLetter != asc('W')){WriteOutput("|");}; ++LinkLetter; } </cfscript> <a href="###ucase(qTitles.indexletter)#">#ucase(qTitles.indexletter)#</a> <cfif asc('W') neq linkLetter>|</cfif> <cfset linkLetter = ++LinkLetter> </cfif> </cfoutput> <ul> <cfset currentLetter = ""> <cfoutput query="qTitles" group="title"> <cfif currentLetter neq #qTitles.indexletter#> <li><a name="#ucase(qTitles.indexletter)#">#ucase(qTitles.indexletter)#</a></li> </cfif> <cfset currentLetter = #qTitles.indexletter#> <li><a href="#url#">#title#</a></li> </cfoutput> </ul> ```
16,460
<p>I was writing some <strong>ASP.NET</strong> control when I came to the scenario where I needed to remove items from a list, only when they matched a certain condition.</p> <p>The <code>RemoveAll</code> method of the generic <code>List</code> class does a good job, but removes <em>all</em> items that match the condition, specified by the predicate.</p> <p>What if I want to only remove a certain number of items specifying the condition? What do you think is the best way to do this?</p>
[ { "answer_id": 16464, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 1, "selected": false, "text": "<p>Unless the method provides a \"limit\" parameter (which it doesn't) your best option is to go with a simple loop that rem...
2008/08/19
[ "https://Stackoverflow.com/questions/16460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1801/" ]
I was writing some **ASP.NET** control when I came to the scenario where I needed to remove items from a list, only when they matched a certain condition. The `RemoveAll` method of the generic `List` class does a good job, but removes *all* items that match the condition, specified by the predicate. What if I want to only remove a certain number of items specifying the condition? What do you think is the best way to do this?
If you want to specify both a limit for number of items to remove and a condition to select the items to remove, you can use this approach: ``` int limit = 30; // Suppose you want to remove 30 items at most list.RemoveAll(item => ShouldIRemoveThis(item) && limit-- > 0); ```
16,473
<p>Say we have the following method:</p> <pre><code>private MyObject foo = new MyObject(); // and later in the class public void PotentialMemoryLeaker(){ int firedCount = 0; foo.AnEvent += (o,e) =&gt; { firedCount++;Console.Write(firedCount);}; foo.MethodThatFiresAnEvent(); } </code></pre> <p>If the class with this method is instantiated and the <code>PotentialMemoryLeaker</code> method is called multiple times, do we leak memory?</p> <p>Is there any way to unhook that lambda event handler after we're done calling <code>MethodThatFiresAnEvent</code>? </p>
[ { "answer_id": 16484, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 5, "selected": true, "text": "<p>Yes, save it to a variable and unhook it.</p>\n\n<pre><code>DelegateType evt = (o, e) =&gt; { firedCount++; Console....
2008/08/19
[ "https://Stackoverflow.com/questions/16473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Say we have the following method: ``` private MyObject foo = new MyObject(); // and later in the class public void PotentialMemoryLeaker(){ int firedCount = 0; foo.AnEvent += (o,e) => { firedCount++;Console.Write(firedCount);}; foo.MethodThatFiresAnEvent(); } ``` If the class with this method is instantiated and the `PotentialMemoryLeaker` method is called multiple times, do we leak memory? Is there any way to unhook that lambda event handler after we're done calling `MethodThatFiresAnEvent`?
Yes, save it to a variable and unhook it. ``` DelegateType evt = (o, e) => { firedCount++; Console.Write(firedCount); }; foo.AnEvent += evt; foo.MethodThatFiresAnEvent(); foo.AnEvent -= evt; ``` And yes, if you don't, you'll *leak* memory, as you'll hook up a new delegate object each time. You'll also notice this because each time you call this method, it'll dump to the console an increasing number of lines (not just an increasing number, but for one call to MethodThatFiresAnEvent it'll dump any number of items, once for each hooked up anonymous method).
16,483
<p>How can I convince Firefox (3.0.1, if it matters) to send an If-Modified-Since header in an HTTPS request? It sends the header if the request uses plain HTTP and my server dutifully honors it. But when I request the same resource from the same server using HTTPS instead (i.e., simply changing the http:// in the URL to https://) then Firefox does not send an If-Modified-Since header at all. Is this behavior mandated by the SSL spec or something?</p> <p>Here are some example HTTP and HTTPS request/response pairs, pulled using the Live HTTP Headers Firefox extension, with some differences in bold:</p> <p>HTTP request/response:</p> <pre>http://myserver.com:30000/scripts/site.js GET /scripts/site.js HTTP/1.1 Host: myserver.com:30000 User-Agent: Mozilla/5.0 (...) Gecko/2008070206 Firefox/3.0.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive <b>If-Modified-Since: Tue, 19 Aug 2008 15:57:30 GMT If-None-Match: "a0501d1-300a-454d22526ae80"-gzip Cache-Control: max-age=0</b> HTTP/1.x 304 Not Modified Date: Tue, 19 Aug 2008 15:59:23 GMT Server: Apache/2.2.8 (Unix) mod_ssl/2.2.8 OpenSSL/0.9.8 Connection: Keep-Alive Keep-Alive: timeout=5, max=99 Etag: "a0501d1-300a-454d22526ae80"-gzip </pre> <p>HTTPS request/response:</p> <pre>https://myserver.com:30001/scripts/site.js GET /scripts/site.js HTTP/1.1 Host: myserver.com:30001 User-Agent: Mozilla/5.0 (...) Gecko/2008070206 Firefox/3.0.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive HTTP/1.x 200 OK Date: Tue, 19 Aug 2008 16:00:14 GMT Server: Apache/2.2.8 (Unix) mod_ssl/2.2.8 OpenSSL/0.9.8 Last-Modified: Tue, 19 Aug 2008 15:57:30 GMT Etag: "a0501d1-300a-454d22526ae80"-gzip Accept-Ranges: bytes Content-Encoding: gzip Content-Length: 3766 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: text/javascript</pre> <p>UPDATE: Setting <code>browser.cache.disk_cache_ssl</code> to true did the trick (which is odd because, as Nickolay points out, there's still the memory cache). Adding a "Cache-control: public" header to the response also worked. Thanks!</p>
[ { "answer_id": 16490, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 2, "selected": false, "text": "<p>HTTPS requests are not cached so sending an <strong>If-Modified-Since</strong> doesn't make any sense. The not caching i...
2008/08/19
[ "https://Stackoverflow.com/questions/16483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/164/" ]
How can I convince Firefox (3.0.1, if it matters) to send an If-Modified-Since header in an HTTPS request? It sends the header if the request uses plain HTTP and my server dutifully honors it. But when I request the same resource from the same server using HTTPS instead (i.e., simply changing the http:// in the URL to https://) then Firefox does not send an If-Modified-Since header at all. Is this behavior mandated by the SSL spec or something? Here are some example HTTP and HTTPS request/response pairs, pulled using the Live HTTP Headers Firefox extension, with some differences in bold: HTTP request/response: ``` http://myserver.com:30000/scripts/site.js GET /scripts/site.js HTTP/1.1 Host: myserver.com:30000 User-Agent: Mozilla/5.0 (...) Gecko/2008070206 Firefox/3.0.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive **If-Modified-Since: Tue, 19 Aug 2008 15:57:30 GMT If-None-Match: "a0501d1-300a-454d22526ae80"-gzip Cache-Control: max-age=0** HTTP/1.x 304 Not Modified Date: Tue, 19 Aug 2008 15:59:23 GMT Server: Apache/2.2.8 (Unix) mod_ssl/2.2.8 OpenSSL/0.9.8 Connection: Keep-Alive Keep-Alive: timeout=5, max=99 Etag: "a0501d1-300a-454d22526ae80"-gzip ``` HTTPS request/response: ``` https://myserver.com:30001/scripts/site.js GET /scripts/site.js HTTP/1.1 Host: myserver.com:30001 User-Agent: Mozilla/5.0 (...) Gecko/2008070206 Firefox/3.0.1 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive HTTP/1.x 200 OK Date: Tue, 19 Aug 2008 16:00:14 GMT Server: Apache/2.2.8 (Unix) mod_ssl/2.2.8 OpenSSL/0.9.8 Last-Modified: Tue, 19 Aug 2008 15:57:30 GMT Etag: "a0501d1-300a-454d22526ae80"-gzip Accept-Ranges: bytes Content-Encoding: gzip Content-Length: 3766 Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Content-Type: text/javascript ``` UPDATE: Setting `browser.cache.disk_cache_ssl` to true did the trick (which is odd because, as Nickolay points out, there's still the memory cache). Adding a "Cache-control: public" header to the response also worked. Thanks!
> > HTTPS requests are not cached so sending an If-Modified-Since doesn't make any sense. The not caching is a security precaution. > > > The not caching **on disk** is a security pre-caution, but it seems it indeed affects the **If-Modified-Since** behavior (glancing over the code). Try setting the Firefox preference (in about:config) **browser.cache.disk\_cache\_ssl** to **true**. If that helps, try sending **Cache-Control: public** header in your response. --- **UPDATE:** Firefox behavior [was changed](https://bugzilla.mozilla.org/show_bug.cgi?id=531801) for Gecko 2.0 (Firefox 4) -- HTTPS content is now cached.
16,487
<p>I am using SourceForge for some Open Source projects and I want to automate the deployment of releases to the SourceForge File Release System. I use Maven for my builds and the standard SFTP deployment mechanism doesn't seem to work unless you do some manual preparation work. I have come across some old postings on other forums suggesting that the only approach is to write a Wagon specifically for SourceForge.</p> <p>Has anybody had any recent experience with this?</p>
[ { "answer_id": 17779, "author": "Brian Matthews", "author_id": 1969, "author_profile": "https://Stackoverflow.com/users/1969", "pm_score": 0, "selected": false, "text": "<p>The Maven SourceForge plug-in does not work with Maven 2. Also I believe this plug-in uses FTP which is no longer s...
2008/08/19
[ "https://Stackoverflow.com/questions/16487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1969/" ]
I am using SourceForge for some Open Source projects and I want to automate the deployment of releases to the SourceForge File Release System. I use Maven for my builds and the standard SFTP deployment mechanism doesn't seem to work unless you do some manual preparation work. I have come across some old postings on other forums suggesting that the only approach is to write a Wagon specifically for SourceForge. Has anybody had any recent experience with this?
I'm not able to test this to confirm, but I believe it is possible without writing any plugins. You can [deploy to SourceForge using SCP](http://sourceforge.net/apps/trac/sourceforge/wiki/SCP), and the maven-deploy-plugin can be configured to [use SCP](http://maven.apache.org/plugins/maven-deploy-plugin/examples/deploy-ssh-external.html) so it should work. You can also deploy your [site to SourceForge](http://maven.apache.org/plugins/maven-site-plugin/examples/site-deploy-to-sourceforge.net.html) via SCP. You would configure the SourceForge server in your settings.xml to use a "combined" username with a comma separator. With these credentials: ``` SourceForge username: foo SourceForge user password: secret SourceForge project name: bar Path: /home/frs/project/P/PR/PROJECT_UNIX_NAME/ - Substitute your project UNIX name data for /P/PR/PROJECT_UNIX_NAME ``` The server element would look like this: ``` <server> <id>sourceforge</id> <username>foo,bar</username> <password>secret</password> </server> ``` And the distributionManagement section in your POM would look like this: ``` <!-- Enabling the use of FTP --> <distributionManagement> <repository> <id>ssh-repository</id> <url> scpexe://frs.sourceforge.net:/home/frs/project/P/PR/PROJECT_UNIX_NAME</url> </repository> </distributionManagement> ``` Finally declare that ssh-external is to be used: ``` <build> <extensions> <extension> <groupId>org.apache.maven.wagon</groupId> <artifactId>wagon-ssh-external</artifactId> <version>1.0-alpha-5</version> </extension> </extensions> </build> ``` --- If this doesn't work, you may be able to use the recommended approach in the site reference above, i.e. create a shell on shell.sourceforge.net with your username and project group: ``` ssh -t <username>,<project name>@shell.sf.net create ``` Then use shell.sourceforge.net (instead of web.sourceforge.net) in your site URL in the diestributionManagement section: ``` <url>scp://shell.sourceforge.net/home/frs/project/P/PR/PROJECT_UNIX_NAME/</url> ```
16,501
<p>For a person without a comp-sci background, what is a lambda in the world of Computer Science?</p>
[ { "answer_id": 16504, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 6, "selected": false, "text": "<p>It refers to <a href=\"http://en.wikipedia.org/wiki/Lambda_calculus\" rel=\"noreferrer\">lambda calculus</a>, which is...
2008/08/19
[ "https://Stackoverflow.com/questions/16501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1344/" ]
For a person without a comp-sci background, what is a lambda in the world of Computer Science?
Lambda comes from the [Lambda Calculus](http://en.wikipedia.org/wiki/Lambda_calculus) and refers to anonymous functions in programming. Why is this cool? It allows you to write quick throw away functions without naming them. It also provides a nice way to write closures. With that power you can do things like this. **Python** ```py def adder(x): return lambda y: x + y add5 = adder(5) add5(1) 6 ``` As you can see from the snippet of Python, the function adder takes in an argument x, and returns an anonymous function, or lambda, that takes another argument y. That anonymous function allows you to create functions from functions. This is a simple example, but it should convey the power lambdas and closures have. **Examples in other languages** **Perl 5** ```pl sub adder { my ($x) = @_; return sub { my ($y) = @_; $x + $y } } my $add5 = adder(5); print &$add5(1) == 6 ? "ok\n" : "not ok\n"; ``` **JavaScript** ```js var adder = function (x) { return function (y) { return x + y; }; }; add5 = adder(5); add5(1) == 6 ``` **JavaScript (ES6)** ```js const adder = x => y => x + y; add5 = adder(5); add5(1) == 6 ``` **Scheme** ```scheme (define adder (lambda (x) (lambda (y) (+ x y)))) (define add5 (adder 5)) (add5 1) 6 ``` **[C# 3.5 or higher](http://msdn.microsoft.com/en-us/library/0yw3tz5k%28v=vs.110%29.aspx)** ```cs Func<int, Func<int, int>> adder = (int x) => (int y) => x + y; // `int` declarations optional Func<int, int> add5 = adder(5); var add6 = adder(6); // Using implicit typing Debug.Assert(add5(1) == 6); Debug.Assert(add6(-1) == 5); // Closure example int yEnclosed = 1; Func<int, int> addWithClosure = (x) => x + yEnclosed; Debug.Assert(addWithClosure(2) == 3); ``` **Swift** ```swift func adder(x: Int) -> (Int) -> Int{ return { y in x + y } } let add5 = adder(5) add5(1) 6 ``` **PHP** ```php $a = 1; $b = 2; $lambda = fn () => $a + $b; echo $lambda(); ``` **Haskell** ``` (\x y -> x + y) ``` **Java** see [this post](https://stackoverflow.com/questions/36233477/lambda-expression-in-java-1-8/36233545#36233545) ```java // The following is an example of Predicate : // a functional interface that takes an argument // and returns a boolean primitive type. Predicate<Integer> pred = x -> x % 2 == 0; // Tests if the parameter is even. boolean result = pred.test(4); // true ``` **Lua** ```lua adder = function(x) return function(y) return x + y end end add5 = adder(5) add5(1) == 6 -- true ``` **Kotlin** ```kotlin val pred = { x: Int -> x % 2 == 0 } val result = pred(4) // true ``` **Ruby** Ruby is slightly different in that you cannot call a lambda using the exact same syntax as calling a function, but it still has lambdas. ```ruby def adder(x) lambda { |y| x + y } end add5 = adder(5) add5[1] == 6 ``` Ruby being Ruby, there is a shorthand for lambdas, so you can define `adder` this way: ``` def adder(x) -> y { x + y } end ``` **R** ```r adder <- function(x) { function(y) x + y } add5 <- adder(5) add5(1) #> [1] 6 ```
16,563
<p>So I'm working on a project that will allow users to enter <strong>poker hand histories</strong> from sites like PokerStars and then display the hand to them.</p> <p>It seems that regex would be a great tool for this, however I rank my regex knowledge at "slim to none".</p> <p>So I'm using PHP and looping through this block of text line by line and on lines like this:</p> <pre><code>Seat 1: fabulous29 (835 in chips) Seat 2: Nioreh_21 (6465 in chips) Seat 3: Big Loads (3465 in chips) Seat 4: Sauchie (2060 in chips) </code></pre> <p>I want to extract seat <code>number, name, &amp; chip count</code> so the format is</p> <pre><code>Seat [number]: [letters&amp;numbers&amp;characters] ([number] in chips) </code></pre> <p>I have NO IDEA where to start or what commands I should even be using to optimize this.</p> <p>Any advice is greatly appreciated - even if it is just a link to a tutorial on PHP regex or the name of the command(s) I should be using.</p>
[ { "answer_id": 16569, "author": "Ellen Teapot", "author_id": 1914, "author_profile": "https://Stackoverflow.com/users/1914", "pm_score": 2, "selected": false, "text": "<p>Look at the PCRE section in the PHP Manual. Also, <a href=\"http://www.regular-expressions.info/\" rel=\"nofollow nor...
2008/08/19
[ "https://Stackoverflow.com/questions/16563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428190/" ]
So I'm working on a project that will allow users to enter **poker hand histories** from sites like PokerStars and then display the hand to them. It seems that regex would be a great tool for this, however I rank my regex knowledge at "slim to none". So I'm using PHP and looping through this block of text line by line and on lines like this: ``` Seat 1: fabulous29 (835 in chips) Seat 2: Nioreh_21 (6465 in chips) Seat 3: Big Loads (3465 in chips) Seat 4: Sauchie (2060 in chips) ``` I want to extract seat `number, name, & chip count` so the format is ``` Seat [number]: [letters&numbers&characters] ([number] in chips) ``` I have NO IDEA where to start or what commands I should even be using to optimize this. Any advice is greatly appreciated - even if it is just a link to a tutorial on PHP regex or the name of the command(s) I should be using.
Look at the PCRE section in the PHP Manual. Also, <http://www.regular-expressions.info/> is a great site for learning regex. Disclaimer: Regex is very addictive once you learn it.
16,568
<p>I'm interested in learning some (ideally) database agnostic ways of selecting the <em>n</em>th row from a database table. It would also be interesting to see how this can be achieved using the native functionality of the following databases: </p> <ul> <li>SQL Server</li> <li>MySQL</li> <li>PostgreSQL</li> <li>SQLite</li> <li>Oracle</li> </ul> <p>I am currently doing something like the following in SQL Server 2005, but I'd be interested in seeing other's more agnostic approaches:</p> <pre><code>WITH Ordered AS ( SELECT ROW_NUMBER() OVER (ORDER BY OrderID) AS RowNumber, OrderID, OrderDate FROM Orders) SELECT * FROM Ordered WHERE RowNumber = 1000000 </code></pre> <p>Credit for the above SQL: <a href="https://web.archive.org/web/20101103031717/http://weblogs.asp.net/Firoz/archive/2005/06/12/411949.aspx" rel="noreferrer">Firoz Ansari's Weblog</a></p> <p><strong>Update:</strong> See <a href="https://stackoverflow.com/questions/16568/how-to-select-the-nth-row-in-a-sql-database-table#42765">Troels Arvin's answer</a> regarding the SQL standard. <em>Troels, have you got any links we can cite?</em></p>
[ { "answer_id": 16570, "author": "Andrew G. Johnson", "author_id": 428190, "author_profile": "https://Stackoverflow.com/users/428190", "pm_score": 2, "selected": false, "text": "<p>ADD:</p>\n\n<pre><code>LIMIT n,1\n</code></pre>\n\n<p>That will limit the results to one result starting at ...
2008/08/19
[ "https://Stackoverflow.com/questions/16568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1944/" ]
I'm interested in learning some (ideally) database agnostic ways of selecting the *n*th row from a database table. It would also be interesting to see how this can be achieved using the native functionality of the following databases: * SQL Server * MySQL * PostgreSQL * SQLite * Oracle I am currently doing something like the following in SQL Server 2005, but I'd be interested in seeing other's more agnostic approaches: ``` WITH Ordered AS ( SELECT ROW_NUMBER() OVER (ORDER BY OrderID) AS RowNumber, OrderID, OrderDate FROM Orders) SELECT * FROM Ordered WHERE RowNumber = 1000000 ``` Credit for the above SQL: [Firoz Ansari's Weblog](https://web.archive.org/web/20101103031717/http://weblogs.asp.net/Firoz/archive/2005/06/12/411949.aspx) **Update:** See [Troels Arvin's answer](https://stackoverflow.com/questions/16568/how-to-select-the-nth-row-in-a-sql-database-table#42765) regarding the SQL standard. *Troels, have you got any links we can cite?*
There are ways of doing this in optional parts of the standard, but a lot of databases support their own way of doing it. A really good site that talks about this and other things is <http://troels.arvin.dk/db/rdbms/#select-limit>. Basically, PostgreSQL and MySQL supports the non-standard: ``` SELECT... LIMIT y OFFSET x ``` Oracle, DB2 and MSSQL supports the standard windowing functions: ``` SELECT * FROM ( SELECT ROW_NUMBER() OVER (ORDER BY key ASC) AS rownumber, columns FROM tablename ) AS foo WHERE rownumber <= n ``` (which I just copied from the site linked above since I never use those DBs) *Update:* As of PostgreSQL 8.4 the standard windowing functions are supported, so expect the second example to work for PostgreSQL as well. *Update:* SQLite added window functions support in version 3.25.0 on 2018-09-15 so both forms also work in SQLite.
16,638
<p>I am having some trouble with the <a href="http://code.google.com/apis/maps/documentation/reference.html" rel="nofollow noreferrer">Google Maps API</a>. I have an array which holds a ojbect I created to store points.</p> <p>My array and class:</p> <pre><code>var tPoints = []; function tPoint(name) { var id = name; var points = []; var pointsCount = 0; ... this.getHeadPoint = function() { return points[pointsCount-1]; } } </code></pre> <p>tPoint holds an array of <a href="http://code.google.com/apis/maps/documentation/reference.html#GLatLng" rel="nofollow noreferrer">GLatLng</a> points. I want to write a function to return a <a href="http://code.google.com/apis/maps/documentation/reference.html#GLatLngBounds" rel="nofollow noreferrer">GLatLngBounds</a> object which is extended from the current map bounds to show all the HeadPoints.</p> <p>Heres what I have so far..</p> <pre><code>function getBounds() { var mBound = map.getBounds(); for (var i = 0; i &lt; tPoints.length; i++) { alert(mBound.getSouthWest().lat() + "," + mBound.getSouthWest().lng()); alert(mBound.getNorthEast().lat() + "," + mBound.getNorthEast().lng()); currPoint = trackMarkers[i].getHeadPoint(); if (!mBound.containsLatLng(currPoint)) { mBound.extend(currPoint); } } return mBound; } </code></pre> <p>Which returns these values for the alert. (Generally over the US)<br /></p> <blockquote> <p>"19.64258,NaN"<br /> "52.69636,NaN"<br /> "i=0"<br /> "19.64258,NaN"<br /> "52.69636,-117.20701"<br /> "i=1"<br /></p> </blockquote> <p>I don't know why I am getting NaN back. When I use the bounds to get a zoom level I think the NaN value is causing the map.getBoundsZoomLevel(bounds) to return 0 which is incorrect. Am I using <a href="http://code.google.com/apis/maps/documentation/reference.html#GLatLngBounds" rel="nofollow noreferrer">GLatLngBounds</a> incorrectly?</p>
[ { "answer_id": 16655, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 3, "selected": true, "text": "<p>Maybe a CLR stored procedure is what you are looking for. These are generally used when you need to interact with the...
2008/08/19
[ "https://Stackoverflow.com/questions/16638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1992/" ]
I am having some trouble with the [Google Maps API](http://code.google.com/apis/maps/documentation/reference.html). I have an array which holds a ojbect I created to store points. My array and class: ``` var tPoints = []; function tPoint(name) { var id = name; var points = []; var pointsCount = 0; ... this.getHeadPoint = function() { return points[pointsCount-1]; } } ``` tPoint holds an array of [GLatLng](http://code.google.com/apis/maps/documentation/reference.html#GLatLng) points. I want to write a function to return a [GLatLngBounds](http://code.google.com/apis/maps/documentation/reference.html#GLatLngBounds) object which is extended from the current map bounds to show all the HeadPoints. Heres what I have so far.. ``` function getBounds() { var mBound = map.getBounds(); for (var i = 0; i < tPoints.length; i++) { alert(mBound.getSouthWest().lat() + "," + mBound.getSouthWest().lng()); alert(mBound.getNorthEast().lat() + "," + mBound.getNorthEast().lng()); currPoint = trackMarkers[i].getHeadPoint(); if (!mBound.containsLatLng(currPoint)) { mBound.extend(currPoint); } } return mBound; } ``` Which returns these values for the alert. (Generally over the US) > > "19.64258,NaN" > "52.69636,NaN" > "i=0" > > "19.64258,NaN" > "52.69636,-117.20701" > "i=1" > > > > I don't know why I am getting NaN back. When I use the bounds to get a zoom level I think the NaN value is causing the map.getBoundsZoomLevel(bounds) to return 0 which is incorrect. Am I using [GLatLngBounds](http://code.google.com/apis/maps/documentation/reference.html#GLatLngBounds) incorrectly?
Maybe a CLR stored procedure is what you are looking for. These are generally used when you need to interact with the system in some way.
16,656
<p>I am working on a program that needs to create a multiple temporary folders for the application. These will not be seen by the user. The app is written in VB.net. I can think of a few ways to do it such as incremental folder name or random numbered folder names, but I was wondering, how other people solve this problem?</p>
[ { "answer_id": 16667, "author": "jwalkerjr", "author_id": 689, "author_profile": "https://Stackoverflow.com/users/689", "pm_score": 1, "selected": false, "text": "<p>As long as the name of the folder doesn't need to be meaningful, how about using a GUID for them?</p>\n" }, { "ans...
2008/08/19
[ "https://Stackoverflow.com/questions/16656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
I am working on a program that needs to create a multiple temporary folders for the application. These will not be seen by the user. The app is written in VB.net. I can think of a few ways to do it such as incremental folder name or random numbered folder names, but I was wondering, how other people solve this problem?
**Update:** Added File.Exists check per comment (2012-Jun-19) Here's what I've used in VB.NET. Essentially the same as presented, except I usually didn't want to create the folder immediately. The advantage to use [GetRandomFilename](http://msdn.microsoft.com/en-us/library/system.io.path.getrandomfilename.aspx) is that it doesn't create a file, so you don't have to clean up if your using the name for something other than a file. Like using it for folder name. ``` Private Function GetTempFolder() As String Dim folder As String = Path.Combine(Path.GetTempPath, Path.GetRandomFileName) Do While Directory.Exists(folder) or File.Exists(folder) folder = Path.Combine(Path.GetTempPath, Path.GetRandomFileName) Loop Return folder End Function ``` **Random** Filename Example: C:\Documents and Settings\username\Local Settings\Temp\u3z5e0co.tvq --- Here's a variation using a Guid to get the temp folder name. ``` Private Function GetTempFolderGuid() As String Dim folder As String = Path.Combine(Path.GetTempPath, Guid.NewGuid.ToString) Do While Directory.Exists(folder) or File.Exists(folder) folder = Path.Combine(Path.GetTempPath, Guid.NewGuid.ToString) Loop Return folder End Function ``` **guid** Example: C:\Documents and Settings\username\Local Settings\Temp\2dbc6db7-2d45-4b75-b27f-0bd492c60496
16,747
<p>I am building a public website using ASP.NET, as part of the deliverable I need to do an Admin Site for data entry of the stuff shown in the public site, I was wondering what techniques or procedures are people using to validate entries using ASP.NET MVC.</p>
[ { "answer_id": 25606, "author": "Daniel Pollard", "author_id": 2758, "author_profile": "https://Stackoverflow.com/users/2758", "pm_score": 6, "selected": true, "text": "<p>Take a look at the <a href=\"http://bassistance.de/jquery-plugins/jquery-plugin-validation/\" rel=\"noreferrer\">JQu...
2008/08/19
[ "https://Stackoverflow.com/questions/16747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1549/" ]
I am building a public website using ASP.NET, as part of the deliverable I need to do an Admin Site for data entry of the stuff shown in the public site, I was wondering what techniques or procedures are people using to validate entries using ASP.NET MVC.
Take a look at the [JQuery Validation plugin](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) this plugin is amazing,it's clean to implement and has all the features you could ever need, including remote validation via AJAX. Also a sample MVC controller method can be found [here](http://httpcode.com/blogs/PermaLink,guid,f8970f20-90d1-4af6-b2da-0285f1963b14.aspx) which basically uses the JsonResult action type like: ``` public JsonResult CheckUserName(string username) { return Json(CheckValidUsername(username)); } ```
16,770
<p>I'm trying to fully understand all of Haskell's concepts.</p> <p>In what ways are algebraic data types similar to generic types, e.g., in C# and Java? And how are they different? What's so algebraic about them anyway? </p> <p>I'm familiar with universal algebra and its rings and fields, but I only have a vague idea of how Haskell's types work.</p>
[ { "answer_id": 16810, "author": "olliej", "author_id": 784, "author_profile": "https://Stackoverflow.com/users/784", "pm_score": 6, "selected": true, "text": "<p>\"Algebraic Data Types\" in Haskell support <em>full parametric polymorphism</em>, which is the more technically correct name ...
2008/08/19
[ "https://Stackoverflow.com/questions/16770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659/" ]
I'm trying to fully understand all of Haskell's concepts. In what ways are algebraic data types similar to generic types, e.g., in C# and Java? And how are they different? What's so algebraic about them anyway? I'm familiar with universal algebra and its rings and fields, but I only have a vague idea of how Haskell's types work.
"Algebraic Data Types" in Haskell support *full parametric polymorphism*, which is the more technically correct name for generics, as a simple example the list data type: ``` data List a = Cons a (List a) | Nil ``` Is equivalent (as much as is possible, and ignoring non-strict evaluation, etc) to ``` class List<a> { class Cons : List<a> { a head; List<a> tail; } class Nil : List<a> {} } ``` Of course Haskell's type system allows more ... interesting use of type parameters but this is just a simple example. With regards to the "Algebraic Type" name, i've honestly never been entirely sure of the exact reason for them being named that, but have assumed that it's due the mathematical underpinnings of the type system. I *believe* that the reason boils down to the theoretical definition of an ADT being the "product of a set of constructors", however it's been a couple of years since i escaped university so i can no longer remember the specifics. [Edit: Thanks to Chris Conway for pointing out my foolish error, ADT are of course sum types, the constructors providing the product/tuple of fields]
16,795
<p>PHP has a great function called <a href="http://us2.php.net/manual/en/function.htmlspecialchars.php" rel="noreferrer">htmlspecialcharacters()</a> where you pass it a string and it replaces all of HTML's special characters with their safe equivalents, it's <em>almost</em> a one stop shop for sanitizing input. Very nice right?</p> <p>Well is there an equivalent in any of the .NET libraries?</p> <p>If not, can anyone link to any code samples or libraries that do this well?</p>
[ { "answer_id": 16801, "author": "Forgotten Semicolon", "author_id": 1960, "author_profile": "https://Stackoverflow.com/users/1960", "pm_score": 3, "selected": false, "text": "<p><a href=\"https://msdn.microsoft.com/en-us/library/system.web.httputility.htmlencode(v=vs.110).aspx\" rel=\"no...
2008/08/19
[ "https://Stackoverflow.com/questions/16795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1366/" ]
PHP has a great function called [htmlspecialcharacters()](http://us2.php.net/manual/en/function.htmlspecialchars.php) where you pass it a string and it replaces all of HTML's special characters with their safe equivalents, it's *almost* a one stop shop for sanitizing input. Very nice right? Well is there an equivalent in any of the .NET libraries? If not, can anyone link to any code samples or libraries that do this well?
Try this. ``` var encodedHtml = HttpContext.Current.Server.HtmlEncode(...); ```
16,815
<p>I'm trying to do a simple test php script for sessions. Basically it increments a counter (stored in <code>$_SESSION</code>) every time you refresh that page. That works, but I'm trying to have a link to destroy the session which reloads the page with the <code>?destroy=1</code> parameter. I've tried a couple of if statements to see if that parameter is set and if so to destroy the session but it doesn't seem to work.</p> <p>I've even put an if statement in the main body to pop-up a message if the parameter is set - but it doesn't seem to be picked up.</p> <p>I know I'm doing something silly (I'm a PHP newbie) but I can't seem to find what it is...</p> <p>See code here:</p> <pre><code>&lt;?php if ($_POST['destroy']) { session_destroy(); } else { session_start(); } ?&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Session test&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;?php if (isset($_POST['destroy'])) { echo "Destroy set"; } $_SESSION['counter']++; echo "You have visited this page " . $_SESSION['counter'] . " times" . "&lt;BR&gt;"; echo "I am tracking you using the session id " . session_id() . "&lt;BR&gt;"; echo "Click &lt;a href=\"" . $_SERVER['PHP_SELF'] . "?destroy=1\"&gt;here&lt;/a&gt; to destroy the session."; ?&gt; </code></pre>
[ { "answer_id": 16818, "author": "Andrew G. Johnson", "author_id": 428190, "author_profile": "https://Stackoverflow.com/users/428190", "pm_score": 4, "selected": true, "text": "<p>I think you put</p>\n\n<pre><code>$_POST['destroy']\n</code></pre>\n\n<p>Instead of</p>\n\n<pre><code>$_GET['...
2008/08/19
[ "https://Stackoverflow.com/questions/16815", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1912/" ]
I'm trying to do a simple test php script for sessions. Basically it increments a counter (stored in `$_SESSION`) every time you refresh that page. That works, but I'm trying to have a link to destroy the session which reloads the page with the `?destroy=1` parameter. I've tried a couple of if statements to see if that parameter is set and if so to destroy the session but it doesn't seem to work. I've even put an if statement in the main body to pop-up a message if the parameter is set - but it doesn't seem to be picked up. I know I'm doing something silly (I'm a PHP newbie) but I can't seem to find what it is... See code here: ``` <?php if ($_POST['destroy']) { session_destroy(); } else { session_start(); } ?> <html> <head> <title>Session test</title> </head> <body> <?php if (isset($_POST['destroy'])) { echo "Destroy set"; } $_SESSION['counter']++; echo "You have visited this page " . $_SESSION['counter'] . " times" . "<BR>"; echo "I am tracking you using the session id " . session_id() . "<BR>"; echo "Click <a href=\"" . $_SERVER['PHP_SELF'] . "?destroy=1\">here</a> to destroy the session."; ?> ```
I think you put ``` $_POST['destroy'] ``` Instead of ``` $_GET['destroy'] ``` You need to use a form if you'd like to use a $\_POST variable. $\_GET variables are stored in the URL.
16,828
<p>It seems like the only way to do this is to pass the -i parameter in when you initially run less. Does anyone know of some secret hack to make something like this work</p> <pre><code>/something to search for/i </code></pre>
[ { "answer_id": 16837, "author": "Juha Syrjälä", "author_id": 1431, "author_profile": "https://Stackoverflow.com/users/1431", "pm_score": 10, "selected": true, "text": "<p>You can also type command <code>-I</code> while less is running. It toggles case sensitivity for searches.</p>\n" }...
2008/08/19
[ "https://Stackoverflow.com/questions/16828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1797/" ]
It seems like the only way to do this is to pass the -i parameter in when you initially run less. Does anyone know of some secret hack to make something like this work ``` /something to search for/i ```
You can also type command `-I` while less is running. It toggles case sensitivity for searches.
16,833
<p>I need to periodically download, extract and save the contents of <a href="http://data.dot.state.mn.us/dds/det_sample.xml.gz" rel="noreferrer">http://data.dot.state.mn.us/dds/det_sample.xml.gz</a> to disk. Anyone have experience downloading gzipped files with C#?</p>
[ { "answer_id": 16841, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 2, "selected": false, "text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.io.compression.gzipstream.aspx\" rel=\"nofollow noreferrer\">GZ...
2008/08/19
[ "https://Stackoverflow.com/questions/16833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1786/" ]
I need to periodically download, extract and save the contents of <http://data.dot.state.mn.us/dds/det_sample.xml.gz> to disk. Anyone have experience downloading gzipped files with C#?
To compress: ``` using (FileStream fStream = new FileStream(@"C:\test.docx.gzip", FileMode.Create, FileAccess.Write)) { using (GZipStream zipStream = new GZipStream(fStream, CompressionMode.Compress)) { byte[] inputfile = File.ReadAllBytes(@"c:\test.docx"); zipStream.Write(inputfile, 0, inputfile.Length); } } ``` To Decompress: ``` using (FileStream fInStream = new FileStream(@"c:\test.docx.gz", FileMode.Open, FileAccess.Read)) { using (GZipStream zipStream = new GZipStream(fInStream, CompressionMode.Decompress)) { using (FileStream fOutStream = new FileStream(@"c:\test1.docx", FileMode.Create, FileAccess.Write)) { byte[] tempBytes = new byte[4096]; int i; while ((i = zipStream.Read(tempBytes, 0, tempBytes.Length)) != 0) { fOutStream.Write(tempBytes, 0, i); } } } } ``` Taken from a post I wrote last year that shows how to decompress a gzip file using C# and the built-in GZipStream class. <http://blogs.msdn.com/miah/archive/2007/09/05/zipping-files.aspx> As for downloading it, you can use the standard [WebRequest](http://msdn.microsoft.com/en-us/library/system.net.webrequest.aspx) or [WebClient](http://msdn.microsoft.com/en-us/library/system.net.webclient.aspx) classes in .NET.
16,861
<p>What is the best way to sanitize user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an <a href="http://en.wikipedia.org/wiki/Cross-site_scripting" rel="noreferrer">XSS</a> or SQL injection attack?</p>
[ { "answer_id": 16875, "author": "Justin Standard", "author_id": 92, "author_profile": "https://Stackoverflow.com/users/92", "pm_score": 0, "selected": false, "text": "<p>If you are using a framework like <a href=\"http://www.djangoproject.com/\" rel=\"nofollow noreferrer\">django</a>, th...
2008/08/19
[ "https://Stackoverflow.com/questions/16861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2019/" ]
What is the best way to sanitize user input for a Python-based web application? Is there a single function to remove HTML characters and any other necessary characters combinations to prevent an [XSS](http://en.wikipedia.org/wiki/Cross-site_scripting) or SQL injection attack?
Here is a snippet that will remove all tags not on the white list, and all tag attributes not on the attribues whitelist (so you can't use `onclick`). It is a modified version of <http://www.djangosnippets.org/snippets/205/>, with the regex on the attribute values to prevent people from using `href="javascript:..."`, and other cases described at <http://ha.ckers.org/xss.html>. (e.g. `<a href="ja&#x09;vascript:alert('hi')">` or `<a href="ja vascript:alert('hi')">`, etc.) As you can see, it uses the (awesome) [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) library. ``` import re from urlparse import urljoin from BeautifulSoup import BeautifulSoup, Comment def sanitizeHtml(value, base_url=None): rjs = r'[\s]*(&#x.{1,7})?'.join(list('javascript:')) rvb = r'[\s]*(&#x.{1,7})?'.join(list('vbscript:')) re_scripts = re.compile('(%s)|(%s)' % (rjs, rvb), re.IGNORECASE) validTags = 'p i strong b u a h1 h2 h3 pre br img'.split() validAttrs = 'href src width height'.split() urlAttrs = 'href src'.split() # Attributes which should have a URL soup = BeautifulSoup(value) for comment in soup.findAll(text=lambda text: isinstance(text, Comment)): # Get rid of comments comment.extract() for tag in soup.findAll(True): if tag.name not in validTags: tag.hidden = True attrs = tag.attrs tag.attrs = [] for attr, val in attrs: if attr in validAttrs: val = re_scripts.sub('', val) # Remove scripts (vbs & js) if attr in urlAttrs: val = urljoin(base_url, val) # Calculate the absolute url tag.attrs.append((attr, val)) return soup.renderContents().decode('utf8') ``` As the other posters have said, pretty much all Python db libraries take care of SQL injection, so this should pretty much cover you.
16,935
<p>I'm trying to compile over 100 java classes from different packages from a clean directory (no incremental compiles) using the following ant tasks:</p> <pre><code>&lt;target name="-main-src-depend"&gt; &lt;depend srcdir="${src.dir}" destdir="${bin.dir}" cache="${cache.dir}" closure="true"/&gt; &lt;/target&gt; &lt;target name="compile" depends="-main-src-depend" description="Compiles the project."&gt; &lt;echo&gt;Compiling&lt;/echo&gt; &lt;javac target="${javac.target}" source="${javac.source}" debug="${javac.debug}" srcdir="${src.dir}" destdir="${bin.dir}"&gt; &lt;classpath&gt; &lt;path refid="runtime.classpath"/&gt; &lt;path refid="compile.classpath"/&gt; &lt;/classpath&gt; &lt;/javac&gt; &lt;/target&gt; </code></pre> <p>However, the first time I run the compile task I always get a StackOverflowException. If I run the task again the compiler does an incremental build and everything works fine. This is undesirable since we are using <a href="http://cruisecontrol.sourceforge.net/" rel="noreferrer">CruiseControl</a> to do an automatic daily build and this is causing false build failures.</p> <p>As a quick-and-dirty solution I have created 2 separate tasks, compiling portions of the project in each. I really don't think this solution will hold as more classes are added in the future, and I don't want to be adding new compile tasks every time we hit the "compile limit".</p>
[ { "answer_id": 16953, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 1, "selected": false, "text": "<p>Does this happen when you run the javac command from the command line? You might want to try the <a href=\"http://ant.apach...
2008/08/19
[ "https://Stackoverflow.com/questions/16935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2024/" ]
I'm trying to compile over 100 java classes from different packages from a clean directory (no incremental compiles) using the following ant tasks: ``` <target name="-main-src-depend"> <depend srcdir="${src.dir}" destdir="${bin.dir}" cache="${cache.dir}" closure="true"/> </target> <target name="compile" depends="-main-src-depend" description="Compiles the project."> <echo>Compiling</echo> <javac target="${javac.target}" source="${javac.source}" debug="${javac.debug}" srcdir="${src.dir}" destdir="${bin.dir}"> <classpath> <path refid="runtime.classpath"/> <path refid="compile.classpath"/> </classpath> </javac> </target> ``` However, the first time I run the compile task I always get a StackOverflowException. If I run the task again the compiler does an incremental build and everything works fine. This is undesirable since we are using [CruiseControl](http://cruisecontrol.sourceforge.net/) to do an automatic daily build and this is causing false build failures. As a quick-and-dirty solution I have created 2 separate tasks, compiling portions of the project in each. I really don't think this solution will hold as more classes are added in the future, and I don't want to be adding new compile tasks every time we hit the "compile limit".
> > It will be nice to know; what can > cause or causes a StackOverflowError > during compilation of Java code? > > > It is probable that evaluating the long expression in your java file consumes lots of memory and because this is being done in conjunction with the compilation of other classes, the VM just runs out of stack space. Your generated class is perhaps pushing the legal limits for its contents. See chapter [4.10 Limitations of the Java Virtual Machine](http://java.sun.com/docs/books/jvms/second_edition/html/ClassFile.doc.html#88659) in [The Java Virtual Machine Specification, Second Edition](http://java.sun.com/docs/books/jvms/). **Fix 1: refactor the class** Since your class is being generated, this might not be an option. Still, it is worth looking at the options your class generation tool offers to see if it can produce something less troublesome. **Fix 2: increase the stack size** I think [Kieron](https://stackoverflow.com/questions/16935/ants-javac-tasks-throws-stackoverflowexception#16982) has one solution when he mentions the -Xss argument. [javac](http://java.sun.com/javase/6/docs/technotes/tools/windows/javac.html) takes a number of non-standard arguments that will vary between versions and compiler vendors. My compiler: ``` $ javac -version javac 1.6.0_05 ``` To list all the options for it, I'd use these commands: ``` javac -help javac -X javac -J-X ``` I *think* the stack limit for javac is 512Kb by default. You can increase the stack size for this compiler to 10Mb with this command: ``` javac -J-Xss10M Foo.java ``` You might be able to pass this in an Ant file with a *compilerarg* element nested in your *javac* task. ``` <javac srcdir="gen" destdir="gen-bin" debug="on" fork="true"> <compilerarg value="-J-Xss10M" /> </javac> ```
16,945
<p>I would like to rename files and folders recursively by applying a string replacement operation.</p> <p>E.g. The word "shark" in files and folders should be replaced by the word "orca".</p> <p><code>C:\Program Files\Shark Tools\Wire Shark\Sharky 10\Shark.exe</code> </p> <p>should be moved to:</p> <p><code>C:\Program Files\Orca Tools\Wire Orca\Orcay 10\Orca.exe</code></p> <p>The same operation should be of course applied to each child object in each folder level as well.</p> <p>I was experimenting with some of the members of the <code>System.IO.FileInfo</code> and <code>System.IO.DirectoryInfo</code> classes but didn't find an easy way to do it.</p> <pre><code>fi.MoveTo(fi.FullName.Replace("shark", "orca")); </code></pre> <p>Doesn't do the trick.</p> <p>I was hoping there is some kind of "genius" way to perform this kind of operation. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 17028, "author": "EBGreen", "author_id": 1358, "author_profile": "https://Stackoverflow.com/users/1358", "pm_score": 1, "selected": false, "text": "<p>So you would use recursion. Here is a powershell example that should be easy to convert to C#:</p>\n\n<pre><code>function ...
2008/08/19
[ "https://Stackoverflow.com/questions/16945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I would like to rename files and folders recursively by applying a string replacement operation. E.g. The word "shark" in files and folders should be replaced by the word "orca". `C:\Program Files\Shark Tools\Wire Shark\Sharky 10\Shark.exe` should be moved to: `C:\Program Files\Orca Tools\Wire Orca\Orcay 10\Orca.exe` The same operation should be of course applied to each child object in each folder level as well. I was experimenting with some of the members of the `System.IO.FileInfo` and `System.IO.DirectoryInfo` classes but didn't find an easy way to do it. ``` fi.MoveTo(fi.FullName.Replace("shark", "orca")); ``` Doesn't do the trick. I was hoping there is some kind of "genius" way to perform this kind of operation. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
So you would use recursion. Here is a powershell example that should be easy to convert to C#: ``` function Move-Stuff($folder) { foreach($sub in [System.IO.Directory]::GetDirectories($folder)) { Move-Stuff $sub } $new = $folder.Replace("Shark", "Orca") if(!(Test-Path($new))) { new-item -path $new -type directory } foreach($file in [System.IO.Directory]::GetFiles($folder)) { $new = $file.Replace("Shark", "Orca") move-item $file $new } } Move-Stuff "C:\Temp\Test" ```
16,964
<p>I'm trying to implement something like this:</p> <pre><code>&lt;div&gt; &lt;table&gt; &lt;thead&gt; &lt;tr&gt; &lt;td&gt;Port name&lt;/td&gt; &lt;td&gt;Current port version&lt;/td&gt; &lt;td&gt;New port version&lt;/td&gt; &lt;td&gt;Update&lt;/td&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;% foreach (var ip in Ports) { %&gt; &lt;tr&gt; &lt;td&gt; &lt;%= ip.PortName %&gt; &lt;/td&gt; &lt;td&gt; &lt;%= ip.CurrentVersion %&gt; &lt;/td&gt; &lt;td&gt; &lt;%= ip.NewVersion %&gt; &lt;/td&gt; &lt;td&gt; &lt;asp:Button ID="btnUpdate" runat="server" Text="Update" CommandArgument="&lt;% ip.PortName %&gt;" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;% } %&gt; &lt;/table&gt; &lt;/div&gt; </code></pre> <p>The button's <code>CommandArgument</code> property is where my code complains about not being able to resolve symbol <code>ip</code>. Is there any way to do what I'm trying to do? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 17024, "author": "Andrew Rimmer", "author_id": 1982, "author_profile": "https://Stackoverflow.com/users/1982", "pm_score": 3, "selected": true, "text": "<p>You don't want to use a Webforms button in ASP.NET MVC. MVC is a completely different way of working, and you no long...
2008/08/19
[ "https://Stackoverflow.com/questions/16964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/614/" ]
I'm trying to implement something like this: ``` <div> <table> <thead> <tr> <td>Port name</td> <td>Current port version</td> <td>New port version</td> <td>Update</td> </tr> </thead> <% foreach (var ip in Ports) { %> <tr> <td> <%= ip.PortName %> </td> <td> <%= ip.CurrentVersion %> </td> <td> <%= ip.NewVersion %> </td> <td> <asp:Button ID="btnUpdate" runat="server" Text="Update" CommandArgument="<% ip.PortName %>" /> </td> </tr> <% } %> </table> </div> ``` The button's `CommandArgument` property is where my code complains about not being able to resolve symbol `ip`. Is there any way to do what I'm trying to do? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
You don't want to use a Webforms button in ASP.NET MVC. MVC is a completely different way of working, and you no longer have the WebForms abstraction. You have 2 different options you can either replace your asp:Button with an input tag or use a standard hyperlink instead. If you use the input option then you will need to wrap in a form element. The form action should point to a Controller action.
16,971
<p>I would like to have a nice template for doing this in development. How do I reset an increment identity's starting value in SQL Server?</p>
[ { "answer_id": 16977, "author": "Ryan Sampson", "author_id": 1375, "author_profile": "https://Stackoverflow.com/users/1375", "pm_score": 8, "selected": true, "text": "<pre><code>DBCC CHECKIDENT('TableName', RESEED, 0)\n</code></pre>\n" }, { "answer_id": 16983, "author": "Keit...
2008/08/19
[ "https://Stackoverflow.com/questions/16971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1976/" ]
I would like to have a nice template for doing this in development. How do I reset an increment identity's starting value in SQL Server?
``` DBCC CHECKIDENT('TableName', RESEED, 0) ```
16,998
<p>I'm having trouble reading a "chunked" response when using a StreamReader to read the stream returned by GetResponseStream() of a HttpWebResponse:</p> <pre><code>// response is an HttpWebResponse StreamReader reader = new StreamReader(response.GetResponseStream()); string output = reader.ReadToEnd(); // throws exception... </code></pre> <p>When the <code>reader.ReadToEnd()</code> method is called I'm getting the following System.IO.IOException: <strong>Unable to read data from the transport connection: The connection was closed.</strong></p> <p>The above code works just fine when server returns a "non-chunked" response.</p> <p>The only way I've been able to get it to work is to use HTTP/1.0 for the initial request (instead of HTTP/1.1, the default) but this seems like a lame work-around.</p> <p>Any ideas?</p> <hr> <p>@Chuck</p> <p>Your solution works pretty good. It still throws the same IOExeception on the last Read(). But after inspecting the contents of the StringBuilder it looks like all the data has been received. So perhaps I just need to wrap the Read() in a try-catch and swallow the "error".</p>
[ { "answer_id": 17236, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>Haven't tried it this with a \"chunked\" response but would something like this work? </p>\n\n<pre><code>StringBuilder sb = n...
2008/08/19
[ "https://Stackoverflow.com/questions/16998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2047/" ]
I'm having trouble reading a "chunked" response when using a StreamReader to read the stream returned by GetResponseStream() of a HttpWebResponse: ``` // response is an HttpWebResponse StreamReader reader = new StreamReader(response.GetResponseStream()); string output = reader.ReadToEnd(); // throws exception... ``` When the `reader.ReadToEnd()` method is called I'm getting the following System.IO.IOException: **Unable to read data from the transport connection: The connection was closed.** The above code works just fine when server returns a "non-chunked" response. The only way I've been able to get it to work is to use HTTP/1.0 for the initial request (instead of HTTP/1.1, the default) but this seems like a lame work-around. Any ideas? --- @Chuck Your solution works pretty good. It still throws the same IOExeception on the last Read(). But after inspecting the contents of the StringBuilder it looks like all the data has been received. So perhaps I just need to wrap the Read() in a try-catch and swallow the "error".
Haven't tried it this with a "chunked" response but would something like this work? ``` StringBuilder sb = new StringBuilder(); Byte[] buf = new byte[8192]; Stream resStream = response.GetResponseStream(); string tmpString = null; int count = 0; do { count = resStream.Read(buf, 0, buf.Length); if(count != 0) { tmpString = Encoding.ASCII.GetString(buf, 0, count); sb.Append(tmpString); } }while (count > 0); ```
17,017
<p>How do I convert a DateTime structure to its equivalent <a href="http://www.ietf.org/rfc/rfc3339.txt" rel="noreferrer">RFC 3339</a> formatted string representation and/or parse this string representation back to a <a href="http://msdn.microsoft.com/en-us/library/system.datetime.aspx" rel="noreferrer">DateTime</a> structure? The RFC-3339 date-time format is used in a number of specifications such as the <a href="http://www.atomenabled.org/developers/syndication/atom-format-spec.php#date.constructs" rel="noreferrer">Atom Syndication Format</a>.</p>
[ { "answer_id": 17021, "author": "Oppositional", "author_id": 2029, "author_profile": "https://Stackoverflow.com/users/2029", "pm_score": 6, "selected": true, "text": "<p>This is an implementation in C# of how to parse and convert a DateTime to and from its RFC-3339 representation. The on...
2008/08/19
[ "https://Stackoverflow.com/questions/17017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2029/" ]
How do I convert a DateTime structure to its equivalent [RFC 3339](http://www.ietf.org/rfc/rfc3339.txt) formatted string representation and/or parse this string representation back to a [DateTime](http://msdn.microsoft.com/en-us/library/system.datetime.aspx) structure? The RFC-3339 date-time format is used in a number of specifications such as the [Atom Syndication Format](http://www.atomenabled.org/developers/syndication/atom-format-spec.php#date.constructs).
This is an implementation in C# of how to parse and convert a DateTime to and from its RFC-3339 representation. The only restriction it has is that the DateTime is in Coordinated Universal Time (UTC). ``` using System; using System.Globalization; namespace DateTimeConsoleApplication { /// <summary> /// Provides methods for converting <see cref="DateTime"/> structures to and from the equivalent RFC 3339 string representation. /// </summary> public static class Rfc3339DateTime { //============================================================ // Private members //============================================================ #region Private Members /// <summary> /// Private member to hold array of formats that RFC 3339 date-time representations conform to. /// </summary> private static string[] formats = new string[0]; /// <summary> /// Private member to hold the DateTime format string for representing a DateTime in the RFC 3339 format. /// </summary> private const string format = "yyyy-MM-dd'T'HH:mm:ss.fffK"; #endregion //============================================================ // Public Properties //============================================================ #region Rfc3339DateTimeFormat /// <summary> /// Gets the custom format specifier that may be used to represent a <see cref="DateTime"/> in the RFC 3339 format. /// </summary> /// <value>A <i>DateTime format string</i> that may be used to represent a <see cref="DateTime"/> in the RFC 3339 format.</value> /// <remarks> /// <para> /// This method returns a string representation of a <see cref="DateTime"/> that /// is precise to the three most significant digits of the seconds fraction; that is, it represents /// the milliseconds in a date and time value. The <see cref="Rfc3339DateTimeFormat"/> is a valid /// date-time format string for use in the <see cref="DateTime.ToString(String, IFormatProvider)"/> method. /// </para> /// </remarks> public static string Rfc3339DateTimeFormat { get { return format; } } #endregion #region Rfc3339DateTimePatterns /// <summary> /// Gets an array of the expected formats for RFC 3339 date-time string representations. /// </summary> /// <value> /// An array of the expected formats for RFC 3339 date-time string representations /// that may used in the <see cref="DateTime.TryParseExact(String, string[], IFormatProvider, DateTimeStyles, out DateTime)"/> method. /// </value> public static string[] Rfc3339DateTimePatterns { get { if (formats.Length > 0) { return formats; } else { formats = new string[11]; // Rfc3339DateTimePatterns formats[0] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; formats[1] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK"; formats[2] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK"; formats[3] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK"; formats[4] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK"; formats[5] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK"; formats[6] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK"; formats[7] = "yyyy'-'MM'-'dd'T'HH':'mm':'ssK"; // Fall back patterns formats[8] = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; // RoundtripDateTimePattern formats[9] = DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern; formats[10] = DateTimeFormatInfo.InvariantInfo.SortableDateTimePattern; return formats; } } } #endregion //============================================================ // Public Methods //============================================================ #region Parse(string s) /// <summary> /// Converts the specified string representation of a date and time to its <see cref="DateTime"/> equivalent. /// </summary> /// <param name="s">A string containing a date and time to convert.</param> /// <returns>A <see cref="DateTime"/> equivalent to the date and time contained in <paramref name="s"/>.</returns> /// <remarks> /// The string <paramref name="s"/> is parsed using formatting information in the <see cref="DateTimeFormatInfo.InvariantInfo"/> object. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="s"/> is a <b>null</b> reference (Nothing in Visual Basic).</exception> /// <exception cref="FormatException"><paramref name="s"/> does not contain a valid RFC 3339 string representation of a date and time.</exception> public static DateTime Parse(string s) { //------------------------------------------------------------ // Validate parameter //------------------------------------------------------------ if(s == null) { throw new ArgumentNullException("s"); } DateTime result; if (Rfc3339DateTime.TryParse(s, out result)) { return result; } else { throw new FormatException(String.Format(null, "{0} is not a valid RFC 3339 string representation of a date and time.", s)); } } #endregion #region ToString(DateTime utcDateTime) /// <summary> /// Converts the value of the specified <see cref="DateTime"/> object to its equivalent string representation. /// </summary> /// <param name="utcDateTime">The Coordinated Universal Time (UTC) <see cref="DateTime"/> to convert.</param> /// <returns>A RFC 3339 string representation of the value of the <paramref name="utcDateTime"/>.</returns> /// <remarks> /// <para> /// This method returns a string representation of the <paramref name="utcDateTime"/> that /// is precise to the three most significant digits of the seconds fraction; that is, it represents /// the milliseconds in a date and time value. /// </para> /// <para> /// While it is possible to display higher precision fractions of a second component of a time value, /// that value may not be meaningful. The precision of date and time values depends on the resolution /// of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock's /// resolution is approximately 10-15 milliseconds. /// </para> /// </remarks> /// <exception cref="ArgumentException">The specified <paramref name="utcDateTime"/> object does not represent a <see cref="DateTimeKind.Utc">Coordinated Universal Time (UTC)</see> value.</exception> public static string ToString(DateTime utcDateTime) { if (utcDateTime.Kind != DateTimeKind.Utc) { throw new ArgumentException("utcDateTime"); } return utcDateTime.ToString(Rfc3339DateTime.Rfc3339DateTimeFormat, DateTimeFormatInfo.InvariantInfo); } #endregion #region TryParse(string s, out DateTime result) /// <summary> /// Converts the specified string representation of a date and time to its <see cref="DateTime"/> equivalent. /// </summary> /// <param name="s">A string containing a date and time to convert.</param> /// <param name="result"> /// When this method returns, contains the <see cref="DateTime"/> value equivalent to the date and time /// contained in <paramref name="s"/>, if the conversion succeeded, /// or <see cref="DateTime.MinValue">MinValue</see> if the conversion failed. /// The conversion fails if the s parameter is a <b>null</b> reference (Nothing in Visual Basic), /// or does not contain a valid string representation of a date and time. /// This parameter is passed uninitialized. /// </param> /// <returns><b>true</b> if the <paramref name="s"/> parameter was converted successfully; otherwise, <b>false</b>.</returns> /// <remarks> /// The string <paramref name="s"/> is parsed using formatting information in the <see cref="DateTimeFormatInfo.InvariantInfo"/> object. /// </remarks> public static bool TryParse(string s, out DateTime result) { //------------------------------------------------------------ // Attempt to convert string representation //------------------------------------------------------------ bool wasConverted = false; result = DateTime.MinValue; if (!String.IsNullOrEmpty(s)) { DateTime parseResult; if (DateTime.TryParseExact(s, Rfc3339DateTime.Rfc3339DateTimePatterns, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.AdjustToUniversal, out parseResult)) { result = DateTime.SpecifyKind(parseResult, DateTimeKind.Utc); wasConverted = true; } } return wasConverted; } #endregion } } ```
17,032
<p><a href="http://resharper.blogspot.com/2008/03/varification-using-implicitly-typed.html" rel="noreferrer">Resharper</a> certainly thinks so, and out of the box it will nag you to convert</p> <pre><code>Dooberry dooberry = new Dooberry(); </code></pre> <p>to</p> <pre><code>var dooberry = new Dooberry(); </code></pre> <p>Is that really considered the best style?</p>
[ { "answer_id": 17041, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 2, "selected": false, "text": "<p>I have a feeling this will be one of the most popular questions asked over time on Stack Overflow. It boils down to p...
2008/08/19
[ "https://Stackoverflow.com/questions/17032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1853/" ]
[Resharper](http://resharper.blogspot.com/2008/03/varification-using-implicitly-typed.html) certainly thinks so, and out of the box it will nag you to convert ``` Dooberry dooberry = new Dooberry(); ``` to ``` var dooberry = new Dooberry(); ``` Is that really considered the best style?
It's of course a matter of style, but I agree with Dare: [C# 3.0 Implicit Type Declarations: To var or not to var?](http://www.25hoursaday.com/weblog/2008/05/21/C30ImplicitTypeDeclarationsToVarOrNotToVar.aspx). I think using var instead of an explicit type makes your code less readable.In the following code: ``` var result = GetUserID(); ``` What is result? An int, a string, a GUID? Yes, it matters, and no, I shouldn't have to dig through the code to know. It's especially annoying in code samples. Jeff wrote a post on this, saying [he favors var](http://blog.codinghorror.com/department-of-declaration-redundancy-department/). But that guy's crazy! I'm seeing a pattern for stackoverflow success: dig up old CodingHorror posts and (Jeopardy style) phrase them in terms of a question.
17,054
<p>How do you use network sockets in Pascal? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 17062, "author": "Mickey", "author_id": 1494, "author_profile": "https://Stackoverflow.com/users/1494", "pm_score": 4, "selected": true, "text": "<p>Here's an example taken from <a href=\"http://www.bastisoft.de/programmierung/pascal/pasinet.html\" rel=\"nofollow noreferre...
2008/08/19
[ "https://Stackoverflow.com/questions/17054", "https://Stackoverflow.com", "https://Stackoverflow.com/users/868/" ]
How do you use network sockets in Pascal? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
Here's an example taken from <http://www.bastisoft.de/programmierung/pascal/pasinet.html> ``` program daytime; { Simple client program } uses sockets, inetaux, myerror; const RemotePort : Word = 13; var Sock : LongInt; sAddr : TInetSockAddr; sin, sout : Text; Line : String; begin if ParamCount = 0 then GenError('Supply IP address as parameter.'); with sAddr do begin Family := af_inet; Port := htons(RemotePort); Addr := StrToAddr(ParamStr(1)); if Addr = 0 then GenError('Not a valid IP address.'); end; Sock := Socket(af_inet, sock_stream, 0); if Sock = -1 then SockError('Socket: '); if not Connect(Sock, sAddr, sizeof(sAddr)) then SockError('Connect: '); Sock2Text(Sock, sin, sout); Reset(sin); Rewrite(sout); while not eof(sin) do begin Readln(sin, Line); Writeln(Line); end; Close(sin); Close(sout); Shutdown(Sock, 2); end. ```
17,056
<p>I'm currently working on an application where we have a SQL-Server database and I need to get a full text search working that allows us to search people's names.</p> <p>Currently the user can enter a into a name field that searches 3 different varchar cols. First, Last, Middle names</p> <p>So say I have 3 rows with the following info.</p> <p>1 - Phillip - J - Fry</p> <p>2 - Amy - NULL - Wong</p> <p>3 - Leo - NULL - Wong</p> <p>If the user enters a name such as 'Fry' it will return row 1. However if they enter Phillip Fry, or Fr, or Phil they get nothing.. and I don't understand why its doing this. If they search for Wong they get rows 2 and 3 if they search for Amy Wong they again get nothing.</p> <p>Currently the query is using CONTAINSTABLE but I have switched that with FREETEXTTABLE, CONTAINS, and FREETEXT without any noticeable differences in the results. The table methods are be preferred because they return the same results but with ranking.</p> <p>Here is the query.</p> <pre><code>.... @Name nvarchar(100), .... --""s added to prevent crash if searching on more then one word. DECLARE @SearchString varchar(100) SET @SearchString = '"'+@Name+'"' SELECT Per.Lastname, Per.Firstname, Per.MiddleName FROM Person as Per INNER JOIN CONTAINSTABLE(Person, (LastName, Firstname, MiddleName), @SearchString) AS KEYTBL ON Per.Person_ID = KEYTBL.[KEY] WHERE KEY_TBL.RANK &gt; 2 ORDER BY KEYTBL.RANK DESC; .... </code></pre> <p>Any Ideas...? Why this full text search is not working correctly ?</p>
[ { "answer_id": 18072, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 2, "selected": false, "text": "<p>FreeTextTable should work.</p>\n\n<pre><code>INNER JOIN FREETEXTTABLE(Person, (LastName, Firstname, MiddleName), @SearchString)...
2008/08/19
[ "https://Stackoverflow.com/questions/17056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1925/" ]
I'm currently working on an application where we have a SQL-Server database and I need to get a full text search working that allows us to search people's names. Currently the user can enter a into a name field that searches 3 different varchar cols. First, Last, Middle names So say I have 3 rows with the following info. 1 - Phillip - J - Fry 2 - Amy - NULL - Wong 3 - Leo - NULL - Wong If the user enters a name such as 'Fry' it will return row 1. However if they enter Phillip Fry, or Fr, or Phil they get nothing.. and I don't understand why its doing this. If they search for Wong they get rows 2 and 3 if they search for Amy Wong they again get nothing. Currently the query is using CONTAINSTABLE but I have switched that with FREETEXTTABLE, CONTAINS, and FREETEXT without any noticeable differences in the results. The table methods are be preferred because they return the same results but with ranking. Here is the query. ``` .... @Name nvarchar(100), .... --""s added to prevent crash if searching on more then one word. DECLARE @SearchString varchar(100) SET @SearchString = '"'+@Name+'"' SELECT Per.Lastname, Per.Firstname, Per.MiddleName FROM Person as Per INNER JOIN CONTAINSTABLE(Person, (LastName, Firstname, MiddleName), @SearchString) AS KEYTBL ON Per.Person_ID = KEYTBL.[KEY] WHERE KEY_TBL.RANK > 2 ORDER BY KEYTBL.RANK DESC; .... ``` Any Ideas...? Why this full text search is not working correctly ?
Thanks for the responses guys I finally was able to get it to work. With part of both Biri, and Kibbee's answers. I needed to add \* to the string and break it up on spaces in order to work. So in the end I got ``` .... @Name nvarchar(100), .... --""s added to prevent crash if searching on more then one word. DECLARE @SearchString varchar(100) --Added this line SET @SearchString = REPLACE(@Name, ' ', '*" OR "*') SET @SearchString = '"*'+@SearchString+'*"' SELECT Per.Lastname, Per.Firstname, Per.MiddleName FROM Person as Per INNER JOIN CONTAINSTABLE(Person, (LastName, Firstname, MiddleName), @SearchString) AS KEYTBL ON Per.Person_ID = KEYTBL.[KEY] WHERE KEY_TBL.RANK > 2 ORDER BY KEYTBL.RANK DESC; .... ``` There are more fields being searched upon I just simplified it for the question, sorry about that, I didn't think it would effect the answer. It actually searches a column that has a csv of nicknames and a notes column as well. Thanks for the help.
17,085
<p>I have a simple CAML query like</p> <pre><code>&lt;Where&gt;&lt;Eq&gt;&lt;Field="FieldName"&gt;&lt;Value Type="Text"&gt;Value text&lt;/Value&gt;&lt;/Field&gt;&lt;/Eq&gt;&lt;/Where&gt; </code></pre> <p>And I have a variable to substitute for <code>Value text</code>. What's the best way to validate/escape the text that is substituted here in the .NET framework? I've done a quick web search on this problem but all what I found was <a href="http://msdn.microsoft.com/en-us/library/system.xml.xmlconvert.aspx" rel="nofollow noreferrer"><code>System.Xml.Convert</code></a> class but this seems to be not quite what I need here.</p> <p>I know I could have gone with an <code>XmlWriter</code> here, but it seems like a lot of code for such a simple task where I just need to make sure that the <code>Value text</code> part is formatted well.</p>
[ { "answer_id": 17093, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 0, "selected": false, "text": "<p>use <code>System.Xml.Linq.XElement</code> and <code>SetValue</code> method. This will format the text <em>(assuming a stri...
2008/08/19
[ "https://Stackoverflow.com/questions/17085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/578/" ]
I have a simple CAML query like ``` <Where><Eq><Field="FieldName"><Value Type="Text">Value text</Value></Field></Eq></Where> ``` And I have a variable to substitute for `Value text`. What's the best way to validate/escape the text that is substituted here in the .NET framework? I've done a quick web search on this problem but all what I found was [`System.Xml.Convert`](http://msdn.microsoft.com/en-us/library/system.xml.xmlconvert.aspx) class but this seems to be not quite what I need here. I know I could have gone with an `XmlWriter` here, but it seems like a lot of code for such a simple task where I just need to make sure that the `Value text` part is formatted well.
When working with XML, always use the XML API that works with your programming environment. Don't try to roll your own XML document building and escaping code. As Longhorn213 mentioned, in .Net all the appropriate stuff is in the System.XML namespace. Trying to to write your own code for writing XML documents will just result in many bugs and troubles down the line.
17,125
<p>I know what <code>yield</code> does, and I've seen a few examples, but I can't think of real life applications, have you used it to solve some specific problem?</p> <p>(Ideally some problem that cannot be solved some other way)</p>
[ { "answer_id": 17133, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 3, "selected": false, "text": "<p>actually I use it in a non traditional way on my site <a href=\"http://www.ideapipe.com\" rel=\"noreferrer\">IdeaPipe</a>...
2008/08/19
[ "https://Stackoverflow.com/questions/17125", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1782/" ]
I know what `yield` does, and I've seen a few examples, but I can't think of real life applications, have you used it to solve some specific problem? (Ideally some problem that cannot be solved some other way)
I realise this is an old question (pre Jon Skeet?) but I have been considering this question myself just lately. Unfortunately the current answers here (in my opinion) don't mention the most obvious advantage of the yield statement. The biggest benefit of the yield statement is that it allows you to iterate over very large lists with much more efficient memory usage then using say a standard list. For example, let's say you have a database query that returns 1 million rows. You could retrieve all rows using a DataReader and store them in a List, therefore requiring list\_size \* row\_size bytes of memory. Or you could use the yield statement to create an Iterator and only ever store one row in memory at a time. In effect this gives you the ability to provide a "streaming" capability over large sets of data. Moreover, in the code that uses the Iterator, you use a simple foreach loop and can decide to break out from the loop as required. If you do break early, you have not forced the retrieval of the entire set of data when you only needed the first 5 rows (for example). Regarding: ``` Ideally some problem that cannot be solved some other way ``` The yield statement does not give you anything you could not do using your own custom iterator implementation, but it saves you needing to write the often complex code needed. There are very few problems (if any) that can't solved more than one way. Here are a couple of more recent questions and answers that provide more detail: [Yield keyword value added?](https://stackoverflow.com/questions/384392/yield-keyword-value-added) [Is yield useful outside of LINQ?](https://stackoverflow.com/questions/317619/is-yield-useful-outside-of-linq)
17,140
<p>How do you run an external program and pass it command line parameters using C? If you have to use operating system API, include a solution for Windows, Mac, and Linux.</p>
[ { "answer_id": 17148, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 4, "selected": false, "text": "<pre><code>#include &lt;stdlib.h&gt;\n\nint main()\n{\n system(\"echo HAI\");\n\n return 0;\n}\n</code></pre>\n" },...
2008/08/19
[ "https://Stackoverflow.com/questions/17140", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432/" ]
How do you run an external program and pass it command line parameters using C? If you have to use operating system API, include a solution for Windows, Mac, and Linux.
It really depends on what you're trying to do, exactly, as it's: 1. OS dependent 2. Not quite clear what you're trying to do. Nevertheless, I'll try to provide some information for you to decide. On UNIX, `fork()` creates a clone of your process from the place where you called fork. Meaning, if I have the following process: ``` #include <unistd.h> #include <stdio.h> int main() { printf( "hi 2 u\n" ); int mypid = fork(); if( 0 == mypid ) printf( "lol child\n" ); else printf( "lol parent\n" ); return( 0 ); } ``` The output will look as follows: > > > > > > hi 2 u > > > > lol child > > > > lol parent > > > > > > > > > When you `fork()` the pid returned in the child is 0, and the pid returned in the parent is the child's pid. Notice that "hi2u" is only printed once... by the **parent**. `execve()` and its family of functions are almost always used with `fork().` `execve()` and the like overwrite the current stackframe with the name of the application you pass to it. `execve()` is almost always used with `fork()` where you fork a child process and if you're the parent you do whatever you need to keep doing and if you're the child you exec a new process. `execve()` is also almost always used with `waitpid()` -- waitpid takes a pid of a child process and, quite literally, *waits* until the child terminates and returns the child's exit status to you. Using this information, you should be able to write a very basic shell; one that takes process names on the command line and runs processes you tell it to. Of course, shells do more than that, like piping input and output, but you should be able to accomplish the basics using `fork()`, `execve()` and `waitpid()`. **NOTE: This is \*nix specific! This will NOT work on Windows.** Hope this helped.
17,172
<p>I've tried to do this several times with no luck. After reading <a href="https://stackoverflow.com/questions/1451/what-is-the-best-way-to-handle-multiple-permission-types#1477">this post</a>, it made me interested in doing this again. So can anyone tell me why the following doesn't work?</p> <pre><code>&lt;?php $guest = 1; $editor = 2; $admin = 4; $user = $editor; if( $user == ($editor | $admin) ) { echo "Test"; } ?&gt; </code></pre>
[ { "answer_id": 17173, "author": "Espen Herseth Halvorsen", "author_id": 1542, "author_profile": "https://Stackoverflow.com/users/1542", "pm_score": 2, "selected": false, "text": "<p>It's been a long time since I used PHP, but I will assume that this will work:</p>\n\n<pre><code>&lt;?php\...
2008/08/19
[ "https://Stackoverflow.com/questions/17172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40/" ]
I've tried to do this several times with no luck. After reading [this post](https://stackoverflow.com/questions/1451/what-is-the-best-way-to-handle-multiple-permission-types#1477), it made me interested in doing this again. So can anyone tell me why the following doesn't work? ``` <?php $guest = 1; $editor = 2; $admin = 4; $user = $editor; if( $user == ($editor | $admin) ) { echo "Test"; } ?> ```
Use the bitwise OR operator (|) to set bits, use the AND operator (&) to check bits. Your code should look like this: ``` <?php $guest = 1; $editor = 2; $admin = 4; $user = $editor; if( $user & ($editor | $admin) ) { echo "Test"; } ?> ``` If you don't understand binary and exactly what the bitwise operators do, you should go learn it. You'll understand how to do this much better.
17,181
<p>In my most C++ project I heavily used ASSERTION statement as following:</p> <pre><code>int doWonderfulThings(const int* fantasticData) { ASSERT(fantasticData); if(!fantasticData) return -1; // ,,, return WOW_VALUE; } </code></pre> <p>But TDD community seems like to enjoy doing something like this:</p> <pre><code>int doMoreWonderfulThings(const int* fantasticData) { if(!fantasticData) return ERROR_VALUE; // ... return AHA_VALUE; } TEST(TDD_Enjoy) { ASSERT_EQ(ERROR_VALUE, doMoreWonderfulThings(0L)); ASSERT_EQ(AHA_VALUE, doMoreWonderfulThings("Foo")); } </code></pre> <p>Just with my experiences first approaches let me remove so many subtle bugs. But TDD approaches are very smart idea to handle legacy codes.</p> <p>"Google" - they compare "FIRST METHOD" to "Walk the shore with life-vest, swim ocean without any safe guard".</p> <p>Which one is better? Which one makes software robust?</p>
[ { "answer_id": 17192, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "<p>I don't know which particlar TDD subcommunity you're refering to but the TDD patterns I've come across either use Asse...
2008/08/19
[ "https://Stackoverflow.com/questions/17181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1556/" ]
In my most C++ project I heavily used ASSERTION statement as following: ``` int doWonderfulThings(const int* fantasticData) { ASSERT(fantasticData); if(!fantasticData) return -1; // ,,, return WOW_VALUE; } ``` But TDD community seems like to enjoy doing something like this: ``` int doMoreWonderfulThings(const int* fantasticData) { if(!fantasticData) return ERROR_VALUE; // ... return AHA_VALUE; } TEST(TDD_Enjoy) { ASSERT_EQ(ERROR_VALUE, doMoreWonderfulThings(0L)); ASSERT_EQ(AHA_VALUE, doMoreWonderfulThings("Foo")); } ``` Just with my experiences first approaches let me remove so many subtle bugs. But TDD approaches are very smart idea to handle legacy codes. "Google" - they compare "FIRST METHOD" to "Walk the shore with life-vest, swim ocean without any safe guard". Which one is better? Which one makes software robust?
In my (limited) experience the first option is quite a bit safer. In a test-case you only test predefined input and compare the outcome, this works well as long as every possible edge-case has been checked. The first option just checks every input and thus tests the 'live' values, it filters out bugs real quickly, however it comes with a performance penalty. In [Code Complete](https://rads.stackoverflow.com/amzn/click/com/0735619670) Steve McConnell learns us the first method can be used successfully to filter out bugs in a **debug** build. In release build you can filter-out all assertions (for instance with a compiler flag) to get the extra performance. In my opinion the best way is to use both methods: Method 1 to catch illegal values ``` int doWonderfulThings(const int* fantasticData) { ASSERT(fantasticData); ASSERTNOTEQUAL(0, fantasticData) return WOW_VALUE / fantasticData; } ``` and method 2 to test edge-cases of an algorithm. ``` int doMoreWonderfulThings(const int fantasticNumber) { int count = 100; for(int i = 0; i < fantasticNumber; ++i) { count += 10 * fantasticNumber; } return count; } TEST(TDD_Enjoy) { // Test lower edge ASSERT_EQ(0, doMoreWonderfulThings(-1)); ASSERT_EQ(0, doMoreWonderfulThings(0)); ASSERT_EQ(110, doMoreWonderfulThings(1)); //Test some random values ASSERT_EQ(350, doMoreWonderfulThings(5)); ASSERT_EQ(2350, doMoreWonderfulThings(15)); ASSERT_EQ(225100, doMoreWonderfulThings(150)); } ```
17,194
<p>I have a Monthly Status database view I need to build a report based on. The data in the view looks something like this:</p> <pre><code>Category | Revenue | Yearh | Month Bikes 10 000 2008 1 Bikes 12 000 2008 2 Bikes 12 000 2008 3 Bikes 15 000 2008 1 Bikes 11 000 2007 2 Bikes 11 500 2007 3 Bikes 15 400 2007 4 </code></pre> <p><br/> ... And so forth</p> <p>The view has a product category, a revenue, a year and a month. I want to create a report comparing 2007 and 2008, showing 0 for the months with no sales. So the report should look something like this:</p> <pre><code>Category | Month | Rev. This Year | Rev. Last Year Bikes 1 10 000 0 Bikes 2 12 000 11 000 Bikes 3 12 000 11 500 Bikes 4 0 15 400 </code></pre> <p><br/> The key thing to notice is how month 1 only has sales in 2008, and therefore is 0 for 2007. Also, month 4 only has no sales in 2008, hence the 0, while it has sales in 2007 and still show up.</p> <p>Also, the report is actually for financial year - so I would love to have empty columns with 0 in both if there was no sales in say month 5 for either 2007 or 2008.</p> <p>The query I got looks something like this:</p> <pre><code>SELECT SP1.Program, SP1.Year, SP1.Month, SP1.TotalRevenue, IsNull(SP2.TotalRevenue, 0) AS LastYearTotalRevenue FROM PVMonthlyStatusReport AS SP1 LEFT OUTER JOIN PVMonthlyStatusReport AS SP2 ON SP1.Program = SP2.Program AND SP2.Year = SP1.Year - 1 AND SP1.Month = SP2.Month WHERE SP1.Program = 'Bikes' AND SP1.Category = @Category AND (SP1.Year &gt;= @FinancialYear AND SP1.Year &lt;= @FinancialYear + 1) AND ((SP1.Year = @FinancialYear AND SP1.Month &gt; 6) OR (SP1.Year = @FinancialYear + 1 AND SP1.Month &lt;= 6)) ORDER BY SP1.Year, SP1.Month </code></pre> <p>The problem with this query is that it would not return the fourth row in my example data above, since we didn't have any sales in 2008, but we actually did in 2007.</p> <p>This is probably a common query/problem, but my SQL is rusty after doing front-end development for so long. Any help is greatly appreciated!</p> <p>Oh, btw, I'm using SQL 2005 for this query so if there are any helpful new features that might help me let me know.</p>
[ { "answer_id": 17206, "author": "Christian Hagelid", "author_id": 202, "author_profile": "https://Stackoverflow.com/users/202", "pm_score": 1, "selected": false, "text": "<p>I could be wrong but shouldn't you be using a full outer join instead of just a left join? That way you will be ge...
2008/08/19
[ "https://Stackoverflow.com/questions/17194", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199387/" ]
I have a Monthly Status database view I need to build a report based on. The data in the view looks something like this: ``` Category | Revenue | Yearh | Month Bikes 10 000 2008 1 Bikes 12 000 2008 2 Bikes 12 000 2008 3 Bikes 15 000 2008 1 Bikes 11 000 2007 2 Bikes 11 500 2007 3 Bikes 15 400 2007 4 ``` ... And so forth The view has a product category, a revenue, a year and a month. I want to create a report comparing 2007 and 2008, showing 0 for the months with no sales. So the report should look something like this: ``` Category | Month | Rev. This Year | Rev. Last Year Bikes 1 10 000 0 Bikes 2 12 000 11 000 Bikes 3 12 000 11 500 Bikes 4 0 15 400 ``` The key thing to notice is how month 1 only has sales in 2008, and therefore is 0 for 2007. Also, month 4 only has no sales in 2008, hence the 0, while it has sales in 2007 and still show up. Also, the report is actually for financial year - so I would love to have empty columns with 0 in both if there was no sales in say month 5 for either 2007 or 2008. The query I got looks something like this: ``` SELECT SP1.Program, SP1.Year, SP1.Month, SP1.TotalRevenue, IsNull(SP2.TotalRevenue, 0) AS LastYearTotalRevenue FROM PVMonthlyStatusReport AS SP1 LEFT OUTER JOIN PVMonthlyStatusReport AS SP2 ON SP1.Program = SP2.Program AND SP2.Year = SP1.Year - 1 AND SP1.Month = SP2.Month WHERE SP1.Program = 'Bikes' AND SP1.Category = @Category AND (SP1.Year >= @FinancialYear AND SP1.Year <= @FinancialYear + 1) AND ((SP1.Year = @FinancialYear AND SP1.Month > 6) OR (SP1.Year = @FinancialYear + 1 AND SP1.Month <= 6)) ORDER BY SP1.Year, SP1.Month ``` The problem with this query is that it would not return the fourth row in my example data above, since we didn't have any sales in 2008, but we actually did in 2007. This is probably a common query/problem, but my SQL is rusty after doing front-end development for so long. Any help is greatly appreciated! Oh, btw, I'm using SQL 2005 for this query so if there are any helpful new features that might help me let me know.
The Case Statement is my best sql friend. You also need a table for time to generate your 0 rev in both months. Assumptions are based on the availability of following tables: > > sales: Category | Revenue | Yearh | > Month > > > and > > tm: Year | Month (populated with all > dates required for reporting) > > > Example 1 without empty rows: ``` select Category ,month ,SUM(CASE WHEN YEAR = 2008 THEN Revenue ELSE 0 END) this_year ,SUM(CASE WHEN YEAR = 2007 THEN Revenue ELSE 0 END) last_year from sales where year in (2008,2007) group by Category ,month ``` RETURNS: ``` Category | Month | Rev. This Year | Rev. Last Year Bikes 1 10 000 0 Bikes 2 12 000 11 000 Bikes 3 12 000 11 500 Bikes 4 0 15 400 ``` Example 2 with empty rows: I am going to use a sub query (but others may not) and will return an empty row for every product and year month combo. ``` select fill.Category ,fill.month ,SUM(CASE WHEN YEAR = 2008 THEN Revenue ELSE 0 END) this_year ,SUM(CASE WHEN YEAR = 2007 THEN Revenue ELSE 0 END) last_year from sales Right join (select distinct --try out left, right and cross joins to test results. product ,year ,month from sales --this ideally would be from a products table cross join tm where year in (2008,2007)) fill where fill.year in (2008,2007) group by fill.Category ,fill.month ``` RETURNS: ``` Category | Month | Rev. This Year | Rev. Last Year Bikes 1 10 000 0 Bikes 2 12 000 11 000 Bikes 3 12 000 11 500 Bikes 4 0 15 400 Bikes 5 0 0 Bikes 6 0 0 Bikes 7 0 0 Bikes 8 0 0 ``` Note that most reporting tools will do this crosstab or matrix functionality, and now that i think of it SQL Server 2005 has pivot syntax that will do this as well. Here are some additional resources. CASE <https://web.archive.org/web/20210728081626/https://www.4guysfromrolla.com/webtech/102704-1.shtml> SQL SERVER 2005 PIVOT <http://msdn.microsoft.com/en-us/library/ms177410.aspx>
17,225
<p>In Perl, you can execute system commands using system() or `` (backticks). You can even capture the output of the command into a variable. However, this hides the program execution in the background so that the person executing your script can't see it. </p> <p>Normally this is useful but sometimes I want to see what is going on behind the scenes. How do you make it so the commands executed are printed to the terminal, and those programs' output printed to the terminal? This would be the <code>.bat</code> equivalent of "@echo on".</p>
[ { "answer_id": 17245, "author": "mk.", "author_id": 1797, "author_profile": "https://Stackoverflow.com/users/1797", "pm_score": 3, "selected": false, "text": "<p>Use open instead. Then you can capture the output of the command.</p>\n\n<pre><code>open(LS,\"|ls\");\nprint LS;\n</code></pre...
2008/08/19
[ "https://Stackoverflow.com/questions/17225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432/" ]
In Perl, you can execute system commands using system() or `` (backticks). You can even capture the output of the command into a variable. However, this hides the program execution in the background so that the person executing your script can't see it. Normally this is useful but sometimes I want to see what is going on behind the scenes. How do you make it so the commands executed are printed to the terminal, and those programs' output printed to the terminal? This would be the `.bat` equivalent of "@echo on".
As I understand, system() will print the result of the command, but not assign it. Eg. ``` [daniel@tux /]$ perl -e '$ls = system("ls"); print "Result: $ls\n"' bin dev home lost+found misc net proc sbin srv System tools var boot etc lib media mnt opt root selinux sys tmp usr Result: 0 ``` Backticks will capture the output of the command and not print it: ``` [daniel@tux /]$ perl -e '$ls = `ls`; print "Result: $ls\n"' Result: bin boot dev etc home lib ``` etc... **Update:** If you want to print the name of the command being `system()` 'd as well, I think [Rudd](https://stackoverflow.com/questions/17225/echo-system-commands-to-terminal-in-perl#17304)'s approach is good. Repeated here for consolidation: ``` sub execute { my $cmd = shift; print "$cmd\n"; system($cmd); } my $cmd = $ARGV[0]; execute($cmd); ```
17,250
<p>I am creating an ZIP file with <code>ZipFile</code> in Python 2.5, it works OK so far:</p> <pre><code>import zipfile, os locfile = &quot;test.txt&quot; loczip = os.path.splitext (locfile)[0] + &quot;.zip&quot; zip = zipfile.ZipFile (loczip, &quot;w&quot;) zip.write (locfile) zip.close() </code></pre> <p>But I couldn't find how to encrypt the files in the ZIP file. I could use system and call <code>PKZIP -s</code>, but I suppose there must be a more &quot;Pythonic&quot; way. I'm looking for an open source solution.</p>
[ { "answer_id": 17287, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": -1, "selected": false, "text": "<p>You can use the <a href=\"http://www.chilkatsoft.com/python.asp\" rel=\"nofollow noreferrer\">Chilkat</a> library...
2008/08/20
[ "https://Stackoverflow.com/questions/17250", "https://Stackoverflow.com", "https://Stackoverflow.com/users/394/" ]
I am creating an ZIP file with `ZipFile` in Python 2.5, it works OK so far: ``` import zipfile, os locfile = "test.txt" loczip = os.path.splitext (locfile)[0] + ".zip" zip = zipfile.ZipFile (loczip, "w") zip.write (locfile) zip.close() ``` But I couldn't find how to encrypt the files in the ZIP file. I could use system and call `PKZIP -s`, but I suppose there must be a more "Pythonic" way. I'm looking for an open source solution.
I created a simple library to create a password encrypted zip file in python. - [**here**](https://github.com/smihica/pyminizip) ``` import pyminizip compression_level = 5 # 1-9 pyminizip.compress("src.txt", "dst.zip", "password", compression_level) ``` **The library requires zlib.** I have checked that the file can be extracted in WINDOWS/MAC.
17,299
<p>I am trying to build a function in C/C++ to sort an array and replace each value with its "score" or rank. It takes in a double pointer array to an array of ints, and sorts the double pointers based on the dereferenced value of the integers. I have tried quite a few times to make it work, but can't get it down. Once again, it must sort the double pointers based on the values they point to. This is what I have:</p> <pre><code>void SortArray( int ** pArray, int ArrayLength ) { int i, j, flag = 1; // set flag to 1 to begin initial pass int * temp; // holding variable orig with no * for(i = 1; (i &lt;= ArrayLength) &amp;&amp; flag; i++) { flag = 0; for (j = 0; j &lt; (ArrayLength -1); j++) { if (*pArray[j+1] &gt; *pArray[j]) // ascending order simply changes to &lt; { temp = &amp;pArray[j]; // swap elements pArray[j] = &amp;pArray[j+1]; pArray[j+1] = &amp;temp; flag = 1; // indicates that a swap occurred. } } } } </code></pre>
[ { "answer_id": 17312, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 4, "selected": true, "text": "<p>You're close. You're referencing the address of the array items when you swap, which isn't necessary. The items in the array are ...
2008/08/20
[ "https://Stackoverflow.com/questions/17299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522/" ]
I am trying to build a function in C/C++ to sort an array and replace each value with its "score" or rank. It takes in a double pointer array to an array of ints, and sorts the double pointers based on the dereferenced value of the integers. I have tried quite a few times to make it work, but can't get it down. Once again, it must sort the double pointers based on the values they point to. This is what I have: ``` void SortArray( int ** pArray, int ArrayLength ) { int i, j, flag = 1; // set flag to 1 to begin initial pass int * temp; // holding variable orig with no * for(i = 1; (i <= ArrayLength) && flag; i++) { flag = 0; for (j = 0; j < (ArrayLength -1); j++) { if (*pArray[j+1] > *pArray[j]) // ascending order simply changes to < { temp = &pArray[j]; // swap elements pArray[j] = &pArray[j+1]; pArray[j+1] = &temp; flag = 1; // indicates that a swap occurred. } } } } ```
You're close. You're referencing the address of the array items when you swap, which isn't necessary. The items in the array are pointers, and that's what needs to be swapped. See below: ``` void SortArray( int ** pArray, int ArrayLength ) { int i, j, flag = 1; // set flag to 1 to begin initial pass int * temp; // holding variable orig with no * for(i = ArrayLength - 1; i > 0 && flag; i--) { flag = 0; for (j = 0; j < i; j++) { if (*pArray[j] > *pArray[j+1]) // ascending order simply changes to < { temp = pArray[j]; // swap elements pArray[j] = pArray[j+1]; pArray[j+1] = temp; flag = 1; // indicates that a swap occurred. } } } } ``` Also, check out [this lovely blog post on Bubble Sorting](http://rant.blackapache.net/2008/08/14/sorting-algorithms-the-bubble-sort/) in case you're interested (sorry, shameless plug :)). Hope that helps you with your homework ;) --- Edit: Note the subtle "optimisation" where you count back from the array length and only increment up until 'i' in the inner loop. This saves you from needlessly reparsing items that have already been sorted.
17,333
<p>What would be the most efficient way to compare two <code>double</code> or two <code>float</code> values?</p> <p>Simply doing this is not correct:</p> <pre><code>bool CompareDoubles1 (double A, double B) { return A == B; } </code></pre> <p>But something like:</p> <pre><code>bool CompareDoubles2 (double A, double B) { diff = A - B; return (diff &lt; EPSILON) &amp;&amp; (-diff &lt; EPSILON); } </code></pre> <p>Seems to waste processing.</p> <p>Does anyone know a smarter float comparer?</p>
[ { "answer_id": 17341, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 8, "selected": false, "text": "<p>The comparison with an epsilon value is what most people do (even in game programming).</p>\n\n<p>You should change your impleme...
2008/08/20
[ "https://Stackoverflow.com/questions/17333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2057/" ]
What would be the most efficient way to compare two `double` or two `float` values? Simply doing this is not correct: ``` bool CompareDoubles1 (double A, double B) { return A == B; } ``` But something like: ``` bool CompareDoubles2 (double A, double B) { diff = A - B; return (diff < EPSILON) && (-diff < EPSILON); } ``` Seems to waste processing. Does anyone know a smarter float comparer?
Be extremely careful using any of the other suggestions. It all depends on context. I have spent a long time tracing bugs in a system that presumed `a==b` if `|a-b|<epsilon`. The underlying problems were: 1. The implicit presumption in an algorithm that if `a==b` and `b==c` then `a==c`. 2. Using the same epsilon for lines measured in inches and lines measured in mils (.001 inch). That is `a==b` but `1000a!=1000b`. (This is why `AlmostEqual2sComplement` asks for the epsilon or max ULPS). 3. The use of the same epsilon for both the cosine of angles and the length of lines! 4. Using such a compare function to sort items in a collection. (In this case using the builtin C++ operator `==` for doubles produced correct results.) Like I said: it all depends on context and the expected size of `a` and `b`. By the way, `std::numeric_limits<double>::epsilon()` is the "machine epsilon". It is the difference between `1.0` and the next value representable by a double. I guess that it could be used in the compare function but only if the expected values are less than 1. (This is in response to @cdv's answer...) Also, if you basically have `int` arithmetic in `doubles` (here we use doubles to hold int values in certain cases) your arithmetic will be correct. For example `4.0/2.0` will be the same as `1.0+1.0`. This is as long as you do not do things that result in fractions (`4.0/3.0`) or do not go outside of the size of an int.
17,359
<p>I've created a script that runs every night on my Linux server that uses <code>mysqldump</code> to back up each of my MySQL databases to .sql files and packages them together as a compressed .tar file. The next step I want to accomplish is to send that tar file through email to a remote email server for safekeeping. I've been able to send the raw script in the body an email by piping the backup text file to <code>mailx</code> like so:</p> <pre><code>$ cat mysqldbbackup.sql | mailx backup@email.example </code></pre> <p><code>cat</code> echoes the backup file's text which is piped into the <code>mailx</code> program with the recipient's email address passed as an argument.</p> <p>While this accomplishes what I need, I think it could be one step better, <strong>Is there any way, using shell scripts or otherwise, to send the compressed .tar file to an outgoing email message as an <em>attachment</em>?</strong> This would beat having to deal with very long email messages which contain header data and often have word-wrapping issues etc.</p>
[ { "answer_id": 17365, "author": "Chris N", "author_id": 1653, "author_profile": "https://Stackoverflow.com/users/1653", "pm_score": 5, "selected": false, "text": "<p>From looking at <code>man mailx</code>, the mailx program does not have an option for attaching a file. You could use anot...
2008/08/20
[ "https://Stackoverflow.com/questions/17359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1339/" ]
I've created a script that runs every night on my Linux server that uses `mysqldump` to back up each of my MySQL databases to .sql files and packages them together as a compressed .tar file. The next step I want to accomplish is to send that tar file through email to a remote email server for safekeeping. I've been able to send the raw script in the body an email by piping the backup text file to `mailx` like so: ``` $ cat mysqldbbackup.sql | mailx backup@email.example ``` `cat` echoes the backup file's text which is piped into the `mailx` program with the recipient's email address passed as an argument. While this accomplishes what I need, I think it could be one step better, **Is there any way, using shell scripts or otherwise, to send the compressed .tar file to an outgoing email message as an *attachment*?** This would beat having to deal with very long email messages which contain header data and often have word-wrapping issues etc.
None of the mutt ones worked for me. It was thinking the email address was part of the attachment. Had to do: ``` echo "This is the message body" | mutt -a "/path/to/file.to.attach" -s "subject of message" -- recipient@domain.example ```
17,370
<p>I've been using OpenGL extensions on Windows the <a href="https://stackoverflow.com/questions/14413/using-opengl-extensions-on-windows">painful way</a>. Is GLEW the easier way to go? How do I get started with it?</p>
[ { "answer_id": 17371, "author": "Ashwin Nanjappa", "author_id": 1630, "author_profile": "https://Stackoverflow.com/users/1630", "pm_score": 6, "selected": true, "text": "<p>Yes, the <strong>OpenGL Extension Wrangler Library</strong> (GLEW) is a painless way to use OpenGL extensions on Wi...
2008/08/20
[ "https://Stackoverflow.com/questions/17370", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
I've been using OpenGL extensions on Windows the [painful way](https://stackoverflow.com/questions/14413/using-opengl-extensions-on-windows). Is GLEW the easier way to go? How do I get started with it?
Yes, the **OpenGL Extension Wrangler Library** (GLEW) is a painless way to use OpenGL extensions on Windows. Here's how to get started on it: Identify the OpenGL extension and the extension APIs you wish to use. OpenGL extensions are listed in the [OpenGL Extension Registry](http://www.opengl.org/registry/). Check if your graphic card supports the extensions you wish to use. Download and install the latest drivers and SDKs for your graphics card. Recent versions of [NVIDIA OpenGL SDK](http://developer.nvidia.com/object/sdk_home.html) ship with GLEW. If you're using this, then you don't need to do some of the following steps. Download [GLEW](http://glew.sourceforge.net/) and unzip it. Add the GLEW **bin** path to your Windows **PATH** environment variable. Alternatively, you can also place the **glew32.dll** in a directory where Windows picks up its DLLs. Add the GLEW **include** path to your compiler's include directory list. Add the GLEW **lib** path to your compiler's library directory list. Instruct your compiler to use **glew32.lib** during linking. If you're using Visual C++ compilers then one way to do this is by adding the following line to your code: ``` #pragma comment(lib, "glew32.lib") ``` Add a `#include <GL/glew.h>` line to your code. Ensure that this is placed above the includes of other GL header files. (You may actually not need the GL header files includes if you include `glew.h`.) Initialize GLEW using `glewInit()` after you've initialized GLUT or GL. If it fails, then something is wrong with your setup. ``` if (GLEW_OK != glewInit()) { // GLEW failed! exit(1); } ``` Check if the extension(s) you wish to use are now available through GLEW. You do this by checking a boolean variable named **GLEW*\_your\_extension\_name*** which is exposed by GLEW. > > Example: > > > ``` if (!GLEW_EXT_framebuffer_object) { exit(1); } ``` That's it! You can now use the OpenGL extension calls in your code just as if they existed naturally for Windows.
17,373
<p>How do I open the default mail program with a Subject and Body in a cross-platform way?</p> <p>Unfortunately, this is for a a client app written in Java, not a website.</p> <p>I would like this to work in a cross-platform way (which means Windows and Mac, sorry Linux). I am happy to execute a VBScript in Windows, or AppleScript in OS X. But I have no idea what those scripts should contain. I would love to execute the user's default program vs. just searching for Outlook or whatever.</p> <p>In OS X, I have tried executing the command:</p> <pre><code>open mailto:?subject=MySubject&amp;body=TheBody </code></pre> <p>URL escaping is needed to replace spaces with <code>%20</code>.</p> <p><strong>Updated</strong> On Windows, you have to play all sorts of games to get <code>start</code> to run correctly. Here is the proper Java incantation:</p> <pre><code>class Win32 extends OS { public void email(String subject, String body) throws Exception { String cmd = "cmd.exe /c start \"\" \"" + formatMailto(subject, body) + "\""; Runtime.getRuntime().exec(cmd); } } </code></pre>
[ { "answer_id": 17379, "author": "Ryan Farley", "author_id": 1627, "author_profile": "https://Stackoverflow.com/users/1627", "pm_score": 2, "selected": false, "text": "<p>Mailto isn't a bad route to go. But as you mentioned, you'll need to make sure it is encoded correctly. </p>\n\n<p>The...
2008/08/20
[ "https://Stackoverflow.com/questions/17373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
How do I open the default mail program with a Subject and Body in a cross-platform way? Unfortunately, this is for a a client app written in Java, not a website. I would like this to work in a cross-platform way (which means Windows and Mac, sorry Linux). I am happy to execute a VBScript in Windows, or AppleScript in OS X. But I have no idea what those scripts should contain. I would love to execute the user's default program vs. just searching for Outlook or whatever. In OS X, I have tried executing the command: ``` open mailto:?subject=MySubject&body=TheBody ``` URL escaping is needed to replace spaces with `%20`. **Updated** On Windows, you have to play all sorts of games to get `start` to run correctly. Here is the proper Java incantation: ``` class Win32 extends OS { public void email(String subject, String body) throws Exception { String cmd = "cmd.exe /c start \"\" \"" + formatMailto(subject, body) + "\""; Runtime.getRuntime().exec(cmd); } } ```
In Java 1.6 you have a stardard way to open the default mailer of the platform: [the Desktop.mail(URI) method](http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html).The URI can be used to set all the fields of the mail (sender, recipients, body, subject). You can check a full example of desktop integration in Java 1.6 on [Using the Desktop API in Java SE 6](http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/)
17,387
<p>I have a blogengine.net install that requires privatization.</p> <p>I'm doing research work at the moment, but I have to keep my blog/journal private until certain conditions are met.</p> <p>How can I privatize my blogEngine.net install so that readers must log in to read my posts?</p>
[ { "answer_id": 17392, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 0, "selected": false, "text": "<p>I would think it's possible to do this in the web config file by doing something like the following:</p>\n\n<pre><code>&lt;sy...
2008/08/20
[ "https://Stackoverflow.com/questions/17387", "https://Stackoverflow.com", "https://Stackoverflow.com/users/209/" ]
I have a blogengine.net install that requires privatization. I'm doing research work at the moment, but I have to keep my blog/journal private until certain conditions are met. How can I privatize my blogEngine.net install so that readers must log in to read my posts?
I use this extension. Just save the file as RequireLogin.cs in your App\_Code\Extensions folder and make sure the extension is activated. ``` using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using BlogEngine.Core; using BlogEngine.Core.Web.Controls; using System.Collections.Generic; /// <summary> /// Summary description for PostSecurity /// </summary> [Extension("Checks to see if a user can see this blog post.", "1.0", "<a href=\"http://www.lavablast.com\">LavaBlast.com</a>")] public class RequireLogin { static protected ExtensionSettings settings = null; public RequireLogin() { Post.Serving += new EventHandler<ServingEventArgs>(Post_Serving); ExtensionSettings s = new ExtensionSettings("RequireLogin"); // describe specific rules for entering parameters s.Help = "Checks to see if the user has any of those roles before displaying the post. "; s.Help += "You can associate a role with a specific category. "; s.Help += "All posts having this category will require that the user have the role. "; s.Help += "A parameter with only a role without a category will enable to filter all posts to this role. "; ExtensionManager.ImportSettings(s); settings = ExtensionManager.GetSettings("PostSecurity"); } protected void Post_Serving(object sender, ServingEventArgs e) { MembershipUser user = Membership.GetUser(); if(HttpContext.Current.Request.RawUrl.Contains("syndication.axd")) { return; } if (user == null) { HttpContext.Current.Response.Redirect("~/Login.aspx"); } } } ```
17,434
<p>I have been reading through the <a href="http://yosefk.com/c++fqa/" rel="noreferrer">C++ FAQ</a> and was curious about the <a href="http://yosefk.com/c++fqa/friend.html" rel="noreferrer"><code>friend</code></a> declaration. I personally have never used it, however I am interested in exploring the language. </p> <p>What is a good example of using <code>friend</code>?</p> <hr> <p>Reading the FAQ a bit longer I like the idea of the <code>&lt;&lt;</code> <code>&gt;&gt;</code> operator overloading and adding as a friend of those classes. However I am not sure how this doesn't break encapsulation. When can these exceptions stay within the strictness that is OOP?</p>
[ { "answer_id": 17436, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 0, "selected": false, "text": "<p>When implementing tree algorithms for class, the framework code the prof gave us had the tree class as a friend of the node c...
2008/08/20
[ "https://Stackoverflow.com/questions/17434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/716/" ]
I have been reading through the [C++ FAQ](http://yosefk.com/c++fqa/) and was curious about the [`friend`](http://yosefk.com/c++fqa/friend.html) declaration. I personally have never used it, however I am interested in exploring the language. What is a good example of using `friend`? --- Reading the FAQ a bit longer I like the idea of the `<<` `>>` operator overloading and adding as a friend of those classes. However I am not sure how this doesn't break encapsulation. When can these exceptions stay within the strictness that is OOP?
Firstly (IMO) don't listen to people who say `friend` is not useful. It IS useful. In many situations you will have objects with data or functionality that are not intended to be publicly available. This is particularly true of large codebases with many authors who may only be superficially familiar with different areas. There ARE alternatives to the friend specifier, but often they are cumbersome (cpp-level concrete classes/masked typedefs) or not foolproof (comments or function name conventions). Onto the answer; The `friend` specifier allows the designated class access to protected data or functionality within the class making the friend statement. For example in the below code anyone may ask a child for their name, but only the mother and the child may change the name. You can take this simple example further by considering a more complex class such as a Window. Quite likely a Window will have many function/data elements that should not be publicly accessible, but ARE needed by a related class such as a WindowManager. ``` class Child { //Mother class members can access the private parts of class Child. friend class Mother; public: string name( void ); protected: void setName( string newName ); }; ```
17,469
<p>Try loading <a href="http://www.zodiacwheels.com/images/wheels/blackout_thumb.jpg" rel="noreferrer">this normal .jpg file</a> in Internet Explorer 6.0. I get an error saying the picture won't load. Try it in any other browser and it works fine. What's wrong? The .jpg file is just a normal picture sitting on the web server. I can even create a simple web page:</p> <pre><code>&lt;a href="http://www.zodiacwheels.com/images/wheels/blackout_thumb.jpg"&gt;blah&lt;/a&gt; </code></pre> <p>and use right click + save target as with IE6 to save it to my desktop, and it's a valid JPG file. However, <em>it won't load in the browser!</em></p> <p>Why?!</p> <p>I even tried checking the header response and MIME type and it looks fine:</p> <pre><code>andy@debian:~$ telnet www.zodiacwheels.com 80 Trying 72.167.174.247... Connected to zodiacwheels.com. Escape character is '^]'. HEAD /images/wheels/blackout_thumb.jpg HTTP/1.1 Host: www.zodiacwheels.com HTTP/1.1 200 OK Date: Wed, 20 Aug 2008 06:19:04 GMT Server: Apache Last-Modified: Wed, 20 Aug 2008 00:29:36 GMT ETag: "1387402-914ac-48ab6570" Accept-Ranges: bytes Content-Length: 595116 Content-Type: image/jpeg </code></pre> <p>The site needs to be able to work with IE6, how come it won't load a simple .jpg file?</p>
[ { "answer_id": 17471, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "<p>It is possible for other applications to register themselves as a handler for files with a particular extension. Quickt...
2008/08/20
[ "https://Stackoverflow.com/questions/17469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432/" ]
Try loading [this normal .jpg file](http://www.zodiacwheels.com/images/wheels/blackout_thumb.jpg) in Internet Explorer 6.0. I get an error saying the picture won't load. Try it in any other browser and it works fine. What's wrong? The .jpg file is just a normal picture sitting on the web server. I can even create a simple web page: ``` <a href="http://www.zodiacwheels.com/images/wheels/blackout_thumb.jpg">blah</a> ``` and use right click + save target as with IE6 to save it to my desktop, and it's a valid JPG file. However, *it won't load in the browser!* Why?! I even tried checking the header response and MIME type and it looks fine: ``` andy@debian:~$ telnet www.zodiacwheels.com 80 Trying 72.167.174.247... Connected to zodiacwheels.com. Escape character is '^]'. HEAD /images/wheels/blackout_thumb.jpg HTTP/1.1 Host: www.zodiacwheels.com HTTP/1.1 200 OK Date: Wed, 20 Aug 2008 06:19:04 GMT Server: Apache Last-Modified: Wed, 20 Aug 2008 00:29:36 GMT ETag: "1387402-914ac-48ab6570" Accept-Ranges: bytes Content-Length: 595116 Content-Type: image/jpeg ``` The site needs to be able to work with IE6, how come it won't load a simple .jpg file?
The JPG you uploaded is in [CMYK](http://en.wikipedia.org/wiki/Cmyk), IE and Firefox versions before 3 can't read these. Open it using Photoshop (or anything similar, I'm sure GIMP would work too) and resave it in [RGB](http://en.wikipedia.org/wiki/Rgb). edit: Further Googling makes me suspect that CMYK isn't really a part of the jpeg standard, but **can** be shoehorned in there. That's why some software does not consider the file valid. It does however open just fine in Photoshop CS3, and shows a cmyk colorspace.
17,483
<p>Is anyone aware of a language feature or technique in C++ to prevent a child class from over riding a particular method in the parent class?</p> <pre><code>class Base { public: bool someGuaranteedResult() { return true; } }; class Child : public Base { public: bool someGuaranteedResult() { return false; /* Haha I broke things! */ } }; </code></pre> <p>Even though it's not virtual, this is still allowed (at least in the Metrowerks compiler I'm using), all you get is a compile time warning about hiding non-virtual inherited function X.</p>
[ { "answer_id": 17485, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 0, "selected": false, "text": "<p>If you address the child class as a type of its parent, then a non-virtual function will call the parent class's version.</p>...
2008/08/20
[ "https://Stackoverflow.com/questions/17483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1366/" ]
Is anyone aware of a language feature or technique in C++ to prevent a child class from over riding a particular method in the parent class? ``` class Base { public: bool someGuaranteedResult() { return true; } }; class Child : public Base { public: bool someGuaranteedResult() { return false; /* Haha I broke things! */ } }; ``` Even though it's not virtual, this is still allowed (at least in the Metrowerks compiler I'm using), all you get is a compile time warning about hiding non-virtual inherited function X.
A couple of ideas: 1. Make your function private. 2. Do not make your function virtual. This doesn't actually prevent the function from being shadowed by another definition though. Other than that, I'm not aware of a language feature that will lock away your function in such a way which prevents it from being overloaded and still able to be invoked through a pointer/reference to the child class. Good luck!
17,500
<p>The <code>System.Windows.Threading.DispatcherObject</code> class (which <code>DependencyObject</code> is based on) contains a useful function, called <code>CheckAccess()</code>, that determines whether or not the code is running on the UI thread.</p> <p>When I wanted to use it yesterday, I was puzzled to find out that Intellisense didn't show the function (nor <code>VerifyAccess()</code>, which throws an exception when not on the UI thread), even though the MSDN library lists it. I decided to investigate the class using Reflector. It seems that the function in question has an <code>EditorBrowsable(EditorBrowsableState.Never)</code> attribute attached to it. The <code>Dispatcher</code> class, which is used by <code>DispatcherObject</code>, has the same attribute attached to <code>CheckAccess()</code> and <code>VerifyAccess()</code>:</p> <pre><code>public abstract class DispatcherObject { // ... [EditorBrowsable(EditorBrowsableState.Never)] public bool CheckAccess(); [EditorBrowsable(EditorBrowsableState.Never)] public void VerifyAccess(); // ... [EditorBrowsable(EditorBrowsableState.Advanced)] public Dispatcher Dispatcher { get; } } public sealed class Dispatcher { // ... [EditorBrowsable(EditorBrowsableState.Never)] public bool CheckAccess(); [EditorBrowsable(EditorBrowsableState.Never)] public void VerifyAccess(); // ... } </code></pre> <p>I don't believe that the application of that attribute is random (or a joke), so my question is: why is it there? Should those methods not be called directly? Then why aren't they <code>protected</code> (or <code>internal</code>, like some of the most useful methods in the WPF)?</p>
[ { "answer_id": 17507, "author": "Eric Haskins", "author_id": 100, "author_profile": "https://Stackoverflow.com/users/100", "pm_score": 0, "selected": false, "text": "<p>I can't find any documentation that says you shouldn't use those methods directly, but I haven't looked very long.</p>\...
2008/08/20
[ "https://Stackoverflow.com/questions/17500", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2074/" ]
The `System.Windows.Threading.DispatcherObject` class (which `DependencyObject` is based on) contains a useful function, called `CheckAccess()`, that determines whether or not the code is running on the UI thread. When I wanted to use it yesterday, I was puzzled to find out that Intellisense didn't show the function (nor `VerifyAccess()`, which throws an exception when not on the UI thread), even though the MSDN library lists it. I decided to investigate the class using Reflector. It seems that the function in question has an `EditorBrowsable(EditorBrowsableState.Never)` attribute attached to it. The `Dispatcher` class, which is used by `DispatcherObject`, has the same attribute attached to `CheckAccess()` and `VerifyAccess()`: ``` public abstract class DispatcherObject { // ... [EditorBrowsable(EditorBrowsableState.Never)] public bool CheckAccess(); [EditorBrowsable(EditorBrowsableState.Never)] public void VerifyAccess(); // ... [EditorBrowsable(EditorBrowsableState.Advanced)] public Dispatcher Dispatcher { get; } } public sealed class Dispatcher { // ... [EditorBrowsable(EditorBrowsableState.Never)] public bool CheckAccess(); [EditorBrowsable(EditorBrowsableState.Never)] public void VerifyAccess(); // ... } ``` I don't believe that the application of that attribute is random (or a joke), so my question is: why is it there? Should those methods not be called directly? Then why aren't they `protected` (or `internal`, like some of the most useful methods in the WPF)?
A Microsoft employee [recently stated](http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/bd0e6f6c-cadd-48f1-8e1a-163c2f17e4ca/) CheckAccess is used only for "advanced scenarios", so they hid it from Intellisense. > > "CheckAccess and VerifyAccess have > always been marked to be not visible, > maybe IntelliSense wasn't respecting > it. You can use Reflector to confirm. > The idea here is that CheckAccess and > VerifyAccess are advances scenarios, > that normal developers don't need. > > > However, I do think that > EditorBrowsableState.Advanced would > have been a more appropriate level." > > > There's a Microsoft Connect case for this shortcoming. [Vote for it](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=367777) if it's important to you.
17,586
<p>Word wrap is one of the must-have features in a modern text editor.</p> <p>How word wrap be handled? What is the best algorithm for word-wrap?</p> <p>If text is several million lines, how can I make word-wrap very fast?</p> <p>Why do I need the solution? Because my projects must draw text with various zoom level and simultaneously beautiful appearance.</p> <p>The running environment is Windows Mobile devices. The maximum 600&nbsp;MHz speed with very small memory size.</p> <p>How should I handle line information? Let's assume original data has three lines.</p> <pre><code>THIS IS LINE 1. THIS IS LINE 2. THIS IS LINE 3. </code></pre> <p>Afterwards, the break text will be shown like this:</p> <pre><code>THIS IS LINE 1. THIS IS LINE 2. THIS IS LINE 3. </code></pre> <p>Should I allocate three lines more? Or any other suggestions? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 17601, "author": "Sven Hecht", "author_id": 1168, "author_profile": "https://Stackoverflow.com/users/1168", "pm_score": 2, "selected": false, "text": "<p>With or without hyphenation?</p>\n\n<p>Without it's easy. Just encapsulate your text as wordobjects per word and give t...
2008/08/20
[ "https://Stackoverflow.com/questions/17586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1556/" ]
Word wrap is one of the must-have features in a modern text editor. How word wrap be handled? What is the best algorithm for word-wrap? If text is several million lines, how can I make word-wrap very fast? Why do I need the solution? Because my projects must draw text with various zoom level and simultaneously beautiful appearance. The running environment is Windows Mobile devices. The maximum 600 MHz speed with very small memory size. How should I handle line information? Let's assume original data has three lines. ``` THIS IS LINE 1. THIS IS LINE 2. THIS IS LINE 3. ``` Afterwards, the break text will be shown like this: ``` THIS IS LINE 1. THIS IS LINE 2. THIS IS LINE 3. ``` Should I allocate three lines more? Or any other suggestions? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
Here is a word-wrap algorithm I've written in C#. It should be fairly easy to translate into other languages (except perhaps for `IndexOfAny`). ```cs static char[] splitChars = new char[] { ' ', '-', '\t' }; private static string WordWrap(string str, int width) { string[] words = Explode(str, splitChars); int curLineLength = 0; StringBuilder strBuilder = new StringBuilder(); for(int i = 0; i < words.Length; i += 1) { string word = words[i]; // If adding the new word to the current line would be too long, // then put it on a new line (and split it up if it's too long). if (curLineLength + word.Length > width) { // Only move down to a new line if we have text on the current line. // Avoids situation where wrapped whitespace causes emptylines in text. if (curLineLength > 0) { strBuilder.Append(Environment.NewLine); curLineLength = 0; } // If the current word is too long to fit on a line even on it's own then // split the word up. while (word.Length > width) { strBuilder.Append(word.Substring(0, width - 1) + "-"); word = word.Substring(width - 1); strBuilder.Append(Environment.NewLine); } // Remove leading whitespace from the word so the new line starts flush to the left. word = word.TrimStart(); } strBuilder.Append(word); curLineLength += word.Length; } return strBuilder.ToString(); } private static string[] Explode(string str, char[] splitChars) { List<string> parts = new List<string>(); int startIndex = 0; while (true) { int index = str.IndexOfAny(splitChars, startIndex); if (index == -1) { parts.Add(str.Substring(startIndex)); return parts.ToArray(); } string word = str.Substring(startIndex, index - startIndex); char nextChar = str.Substring(index, 1)[0]; // Dashes and the likes should stick to the word occuring before it. Whitespace doesn't have to. if (char.IsWhiteSpace(nextChar)) { parts.Add(word); parts.Add(nextChar.ToString()); } else { parts.Add(word + nextChar); } startIndex = index + 1; } } ``` It's fairly primitive - it splits on spaces, tabs and dashes. It does make sure that dashes stick to the word before it (so you don't end up with stack\n-overflow) though it doesn't favour moving small hyphenated words to a newline rather than splitting them. It does split up words if they are too long for a line. It's also fairly culturally specific, as I don't know much about the word-wrapping rules of other cultures.
17,612
<p>Programmatic solution of course...</p>
[ { "answer_id": 17618, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 4, "selected": false, "text": "<p>You need to delve into unmanaged code. Here's a static class that I've been using:</p>\n\n<pre><code>public static class Re...
2008/08/20
[ "https://Stackoverflow.com/questions/17612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/580/" ]
Programmatic solution of course...
<http://www.daveamenta.com/2008-05/c-delete-a-file-to-the-recycle-bin/> From above: ``` using Microsoft.VisualBasic; string path = @"c:\myfile.txt"; FileIO.FileSystem.DeleteDirectory(path, FileIO.UIOption.OnlyErrorDialogs, RecycleOption.SendToRecycleBin); ```
17,624
<p>I have a table with a 'filename' column. I recently performed an insert into this column but in my haste forgot to append the file extension to all the filenames entered. Fortunately they are all '.jpg' images.</p> <p>How can I easily update the 'filename' column of these inserted fields (assuming I can select the recent rows based on known id values) to include the '.jpg' extension?</p>
[ { "answer_id": 17627, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 6, "selected": true, "text": "<p>The solution is:</p>\n\n<pre><code>UPDATE tablename SET [filename] = RTRIM([filename]) + '.jpg' WHERE id &gt; 50\n</cod...
2008/08/20
[ "https://Stackoverflow.com/questions/17624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
I have a table with a 'filename' column. I recently performed an insert into this column but in my haste forgot to append the file extension to all the filenames entered. Fortunately they are all '.jpg' images. How can I easily update the 'filename' column of these inserted fields (assuming I can select the recent rows based on known id values) to include the '.jpg' extension?
The solution is: ``` UPDATE tablename SET [filename] = RTRIM([filename]) + '.jpg' WHERE id > 50 ``` RTRIM is required because otherwise the [filename] column in its entirety will be selected for the string concatenation i.e. if it is a varchar(20) column and filename is only 10 letters long then it will still select those 10 letters and then 10 spaces. This will in turn result in an error as you try to fit 20 + 3 characters into a 20 character long field.
17,645
<p>Am I correct in assuming that the only difference between &quot;windows files&quot; and &quot;unix files&quot; is the linebreak?</p> <p>We have a system that has been moved from a windows machine to a unix machine and are having troubles with the format.</p> <p>I need to automate the translation between unix/windows before the files get delivered to the system in our &quot;transportsystem&quot;. I'll probably need something to determine the current format and something to transform it into the other format. If it's just the newline thats the big difference then I'm considering just reading the files with the java.io. As far as I know, they are able to handle both with readLine. And then just write each line back with</p> <pre><code>while (line = readline) print(line + NewlineInOtherFormat) .... </code></pre> <hr /> <h2>Summary:</h2> <blockquote> <p><a href="https://stackoverflow.com/users/1908/samjudson">samjudson</a>:</p> <blockquote> <p><i>This is only a difference in text files, where UNIX uses a single Line Feed (LF) to signify a new line, Windows uses a Carriage Return/Line Feed (CRLF) and Mac uses just a CR.</i></p> </blockquote> <p>to which <a href="https://stackoverflow.com/users/1612/cebjyre">Cebjyre</a> elaborates:</p> <blockquote> <p><i>OS X uses LF, the same as UNIX - MacOS 9 and below did use CR though</i></p> </blockquote> <p><a href="https://stackoverflow.com/users/1870/mo">Mo</a></p> <blockquote> <p><i>There could also be a difference in character encoding for national characters. There is no &quot;unix-encoding&quot; but many linux-variants use UTF-8 as the default encoding. Mac OS (which is also a unix) uses its own encoding (macroman). I am not sure, what windows default encoding is.</i></p> </blockquote> <p><a href="https://stackoverflow.com/users/304/mcdowell">McDowell</a></p> <blockquote> <p><i>In addition to the new-line differences, the byte-order mark can cause problems if files are treated as Unicode on Windows.</i></p> </blockquote> <p><a href="https://stackoverflow.com/users/1820/cheekysoft">Cheekysoft</a></p> <blockquote> <p><i>However, another set of problems that you may come across can be related to single/multi-byte character encodings. If you see strange unexpected chars (not at end-of-line) then this could be the reason. Especially if you see square boxes, question marks, upside-down question marks, extra characters or unexpected accented characters.</i></p> </blockquote> <p><a href="https://stackoverflow.com/users/1000/sadie">Sadie</a></p> <blockquote> <p><i>On unix, files that start with a . are hidden. On windows, it's a filesystem flag that you probably don't have easy access to. This may result in files that are supposed to be hidden now becoming visible on the client machines.</p> <p>File permissions vary between the two. You will probably find, when you copy files onto a unix system, that the files now belong to the user that did the copying and have limited rights. You'll need to use chown/chmod to make sure the correct users have access to them.</i></p> </blockquote> </blockquote> <p>There exists tools to help with the problem:</p> <blockquote> <p><a href="https://stackoverflow.com/users/755/pauldoo">pauldoo</a></p> <blockquote> <p><i>If you are just interested in the content of text files, then yes the line endings are different. Take a look at something like dos2unix, it may be of help here.</i></p> </blockquote> <p><a href="https://stackoverflow.com/users/1820/cheekysoft">Cheekysoft</a></p> <blockquote> <p><i>As pauldoo suggests, tools like dos2unix can be very useful. Note that these may be on your linux/unix system as fromdos or tofrodos, or perhaps even as the general purpose toolbox recode.</i></p> </blockquote> </blockquote> <p>Help for java coding</p> <blockquote> <p><a href="https://stackoverflow.com/users/1820/cheekysoft">Cheekysoft</a></p> <blockquote> <p><i>When writing to files or reading from files (that you are in control of), it is often worth specifying the encoding to use, as most Java methods allow this. However, also ensuring that the system locale matches can save a lot of pain</i></p> </blockquote> </blockquote>
[ { "answer_id": 17649, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 5, "selected": true, "text": "<p>This is only a difference in text files, where UNIX uses a single Line Feed (LF) to signify a new line, Windows uses a Ca...
2008/08/20
[ "https://Stackoverflow.com/questions/17645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/86/" ]
Am I correct in assuming that the only difference between "windows files" and "unix files" is the linebreak? We have a system that has been moved from a windows machine to a unix machine and are having troubles with the format. I need to automate the translation between unix/windows before the files get delivered to the system in our "transportsystem". I'll probably need something to determine the current format and something to transform it into the other format. If it's just the newline thats the big difference then I'm considering just reading the files with the java.io. As far as I know, they are able to handle both with readLine. And then just write each line back with ``` while (line = readline) print(line + NewlineInOtherFormat) .... ``` --- Summary: -------- > > [samjudson](https://stackoverflow.com/users/1908/samjudson): > > > > > > > *This is only a difference in text files, where UNIX uses a single Line Feed (LF) to signify a new line, Windows uses a Carriage Return/Line Feed (CRLF) and Mac uses just a CR.* > > > > > > > > > to which [Cebjyre](https://stackoverflow.com/users/1612/cebjyre) elaborates: > > > > > > > *OS X uses LF, the same as UNIX - MacOS 9 and below did use CR though* > > > > > > > > > [Mo](https://stackoverflow.com/users/1870/mo) > > > > > > > *There could also be a difference in character encoding for national characters. There is no "unix-encoding" but many linux-variants use UTF-8 as the default encoding. Mac OS (which is also a unix) uses its own encoding (macroman). I am not sure, what windows default encoding is.* > > > > > > > > > [McDowell](https://stackoverflow.com/users/304/mcdowell) > > > > > > > *In addition to the new-line differences, the byte-order mark can cause problems if files are treated as Unicode on Windows.* > > > > > > > > > [Cheekysoft](https://stackoverflow.com/users/1820/cheekysoft) > > > > > > > *However, another set of problems that you may come across can be related to single/multi-byte character encodings. If you see strange unexpected chars (not at end-of-line) then this could be the reason. Especially if you see square boxes, question marks, upside-down question marks, extra characters or unexpected accented characters.* > > > > > > > > > [Sadie](https://stackoverflow.com/users/1000/sadie) > > > > > > > *On unix, files that start with a . are hidden. On windows, it's a filesystem flag that you probably don't have easy access to. This may result in files that are supposed to be hidden now becoming visible on the client machines.* > > > > > > File permissions vary between the two. You will probably find, when you copy files onto a unix system, that the files now belong to the user that did the copying and have limited rights. You'll need to use chown/chmod to make sure the correct users have access to them. > > > > > > > > > There exists tools to help with the problem: > > [pauldoo](https://stackoverflow.com/users/755/pauldoo) > > > > > > > *If you are just interested in the content of text files, then yes the line endings are different. Take a look at something like dos2unix, it may be of help here.* > > > > > > > > > [Cheekysoft](https://stackoverflow.com/users/1820/cheekysoft) > > > > > > > *As pauldoo suggests, tools like dos2unix can be very useful. Note that these may be on your linux/unix system as fromdos or tofrodos, or perhaps even as the general purpose toolbox recode.* > > > > > > > > > Help for java coding > > [Cheekysoft](https://stackoverflow.com/users/1820/cheekysoft) > > > > > > > *When writing to files or reading from files (that you are in control of), it is often worth specifying the encoding to use, as most Java methods allow this. However, also ensuring that the system locale matches can save a lot of pain* > > > > > > > > >
This is only a difference in text files, where UNIX uses a single Line Feed (LF) to signify a new line, Windows uses a Carriage Return/Line Feed (CRLF) and Mac uses just a CR. Binary files there should be no difference (i.e. a JPEG on a windows machine will be byte for byte the same as the same JPEG on a unix box.)
17,664
<p>I have an ASP.net Application that runs on the internal network (well, actually it's running on Sharepoint 2007). </p> <p>I just wonder:</p> <p>Can I somehow retrieve the name of the PC the Client is using? I would have access to Active Directory if that helps. The thing is, people use multiple PCs. So, I cannot use any manual/static mapping.</p> <p>If possible, I do not want to use any client-side (read: JavaScript) code, but if it cannot be done server-side, JavaScript would be OK as well. ActiveX is absolutely out of question.</p>
[ { "answer_id": 17691, "author": "OJ.", "author_id": 611, "author_profile": "https://Stackoverflow.com/users/611", "pm_score": 2, "selected": false, "text": "<p>Does <a href=\"http://msdn.microsoft.com/en-us/library/system.web.httprequest.userhostname.aspx\" rel=\"nofollow noreferrer\">Sy...
2008/08/20
[ "https://Stackoverflow.com/questions/17664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
I have an ASP.net Application that runs on the internal network (well, actually it's running on Sharepoint 2007). I just wonder: Can I somehow retrieve the name of the PC the Client is using? I would have access to Active Directory if that helps. The thing is, people use multiple PCs. So, I cannot use any manual/static mapping. If possible, I do not want to use any client-side (read: JavaScript) code, but if it cannot be done server-side, JavaScript would be OK as well. ActiveX is absolutely out of question.
[System.Web.HttpRequest.UserHostname](https://learn.microsoft.com/en-us/dotnet/api/system.web.httprequest.userhostname?redirectedfrom=MSDN&view=netframework-4.8#System_Web_HttpRequest_UserHostName) as suggested in [this answer](https://stackoverflow.com/a/17691/1011722) just returns the IP :-( But I just found this: ``` System.Net.Dns.GetHostEntry(Page.Request.UserHostAddress).HostName ``` That only works if there is actually a DNS Server to resolve the name, which is the case for my network.
17,681
<p>I have a <a href="http://www.visualsvn.com/server/" rel="nofollow noreferrer">VisualSVN Server</a> installed on a Windows server, serving several repositories.</p> <p>Since the web-viewer built into VisualSVN server is a minimalistic subversion browser, I'd like to install <a href="http://websvn.tigris.org/" rel="nofollow noreferrer">WebSVN</a> on top of my repositories.</p> <p>The problem, however, is that I can't seem to get authentication to work. Ideally I'd like my current repository authentication as specified in VisualSVN to work with WebSVN, so that though I see all the repository names in WebSVN, I can't actually browse into them without the right credentials.</p> <p>By visiting the cached copy of the topmost link on <a href="http://www.google.com/search?q=WebSVN+authentication+with+IIS+and+VisualSVN" rel="nofollow noreferrer">this google query</a> you can see what I've found so far that looks promising.<br> (the main blog page seems to have been destroyed, domain of the topmost page I'm referring to is the-wizzard.de)</p> <p>There I found some php functions I could tack onto one of the php files in WebSVN. I followed the modifications there, but all I succeeded in doing was make WebSVN ask me for a username and password and no matter what I input, it won't let me in.</p> <p>Unfortunately, php and apache is largely black magic to me.</p> <p>So, has anyone successfully integrated WebSVN with VisualSVN hosted repositories?</p>
[ { "answer_id": 233587, "author": "Kit Roed", "author_id": 1339, "author_profile": "https://Stackoverflow.com/users/1339", "pm_score": 2, "selected": false, "text": "<p>I'm using VisualSVN Server and I just got done installing Trac. My goal was to get a better web-based repository browse...
2008/08/20
[ "https://Stackoverflow.com/questions/17681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/267/" ]
I have a [VisualSVN Server](http://www.visualsvn.com/server/) installed on a Windows server, serving several repositories. Since the web-viewer built into VisualSVN server is a minimalistic subversion browser, I'd like to install [WebSVN](http://websvn.tigris.org/) on top of my repositories. The problem, however, is that I can't seem to get authentication to work. Ideally I'd like my current repository authentication as specified in VisualSVN to work with WebSVN, so that though I see all the repository names in WebSVN, I can't actually browse into them without the right credentials. By visiting the cached copy of the topmost link on [this google query](http://www.google.com/search?q=WebSVN+authentication+with+IIS+and+VisualSVN) you can see what I've found so far that looks promising. (the main blog page seems to have been destroyed, domain of the topmost page I'm referring to is the-wizzard.de) There I found some php functions I could tack onto one of the php files in WebSVN. I followed the modifications there, but all I succeeded in doing was make WebSVN ask me for a username and password and no matter what I input, it won't let me in. Unfortunately, php and apache is largely black magic to me. So, has anyone successfully integrated WebSVN with VisualSVN hosted repositories?
I got WebSVN authentication working with VisualSVN server, albeit with a lot of hacking/trial-error customization of my own. Here's how I did it: 1. If you haven't already, install PHP manually by downloading the zip file and going through the online php manual install instructions. I installed PHP to C:\PHP 2. Extract the websvn folder to C:\Program Files\VisualSVN Server\htdocs\ 3. Go through the steps of configuring the websvn directory, i.e. rename configdist.php to config, etc. My repositories were located in C:\SVNRepositories, so to configure the authentication file, I set the config.php line so: $config->useAuthenticationFile('C:/SVNRepositories/authz'); // Global access file 4. Add the following to C:\Program Files\VisualSVN Server\conf\httpd-custom.conf : ``` # For PHP 5 do something like this: LoadModule php5_module "c:/php/php5apache2_2.dll" AddType application/x-httpd-php .php # configure the path to php.ini PHPIniDir "C:/php" <IfModule dir_module> DirectoryIndex index.html index.php </IfModule> <Location /websvn/> Options FollowSymLinks AuthType Basic AuthName "Subversion Repository" Require valid-user AuthUserFile "C:/SVNRepositories/htpasswd" AuthzSVNAccessFile "C:/SVNRepositories/authz" SVNListParentPath on SVNParentPath "C:/SVNRepositories/" </Location> ``` This worked for me, and websvn will only show those directories that are authorized for a given user. Note that in order for it to work right, you have to provide "Main Level" access to everybody, and then disable access to certain sub-directories for certain users. For example, I have one user who doesn't have main level access, but does have access to a sub-level. Unfortunately, this person can't see anything in websvn, even if he links directly to filedetails.php for a file he's authorized to see. In my case it's not a big deal because I don't want him accessing websvn anyway, but it's something you'll want to know. Also, this sets the server up for an ssl connection, so once you've set it up, the address will be and https:// address, not the regular http://.
17,772
<p>This is probably best shown with an example. I have an enum with attributes:</p> <pre><code>public enum MyEnum { [CustomInfo("This is a custom attrib")] None = 0, [CustomInfo("This is another attrib")] ValueA, [CustomInfo("This has an extra flag", AllowSomething = true)] ValueB, } </code></pre> <p>I want to get to those attributes from an instance:</p> <pre><code>public CustomInfoAttribute GetInfo( MyEnum enumInput ) { Type typeOfEnum = enumInput.GetType(); //this will be typeof( MyEnum ) //here is the problem, GetField takes a string // the .ToString() on enums is very slow FieldInfo fi = typeOfEnum.GetField( enumInput.ToString() ); //get the attribute from the field return fi.GetCustomAttributes( typeof( CustomInfoAttribute ), false ). FirstOrDefault() //Linq method to get first or null as CustomInfoAttribute; //use as operator to convert } </code></pre> <p>As this is using reflection I expect some slowness, but it seems messy to convert the enum value to a string (which reflects the name) when I already have an instance of it.</p> <p>Does anyone have a better way?</p>
[ { "answer_id": 17807, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 5, "selected": true, "text": "<p>This is probably the easiest way.</p>\n\n<p>A quicker way would be to Statically Emit the IL code using Dynamic Method ...
2008/08/20
[ "https://Stackoverflow.com/questions/17772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
This is probably best shown with an example. I have an enum with attributes: ``` public enum MyEnum { [CustomInfo("This is a custom attrib")] None = 0, [CustomInfo("This is another attrib")] ValueA, [CustomInfo("This has an extra flag", AllowSomething = true)] ValueB, } ``` I want to get to those attributes from an instance: ``` public CustomInfoAttribute GetInfo( MyEnum enumInput ) { Type typeOfEnum = enumInput.GetType(); //this will be typeof( MyEnum ) //here is the problem, GetField takes a string // the .ToString() on enums is very slow FieldInfo fi = typeOfEnum.GetField( enumInput.ToString() ); //get the attribute from the field return fi.GetCustomAttributes( typeof( CustomInfoAttribute ), false ). FirstOrDefault() //Linq method to get first or null as CustomInfoAttribute; //use as operator to convert } ``` As this is using reflection I expect some slowness, but it seems messy to convert the enum value to a string (which reflects the name) when I already have an instance of it. Does anyone have a better way?
This is probably the easiest way. A quicker way would be to Statically Emit the IL code using Dynamic Method and ILGenerator. Although I've only used this to GetPropertyInfo, but can't see why you couldn't emit CustomAttributeInfo as well. For example code to emit a getter from a property ``` public delegate object FastPropertyGetHandler(object target); private static void EmitBoxIfNeeded(ILGenerator ilGenerator, System.Type type) { if (type.IsValueType) { ilGenerator.Emit(OpCodes.Box, type); } } public static FastPropertyGetHandler GetPropertyGetter(PropertyInfo propInfo) { // generates a dynamic method to generate a FastPropertyGetHandler delegate DynamicMethod dynamicMethod = new DynamicMethod( string.Empty, typeof (object), new Type[] { typeof (object) }, propInfo.DeclaringType.Module); ILGenerator ilGenerator = dynamicMethod.GetILGenerator(); // loads the object into the stack ilGenerator.Emit(OpCodes.Ldarg_0); // calls the getter ilGenerator.EmitCall(OpCodes.Callvirt, propInfo.GetGetMethod(), null); // creates code for handling the return value EmitBoxIfNeeded(ilGenerator, propInfo.PropertyType); // returns the value to the caller ilGenerator.Emit(OpCodes.Ret); // converts the DynamicMethod to a FastPropertyGetHandler delegate // to get the property FastPropertyGetHandler getter = (FastPropertyGetHandler) dynamicMethod.CreateDelegate(typeof(FastPropertyGetHandler)); return getter; } ```
17,785
<p>I know this is not programming directly, but it's regarding a development workstation I'm setting up.</p> <p>I've got a Windows Server 2003 machine that needs to be on two LAN segments at the same time. One of them is a 10.17.x.x LAN and the other is 10.16.x.x</p> <p>The problem is that I don't want to be using up the bandwidth on the 10.16.x.x network for internet traffic, etc (this network is basically only for internal stuff, though it does have internet access) so I would like the system to use the 10.17.x.x connection for anything that is external to the LAN (and for anything on 10.17.x.x of course, and to only use the 10.16.x.x connection for things that are on <em>that</em> specific LAN.</p> <p>I've tried looking into the windows "route" command but it's fairly confusing and won't seem to let me delete routes tha tI believe are interfering with what I want it to do. Is there a better way of doing this? Any good software for segmenting your LAN access?</p>
[ { "answer_id": 17804, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>If you don't move your network cables around and can assign yourself a static IP address on the 10.16.x.x network, you can r...
2008/08/20
[ "https://Stackoverflow.com/questions/17785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/194/" ]
I know this is not programming directly, but it's regarding a development workstation I'm setting up. I've got a Windows Server 2003 machine that needs to be on two LAN segments at the same time. One of them is a 10.17.x.x LAN and the other is 10.16.x.x The problem is that I don't want to be using up the bandwidth on the 10.16.x.x network for internet traffic, etc (this network is basically only for internal stuff, though it does have internet access) so I would like the system to use the 10.17.x.x connection for anything that is external to the LAN (and for anything on 10.17.x.x of course, and to only use the 10.16.x.x connection for things that are on *that* specific LAN. I've tried looking into the windows "route" command but it's fairly confusing and won't seem to let me delete routes tha tI believe are interfering with what I want it to do. Is there a better way of doing this? Any good software for segmenting your LAN access?
I'm no network expert but I have fiddled with the route command a number of times... ``` route add 0.0.0.0 MASK 0.0.0.0 <address of gateway on 10.17.x.x net> ``` Will route all default traffic through the 10.17.x.x gateway, if you find that it still routes through the other interface, you should make sure that the new rule has a lower metric than the existing routes. Do this by adding METRIC 1 for example to the end of the line above. You could also adjust the metric in the Advanced TCP/IP Settings window of the 10.17.x.x interface, unticking the Automatic Metric checkbox and setting the value to something low, like 1 or 2.
17,786
<p>When compiling my C++ .Net application I get 104 warnings of the type:</p> <pre><code>Warning C4341 - 'XX': signed value is out of range for enum constant </code></pre> <p>Where XX can be</p> <ul> <li>WCHAR</li> <li>LONG</li> <li>BIT</li> <li>BINARY</li> <li>GUID</li> <li>...</li> </ul> <p>I can't seem to remove these warnings whatever I do. When I double click on them it takes me to a part of my code that uses OdbcParameters - any when I try a test project with all the rest of my stuff but no OdbcParameters it doesn't give the warnings.</p> <p>Any idea how I can get rid of these warnings? They're making real warnings from code I've actually written hard to see - and it just gives me a horrible feeling knowing my app has 104 warnings!</p>
[ { "answer_id": 17790, "author": "Huppie", "author_id": 1830, "author_profile": "https://Stackoverflow.com/users/1830", "pm_score": 2, "selected": false, "text": "<p>In Visual Studio you can always disable specific warnings by going to:</p>\n\n<blockquote>\n <p>Project settings -> C/C++ ...
2008/08/20
[ "https://Stackoverflow.com/questions/17786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1912/" ]
When compiling my C++ .Net application I get 104 warnings of the type: ``` Warning C4341 - 'XX': signed value is out of range for enum constant ``` Where XX can be * WCHAR * LONG * BIT * BINARY * GUID * ... I can't seem to remove these warnings whatever I do. When I double click on them it takes me to a part of my code that uses OdbcParameters - any when I try a test project with all the rest of my stuff but no OdbcParameters it doesn't give the warnings. Any idea how I can get rid of these warnings? They're making real warnings from code I've actually written hard to see - and it just gives me a horrible feeling knowing my app has 104 warnings!
This is a [compiler bug](http://forums.msdn.microsoft.com/en-US/vclanguage/thread/7bc77d72-c223-4d5e-b9f7-4c639c68b624/). Here's [another post](http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=159519&SiteID=1) confirming it's a known issue. I've got the same issue in one of my projects and there's no way to prevent it from being triggered unless you have some way of avoiding the use of OdbcParameter. The most conservative way to suppress only the buggy warnings is to use ``` #pragma warning( push ) #pragma warning( disable: 4341 ) // code affected by bug #pragma warning( pop ) ```
17,795
<p>I wanted to show the users Name Address (see <a href="http://www.ipchicken.com" rel="nofollow noreferrer">www.ipchicken.com</a>), but the only thing I can find is the IP Address. I tried a reverse lookup, but didn't work either:</p> <pre><code>IPAddress ip = IPAddress.Parse(this.lblIp.Text); string hostName = Dns.GetHostByAddress(ip).HostName; this.lblHost.Text = hostName; </code></pre> <p>But HostName is the same as the IP address.</p> <p>Who know's what I need to do?</p> <p>Thanks. Gab.</p>
[ { "answer_id": 17797, "author": "saniul", "author_id": 52, "author_profile": "https://Stackoverflow.com/users/52", "pm_score": 0, "selected": false, "text": "<p>Not all IP addresses need to have hostnames. I think that's what is happening in your case. Try it ouy with more well-known IP/...
2008/08/20
[ "https://Stackoverflow.com/questions/17795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2104/" ]
I wanted to show the users Name Address (see [www.ipchicken.com](http://www.ipchicken.com)), but the only thing I can find is the IP Address. I tried a reverse lookup, but didn't work either: ``` IPAddress ip = IPAddress.Parse(this.lblIp.Text); string hostName = Dns.GetHostByAddress(ip).HostName; this.lblHost.Text = hostName; ``` But HostName is the same as the IP address. Who know's what I need to do? Thanks. Gab.
Edit of my previous answer. Try (in vb.net): ``` Dim sTmp As String Dim ip As IPHostEntry sTmp = MaskedTextBox1.Text Dim ipAddr As IPAddress = IPAddress.Parse(sTmp) ip = Dns.GetHostEntry(ipAddr) MaskedTextBox2.Text = ip.HostName ``` Dns.resolve appears to be obsolete in later versions of .Net. As stated here before I believe the issue is caused by your IP address not having a fixed name or by it having multiple names. The example above works with Google addresses, but not with an address we use that has a couple of names associated with it.
17,870
<p>Is there a way to select data where any one of multiple conditions occur on the same field?</p> <p>Example: I would typically write a statement such as:</p> <pre><code>select * from TABLE where field = 1 or field = 2 or field = 3 </code></pre> <p>Is there a way to instead say something like:</p> <pre><code>select * from TABLE where field = 1 || 2 || 3 </code></pre> <p>Any help is appreciated.</p>
[ { "answer_id": 17872, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 6, "selected": true, "text": "<p>Sure thing, the simplest way is this:</p>\n\n<pre><code>select foo from bar where baz in (1,2,3)\n</code></pre>\n" }, ...
2008/08/20
[ "https://Stackoverflow.com/questions/17870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2116/" ]
Is there a way to select data where any one of multiple conditions occur on the same field? Example: I would typically write a statement such as: ``` select * from TABLE where field = 1 or field = 2 or field = 3 ``` Is there a way to instead say something like: ``` select * from TABLE where field = 1 || 2 || 3 ``` Any help is appreciated.
Sure thing, the simplest way is this: ``` select foo from bar where baz in (1,2,3) ```
17,877
<p>Just looking for the first step basic solution here that keeps the honest people out.</p> <p>Thanks, Mike</p>
[ { "answer_id": 17872, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 6, "selected": true, "text": "<p>Sure thing, the simplest way is this:</p>\n\n<pre><code>select foo from bar where baz in (1,2,3)\n</code></pre>\n" }, ...
2008/08/20
[ "https://Stackoverflow.com/questions/17877", "https://Stackoverflow.com", "https://Stackoverflow.com/users/785/" ]
Just looking for the first step basic solution here that keeps the honest people out. Thanks, Mike
Sure thing, the simplest way is this: ``` select foo from bar where baz in (1,2,3) ```
17,880
<p>There is a rich scripting model for Microsoft Office, but not so with Apple iWork, and specifically the word processor Pages. While there are some AppleScript hooks, it looks like the best approach is to manipulate the underlying XML data.</p> <p>This turns out to be pretty ugly because (for example) page breaks are stored in XML. So for example, you have something like:</p> <pre><code>... we hold these truths to be self evident, that &lt;/page&gt; &lt;page&gt;all men are created equal, and are ... </code></pre> <p>So if you want to add or remove text, you have to move the start/end tags around based on the size of the text on the page. This is pretty impossible without computing the number of words a page can hold, which seems wildly inelegant.</p> <p>Anybody have any thoughts on this?</p>
[ { "answer_id": 17892, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "<p>You can either use remoting or WCF. See <a href=\"http://msdn.microsoft.com/en-us/library/aa730857(VS.80).aspx#netremo...
2008/08/20
[ "https://Stackoverflow.com/questions/17880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1854/" ]
There is a rich scripting model for Microsoft Office, but not so with Apple iWork, and specifically the word processor Pages. While there are some AppleScript hooks, it looks like the best approach is to manipulate the underlying XML data. This turns out to be pretty ugly because (for example) page breaks are stored in XML. So for example, you have something like: ``` ... we hold these truths to be self evident, that </page> <page>all men are created equal, and are ... ``` So if you want to add or remove text, you have to move the start/end tags around based on the size of the text on the page. This is pretty impossible without computing the number of words a page can hold, which seems wildly inelegant. Anybody have any thoughts on this?
In order for two applications (separate processes) to exchange events, they must agree on how these events are communicated. There are many different ways of doing this, and exactly which method to use may depend on architecture and context. The general term for this kind of information exchange between processes is [Inter-process Communication (IPC)](http://en.wikipedia.org/wiki/Inter-process_communication). There exists many standard ways of doing IPC, the most common being files, pipes, (network) sockets, [remote procedure calls (RPC)](http://en.wikipedia.org/wiki/Remote_procedure_call) and shared memory. On Windows it's also common to use [window messages](http://msdn.microsoft.com/en-us/library/aa931932.aspx). I am not sure how this works for .NET/C# applications on Windows, but in native Win32 applications you can [hook on to the message loop of external processes and "spy" on the messages they are sending](http://msdn.microsoft.com/en-us/library/ms644990.aspx). If your program generates a message event when the desired function is called, this could be a way to detect it. If you are implementing both applications yourself you can chose to use any IPC method you prefer. Network sockets and higher-level socket-based protocols like HTTP, XML-RPC and SOAP are very popular these days, as they allow you do run the applications on different physical machines as well (given that they are connected via a network).
17,906
<p>I have a rather classic UI situation - two ListBoxes named <code>SelectedItems</code> and <code>AvailableItems</code> - the idea being that the items you have already selected live in <code>SelectedItems</code>, while the items that are available for adding to <code>SelectedItems</code> (i.e. every item that isn't already in there) live in <code>AvailableItems</code>.</p> <p>Also, I have the <code>&lt;</code> and <code>&gt;</code> buttons to move the current selection from one list to the other (in addition to double clicking, which works fine).</p> <p>Is it possible in WPF to set up a style/trigger to enable or disable the move buttons depending on anything being selected in either ListBox? <code>SelectedItems</code> is on the left side, so the <code>&lt;</code> button will move the selected <code>AvailableItems</code> to that list. However, if no items are selected (<code>AvailableItems.SelectedIndex == -1</code>), I want this button to be disabled (<code>IsEnabled == false</code>) - and the other way around for the other list/button.</p> <p>Is this possible to do directly in XAML, or do I need to create complex logic in the codebehind to handle it?</p>
[ { "answer_id": 18026, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "<p>Here's your solution.</p>\n\n<pre><code>&lt;Button Name=\"btn1\" &gt;click me \n &lt;Button.Style&gt; \n ...
2008/08/20
[ "https://Stackoverflow.com/questions/17906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2122/" ]
I have a rather classic UI situation - two ListBoxes named `SelectedItems` and `AvailableItems` - the idea being that the items you have already selected live in `SelectedItems`, while the items that are available for adding to `SelectedItems` (i.e. every item that isn't already in there) live in `AvailableItems`. Also, I have the `<` and `>` buttons to move the current selection from one list to the other (in addition to double clicking, which works fine). Is it possible in WPF to set up a style/trigger to enable or disable the move buttons depending on anything being selected in either ListBox? `SelectedItems` is on the left side, so the `<` button will move the selected `AvailableItems` to that list. However, if no items are selected (`AvailableItems.SelectedIndex == -1`), I want this button to be disabled (`IsEnabled == false`) - and the other way around for the other list/button. Is this possible to do directly in XAML, or do I need to create complex logic in the codebehind to handle it?
Here's your solution. ``` <Button Name="btn1" >click me <Button.Style> <Style> <Style.Triggers> <DataTrigger Binding ="{Binding ElementName=list1, Path=SelectedIndex}" Value="-1"> <Setter Property="Button.IsEnabled" Value="false"/> </DataTrigger> </Style.Triggers> </Style> </Button.Style> </Button> ```
17,911
<p>I've been having some trouble parsing various types of XML within flash (specifically FeedBurner RSS files and YouTube Data API responses). I'm using a <code>URLLoader</code> to load a XML file, and upon <code>Event.COMPLETE</code> creating a new XML object. 75% of the time this work fine, and every now and again I get this type of exception:</p> <pre><code>TypeError: Error #1085: The element type "link" must be terminated by the matching end-tag "&lt;/link&gt;". </code></pre> <p>We think the problem is that The XML is large, and perhaps the <code>Event.COMPLETE</code> event is fired before the XML is actually downloaded from the <code>URLLoader</code>. The only solution we have come up with is to set off a timer upon the Event, and essentially "wait a few seconds" before beginning to parse the data. Surely this can't be the best way to do this.</p> <p>Is there any surefire way to parse XML within Flash?</p> <p><strong>Update Sept 2 2008</strong> We have concluded the following, the excption is fired in the code at this point:</p> <pre><code>data = new XML(mainXMLLoader.data); // calculate the total number of entries. for each (var i in data.channel.item){ _totalEntries++; } </code></pre> <p>I have placed a try/catch statement around this part, and am currently displaying an error message on screen when it occurs. My question is how would an incomplete file get to this point if the <code>bytesLoaded == bytesTotal</code>?</p> <hr> <p>I have updated the original question with a status report; I guess another question could be is there a way to determine wether or not an <code>XML</code> object is properly parsed before accessing the data (in case the error is that my loop counting the number of objects is starting before the XML is actually parsed into the object)?</p> <hr> <p>@Theo: Thanks for the ignoreWhitespace tip. Also, we have determined that the event is called before its ready (We did some tests tracing <code>mainXMLLoader.bytesLoaded + "/" + mainXMLLoader.bytesLoaded</code></p>
[ { "answer_id": 17963, "author": "Re0sless", "author_id": 2098, "author_profile": "https://Stackoverflow.com/users/2098", "pm_score": 1, "selected": false, "text": "<p>Have you tried checking that the bytes loaded are the same as the total bytes?</p>\n\n<pre><code>URLLoader.bytesLoaded ==...
2008/08/20
[ "https://Stackoverflow.com/questions/17911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1306/" ]
I've been having some trouble parsing various types of XML within flash (specifically FeedBurner RSS files and YouTube Data API responses). I'm using a `URLLoader` to load a XML file, and upon `Event.COMPLETE` creating a new XML object. 75% of the time this work fine, and every now and again I get this type of exception: ``` TypeError: Error #1085: The element type "link" must be terminated by the matching end-tag "</link>". ``` We think the problem is that The XML is large, and perhaps the `Event.COMPLETE` event is fired before the XML is actually downloaded from the `URLLoader`. The only solution we have come up with is to set off a timer upon the Event, and essentially "wait a few seconds" before beginning to parse the data. Surely this can't be the best way to do this. Is there any surefire way to parse XML within Flash? **Update Sept 2 2008** We have concluded the following, the excption is fired in the code at this point: ``` data = new XML(mainXMLLoader.data); // calculate the total number of entries. for each (var i in data.channel.item){ _totalEntries++; } ``` I have placed a try/catch statement around this part, and am currently displaying an error message on screen when it occurs. My question is how would an incomplete file get to this point if the `bytesLoaded == bytesTotal`? --- I have updated the original question with a status report; I guess another question could be is there a way to determine wether or not an `XML` object is properly parsed before accessing the data (in case the error is that my loop counting the number of objects is starting before the XML is actually parsed into the object)? --- @Theo: Thanks for the ignoreWhitespace tip. Also, we have determined that the event is called before its ready (We did some tests tracing `mainXMLLoader.bytesLoaded + "/" + mainXMLLoader.bytesLoaded`
Have you tried checking that the bytes loaded are the same as the total bytes? ``` URLLoader.bytesLoaded == URLLoader.bytesTotal ``` That should tell you if the file has finished loading, it wont help with the compleate event firing to early, but it should tell you if its a problem with the xml been read. I am unsure if it will work over domains, as my xml is always on the same site.
17,928
<p>I want to quickly test an ocx. How do I drop that ocx in a console application. I have found some tutorials in CodeProject and but are incomplete. </p>
[ { "answer_id": 19021, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "<p>Isn't an OCX an ActiveX User Control? (something that you put onto a form for the user to interact with)?</p>\n\n<p>Th...
2008/08/20
[ "https://Stackoverflow.com/questions/17928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1781/" ]
I want to quickly test an ocx. How do I drop that ocx in a console application. I have found some tutorials in CodeProject and but are incomplete.
Sure..it's pretty easy. Here's a fun app I threw together. I'm assuming you have Visual C++. Save to test.cpp and compile: cl.exe /EHsc test.cpp To test with your OCX you'll need to either #import the typelib and use it's CLSID (or just hard-code the CLSID) in the CoCreateInstance call. Using #import will also help define any custom interfaces you might need. ``` #include "windows.h" #include "shobjidl.h" #include "atlbase.h" // // compile with: cl /EHsc test.cpp // // A fun little program to demonstrate creating an OCX. // (CLSID_TaskbarList in this case) // BOOL CALLBACK RemoveFromTaskbarProc( HWND hwnd, LPARAM lParam ) { ITaskbarList* ptbl = (ITaskbarList*)lParam; ptbl->DeleteTab(hwnd); return TRUE; } void HideTaskWindows(ITaskbarList* ptbl) { EnumWindows( RemoveFromTaskbarProc, (LPARAM) ptbl); } // ============ BOOL CALLBACK AddToTaskbarProc( HWND hwnd, LPARAM lParam ) { ITaskbarList* ptbl = (ITaskbarList*)lParam; ptbl->AddTab(hwnd); return TRUE;// continue enumerating } void ShowTaskWindows(ITaskbarList* ptbl) { if (!EnumWindows( AddToTaskbarProc, (LPARAM) ptbl)) throw "Unable to enum windows in ShowTaskWindows"; } // ============ int main(int, char**) { CoInitialize(0); try { CComPtr<IUnknown> pUnk; if (FAILED(CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER|CLSCTX_LOCAL_SERVER, IID_IUnknown, (void**) &pUnk))) throw "Unabled to create CLSID_TaskbarList"; // Do something with the object... CComQIPtr<ITaskbarList> ptbl = pUnk; if (ptbl) ptbl->HrInit(); HideTaskWindows(ptbl); MessageBox( GetDesktopWindow(), _T("Check out the task bar!"), _T("StackOverflow FTW"), MB_OK); ShowTaskWindows(ptbl); } catch( TCHAR * msg ) { MessageBox( GetDesktopWindow(), msg, _T("Error"), MB_OK); } CoUninitialize(); return 0; } ```
17,944
<p>I'm thinking in particular of how to display pagination controls, when using a language such as C# or Java.</p> <p>If I have <em>x</em> items which I want to display in chunks of <em>y</em> per page, how many pages will be needed?</p>
[ { "answer_id": 17949, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": -1, "selected": false, "text": "<p>You'll want to do floating point division, and then use the ceiling function, to round up the value to the next integer.</...
2008/08/20
[ "https://Stackoverflow.com/questions/17944", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2084/" ]
I'm thinking in particular of how to display pagination controls, when using a language such as C# or Java. If I have *x* items which I want to display in chunks of *y* per page, how many pages will be needed?
Found an elegant solution: ``` int pageCount = (records + recordsPerPage - 1) / recordsPerPage; ``` Source: [Number Conversion, Roland Backhouse, 2001](http://www.cs.nott.ac.uk/~rcb/G51MPC/slides/NumberLogic.pdf)
17,947
<p>I cant post the code (proprietary issues) but does anyone know what types of things would cause the following error in C#. It is being thrown by a VOIP client that I wrote (using counterpath api) when the call is ended by the other client. The error is:</p> <pre><code>System.AccessViolationException was unhandled Message="Attempted to read or write protected memory. This is often an indication that other memory is corrupt." Source="System.Windows.Forms" StackTrace: at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at CollabAnalysisSF.Edge.GUI.Forms.Program.Main() in d:\data\beyerss\Desktop\client\GUI\ARGui\Program.cs:line 18 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: </code></pre> <p><em>UPDATE:</em><br> Turns out one of the libraries we were using was sending off an event that we didnt know about, and the problem was in there somewhere. Fixed now.</p>
[ { "answer_id": 17951, "author": "TK.", "author_id": 1816, "author_profile": "https://Stackoverflow.com/users/1816", "pm_score": 1, "selected": false, "text": "<p>This kind of prolem can occur if you are calling unmanaged code e.g. a dll. It can occur when Marshalling goes horribly wrong....
2008/08/20
[ "https://Stackoverflow.com/questions/17947", "https://Stackoverflow.com", "https://Stackoverflow.com/users/673/" ]
I cant post the code (proprietary issues) but does anyone know what types of things would cause the following error in C#. It is being thrown by a VOIP client that I wrote (using counterpath api) when the call is ended by the other client. The error is: ``` System.AccessViolationException was unhandled Message="Attempted to read or write protected memory. This is often an indication that other memory is corrupt." Source="System.Windows.Forms" StackTrace: at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg) at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData) at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context) at System.Windows.Forms.Application.Run(Form mainForm) at CollabAnalysisSF.Edge.GUI.Forms.Program.Main() in d:\data\beyerss\Desktop\client\GUI\ARGui\Program.cs:line 18 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException: ``` *UPDATE:* Turns out one of the libraries we were using was sending off an event that we didnt know about, and the problem was in there somewhere. Fixed now.
List of some possibilities: * An object is being used after it has been disposed. This can happen a lot if you are disposing managed object in a finalizer (you should not do that). * An unmannaged implementation of one of the object you are using is bugged and it corrupted the process memory heap. Happens a lot with DirectX, GDI and others. * Mashaling on managed-unmanaged boundary is flawed. Make sure you pin a managed pointer before you use it on an unmanaged part of code. * You are using unsafe block and doing funny stuff with it. --- In you case it could be a problem with Windows Forms. But the problem is not that it is happening, but rather that it is not being reported correctly; you possibly still have done something wrong. Are you able to determine what control is causing the error using the HWND? Is it always the same? Is this control doing something funny just before the application crashes? Is the unmannaged part of the control a custom window or a standard control?
17,960
<p>Has anyone worked out how to get PowerShell to use <code>app.config</code> files? I have a couple of .NET DLL's I'd like to use in one of my scripts but they expect their own config sections to be present in <code>app.config</code>/<code>web.config</code>.</p>
[ { "answer_id": 18061, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 3, "selected": false, "text": "<p>I'm guessing that the settings would have to be in powershell.exe.config in the powershell directory, but that seems to ...
2008/08/20
[ "https://Stackoverflow.com/questions/17960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/419/" ]
Has anyone worked out how to get PowerShell to use `app.config` files? I have a couple of .NET DLL's I'd like to use in one of my scripts but they expect their own config sections to be present in `app.config`/`web.config`.
Cross-referencing with this thread, which helped me with the same question: [Subsonic Access To App.Config Connection Strings From Referenced DLL in Powershell Script](https://stackoverflow.com/questions/2789920/subsonic-access-to-app-config-connection-strings-from-referenced-dll-in-powershel) I added the following to my script, before invoking the DLL that needs config settings, where $configpath is the location of the file I want to load: ``` [appdomain]::CurrentDomain.SetData("APP_CONFIG_FILE", $configpath) Add-Type -AssemblyName System.Configuration ``` See [this](https://stackoverflow.com/questions/6150644/change-default-app-config-at-runtime/6151688#6151688) post to ensure the configuration file specified is applied to the running context.
17,965
<p>I have a process in Linux that's getting a segmentation fault. How can I tell it to generate a core dump when it fails?</p>
[ { "answer_id": 17994, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 9, "selected": true, "text": "<p>This depends on what shell you are using. If you are using bash, then the ulimit command controls several settings...
2008/08/20
[ "https://Stackoverflow.com/questions/17965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1084/" ]
I have a process in Linux that's getting a segmentation fault. How can I tell it to generate a core dump when it fails?
This depends on what shell you are using. If you are using bash, then the ulimit command controls several settings relating to program execution, such as whether you should dump core. If you type ``` ulimit -c unlimited ``` then that will tell bash that its programs can dump cores of any size. You can specify a size such as 52M instead of unlimited if you want, but in practice this shouldn't be necessary since the size of core files will probably never be an issue for you. In tcsh, you'd type ``` limit coredumpsize unlimited ```
17,980
<p>I've searched for this a little but I have not gotten a particularly straight answer. In C (and I guess C++), how do you determine what comes after the % when using <code>printf</code>?. For example:</p> <pre><code>double radius = 1.0; double area = 0.0; area = calculateArea( radius ); printf( "%10.1f %10.2\n", radius, area ); </code></pre> <p>I took this example straight from a book that I have on the C language. This does not make sense to me at all. Where do you come up with <code>10.1f</code> and <code>10.2f</code>? Could someone please explain this?</p>
[ { "answer_id": 17987, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 3, "selected": false, "text": "<pre><code>man 3 printf\n</code></pre>\n\n<p>on a Linux system will give you all the information you need. You can a...
2008/08/20
[ "https://Stackoverflow.com/questions/17980", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128/" ]
I've searched for this a little but I have not gotten a particularly straight answer. In C (and I guess C++), how do you determine what comes after the % when using `printf`?. For example: ``` double radius = 1.0; double area = 0.0; area = calculateArea( radius ); printf( "%10.1f %10.2\n", radius, area ); ``` I took this example straight from a book that I have on the C language. This does not make sense to me at all. Where do you come up with `10.1f` and `10.2f`? Could someone please explain this?
<http://en.wikipedia.org/wiki/Printf#printf_format_placeholders> is Wikipedia's reference for format placeholders in printf. <http://www.cplusplus.com/reference/clibrary/cstdio/printf.html> is also helpful Basically in a simple form it's %[width].[precision][type]. Width allows you to make sure that the variable which is being printed is at least a certain length (useful for tables etc). Precision allows you to specify the precision a number is printed to (eg. decimal places etc) and the informs C/C++ what the variable you've given it is (character, integer, double etc). Hope this helps **UPDATE:** To clarify using your examples: ``` printf( "%10.1f %10.2\n", radius, area ); ``` %10.1f (referring to the first argument: radius) means make it 10 characters long (ie. pad with spaces), and print it as a float with one decimal place. %10.2 (referring to the second argument: area) means make it 10 character long (as above) and print with two decimal places.
17,984
<p>Alright, this might be a bit of a long shot, but I have having problems getting AnkhSVN to connect from Visual Studio 2005 to an external SVN server. There is a network proxy in the way, but I can't seem to find a way in AnkhSVN to configure the proxy and doesn't seem to be detecting the Internet Explorer proxy configuration. Is there any way to resolve this issue, or will it likely just not work?</p>
[ { "answer_id": 17987, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 3, "selected": false, "text": "<pre><code>man 3 printf\n</code></pre>\n\n<p>on a Linux system will give you all the information you need. You can a...
2008/08/20
[ "https://Stackoverflow.com/questions/17984", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1185/" ]
Alright, this might be a bit of a long shot, but I have having problems getting AnkhSVN to connect from Visual Studio 2005 to an external SVN server. There is a network proxy in the way, but I can't seem to find a way in AnkhSVN to configure the proxy and doesn't seem to be detecting the Internet Explorer proxy configuration. Is there any way to resolve this issue, or will it likely just not work?
<http://en.wikipedia.org/wiki/Printf#printf_format_placeholders> is Wikipedia's reference for format placeholders in printf. <http://www.cplusplus.com/reference/clibrary/cstdio/printf.html> is also helpful Basically in a simple form it's %[width].[precision][type]. Width allows you to make sure that the variable which is being printed is at least a certain length (useful for tables etc). Precision allows you to specify the precision a number is printed to (eg. decimal places etc) and the informs C/C++ what the variable you've given it is (character, integer, double etc). Hope this helps **UPDATE:** To clarify using your examples: ``` printf( "%10.1f %10.2\n", radius, area ); ``` %10.1f (referring to the first argument: radius) means make it 10 characters long (ie. pad with spaces), and print it as a float with one decimal place. %10.2 (referring to the second argument: area) means make it 10 character long (as above) and print with two decimal places.
18,034
<p>How do I create a self signed SSL certificate for an Apache Server to use while testing a web app?</p>
[ { "answer_id": 18038, "author": "tgmdbm", "author_id": 1851, "author_profile": "https://Stackoverflow.com/users/1851", "pm_score": -1, "selected": false, "text": "<p>Use OpenSSL (<a href=\"http://www.openssl.org/\" rel=\"nofollow noreferrer\">http://www.openssl.org/</a>)</p>\n\n<p>Here's...
2008/08/20
[ "https://Stackoverflow.com/questions/18034", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
How do I create a self signed SSL certificate for an Apache Server to use while testing a web app?
> > **How do I create a self-signed SSL > Certificate for testing purposes?** > > > from [http://httpd.apache.org/docs/2.0/ssl/ssl\_faq.html#selfcert](http://httpd.apache.org/docs/2.0/ssl/ssl_faq.html#selfcert "How do I create a self-signed SSL Certificate for testing purposes?"): 1. Make sure OpenSSL is installed and in your PATH. 2. Run the following command, to create server.key and server.crt files: ``` openssl req -new -x509 -nodes -out server.crt -keyout server.key ``` These can be used as follows in your httpd.conf file: ``` SSLCertificateFile /path/to/this/server.crt SSLCertificateKeyFile /path/to/this/server.key ``` 3. It is important that you are aware that this server.key does not have any passphrase. To add a passphrase to the key, you should run the following command, and enter & verify the passphrase as requested. ``` openssl rsa -des3 -in server.key -out server.key.new mv server.key.new server.key ``` Please backup the server.key file, and the passphrase you entered, in a secure location.
18,059
<p>I'm using the <code>System.Windows.Forms.WebBrowser</code>, to make a view a-la Visual Studio Start Page. However, it seems the control is catching and handling all exceptions by silently sinking them! No need to tell this is a very unfortunate behaviour.</p> <pre><code>void webBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e) { // WebBrowser.Navigating event handler throw new Exception("OMG!"); } </code></pre> <p>The code above will cancel navigation and swallow the exception.</p> <pre><code>void webBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e) { // WebBrowser.Navigating event handler try { e.Cancel = true; if (actions.ContainsKey(e.Url.ToString())) { actions[e.Url.ToString()].Invoke(e.Url, webBrowser.Document); } } catch (Exception exception) { MessageBox.Show(exception.ToString()); } } </code></pre> <p>So, what I do (above) is catch all exceptions and pop a box, this is better than silently failing but still clearly far from ideal. I'd like it to redirect the exception through the normal application failure path so that it ultimately becomes unhandled, or handled by the application from the root.</p> <p>Is there any way to tell the <code>WebBrowser</code> control to stop sinking the exceptions and just forward them the natural and expected way? Or is there some hacky way to throw an exception through native boundaries?</p>
[ { "answer_id": 18138, "author": "Judah Gabriel Himango", "author_id": 536, "author_profile": "https://Stackoverflow.com/users/536", "pm_score": 1, "selected": false, "text": "<p>I haven't seen the browser eat exceptions, unless you mean script errors. Script errors can be enabled via the...
2008/08/20
[ "https://Stackoverflow.com/questions/18059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42/" ]
I'm using the `System.Windows.Forms.WebBrowser`, to make a view a-la Visual Studio Start Page. However, it seems the control is catching and handling all exceptions by silently sinking them! No need to tell this is a very unfortunate behaviour. ``` void webBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e) { // WebBrowser.Navigating event handler throw new Exception("OMG!"); } ``` The code above will cancel navigation and swallow the exception. ``` void webBrowserNavigating(object sender, WebBrowserNavigatingEventArgs e) { // WebBrowser.Navigating event handler try { e.Cancel = true; if (actions.ContainsKey(e.Url.ToString())) { actions[e.Url.ToString()].Invoke(e.Url, webBrowser.Document); } } catch (Exception exception) { MessageBox.Show(exception.ToString()); } } ``` So, what I do (above) is catch all exceptions and pop a box, this is better than silently failing but still clearly far from ideal. I'd like it to redirect the exception through the normal application failure path so that it ultimately becomes unhandled, or handled by the application from the root. Is there any way to tell the `WebBrowser` control to stop sinking the exceptions and just forward them the natural and expected way? Or is there some hacky way to throw an exception through native boundaries?
My best bet why it happens is because there is a native-managed-native boundary to cross. The native part doesn't forward the managed exceptions correctly and there is not much that can be done. I am still hoping for a better answer though.
18,077
<p>I wanted some of those spiffy rounded corners for a web project that I'm currently working on.</p> <p>I thought I'd try to accomplish it using javascript and not CSS in an effort to keep the requests for image files to a minimum (yes, I know that it's possible to combine all required rounded corner shapes into one image) and I also wanted to be able to change the background color pretty much on the fly.</p> <p>I already utilize jQuery so I looked at the excellent <a href="http://plugins.jquery.com/project/corners" rel="nofollow noreferrer">rounded corners plugin</a> and it worked like a charm in every browser I tried. Being a developer however I noticed the opportunity to make it a bit more efficient. The script already includes code for detecting if the current browser supports webkit rounded corners (safari based browsers). If so it uses raw CSS instead of creating layers of divs.</p> <p>I thought that it would be awesome if the same kind of check could be performed to see if the browser supports the Gecko-specific <code>-moz-border-radius-*</code> properties and if so utilize them.</p> <p>The check for webkit support looks like this:</p> <pre><code>var webkitAvailable = false; try { webkitAvailable = (document.defaultView.getComputedStyle(this[0], null)['-webkit-border-radius'] != undefined); } catch(err) {} </code></pre> <p>That, however, did not work for <code>-moz-border-radius</code> so I started checking for alternatives.</p> <p>My fallback solution is of course to use browser detection but that's far from recommended practice ofcourse.</p> <p>My best solution yet is as follows.</p> <pre><code>var mozborderAvailable = false; try { var o = jQuery('&lt;div&gt;').css('-moz-border-radius', '1px'); mozborderAvailable = $(o).css('-moz-border-radius-topleft') == '1px'; o = null; } catch(err) {} </code></pre> <p>It's based on the theory that Gecko "expands" the composite -moz-border-radius to the four sub-properties</p> <ul> <li><code>-moz-border-radius-topleft</code></li> <li><code>-moz-border-radius-topright</code></li> <li><code>-moz-border-radius-bottomleft</code></li> <li><code>-moz-border-radius-bottomright</code></li> </ul> <p>Is there any javascript/CSS guru out there that have a better solution?</p> <p>(The feature request for this page is at <a href="http://plugins.jquery.com/node/3619" rel="nofollow noreferrer">http://plugins.jquery.com/node/3619</a>)</p>
[ { "answer_id": 19080, "author": "M. Dave Auayan", "author_id": 2007, "author_profile": "https://Stackoverflow.com/users/2007", "pm_score": 2, "selected": false, "text": "<p>Why not use <code>-moz-border-radius</code> and <code>-webkit-border-radius</code> in the stylesheet? It's valid CS...
2008/08/20
[ "https://Stackoverflow.com/questions/18077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2114/" ]
I wanted some of those spiffy rounded corners for a web project that I'm currently working on. I thought I'd try to accomplish it using javascript and not CSS in an effort to keep the requests for image files to a minimum (yes, I know that it's possible to combine all required rounded corner shapes into one image) and I also wanted to be able to change the background color pretty much on the fly. I already utilize jQuery so I looked at the excellent [rounded corners plugin](http://plugins.jquery.com/project/corners) and it worked like a charm in every browser I tried. Being a developer however I noticed the opportunity to make it a bit more efficient. The script already includes code for detecting if the current browser supports webkit rounded corners (safari based browsers). If so it uses raw CSS instead of creating layers of divs. I thought that it would be awesome if the same kind of check could be performed to see if the browser supports the Gecko-specific `-moz-border-radius-*` properties and if so utilize them. The check for webkit support looks like this: ``` var webkitAvailable = false; try { webkitAvailable = (document.defaultView.getComputedStyle(this[0], null)['-webkit-border-radius'] != undefined); } catch(err) {} ``` That, however, did not work for `-moz-border-radius` so I started checking for alternatives. My fallback solution is of course to use browser detection but that's far from recommended practice ofcourse. My best solution yet is as follows. ``` var mozborderAvailable = false; try { var o = jQuery('<div>').css('-moz-border-radius', '1px'); mozborderAvailable = $(o).css('-moz-border-radius-topleft') == '1px'; o = null; } catch(err) {} ``` It's based on the theory that Gecko "expands" the composite -moz-border-radius to the four sub-properties * `-moz-border-radius-topleft` * `-moz-border-radius-topright` * `-moz-border-radius-bottomleft` * `-moz-border-radius-bottomright` Is there any javascript/CSS guru out there that have a better solution? (The feature request for this page is at <http://plugins.jquery.com/node/3619>)
How about this? ``` var mozborderAvailable = false; try { if (typeof(document.body.style.MozBorderRadius) !== "undefined") { mozborderAvailable = true; } } catch(err) {} ``` I tested it in Firefox 3 (true) and false in: Safari, IE7, and Opera. (Edit: better undefined test)
18,082
<p>What's the cleanest, most effective way to validate decimal numbers in JavaScript?</p> <p>Bonus points for:</p> <ol> <li>Clarity. Solution should be clean and simple.</li> <li>Cross-platform.</li> </ol> <p>Test cases:</p> <pre><code>01. IsNumeric('-1') =&gt; true 02. IsNumeric('-1.5') =&gt; true 03. IsNumeric('0') =&gt; true 04. IsNumeric('0.42') =&gt; true 05. IsNumeric('.42') =&gt; true 06. IsNumeric('99,999') =&gt; false 07. IsNumeric('0x89f') =&gt; false 08. IsNumeric('#abcdef') =&gt; false 09. IsNumeric('1.2.3') =&gt; false 10. IsNumeric('') =&gt; false 11. IsNumeric('blah') =&gt; false </code></pre>
[ { "answer_id": 18085, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 6, "selected": false, "text": "<p>This way seems to work well:</p>\n\n<pre><code>function IsNumeric(input){\n var RE = /^-{0,1}\\d*\\.{0,1}\\d+$/;\n ...
2008/08/20
[ "https://Stackoverflow.com/questions/18082", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29/" ]
What's the cleanest, most effective way to validate decimal numbers in JavaScript? Bonus points for: 1. Clarity. Solution should be clean and simple. 2. Cross-platform. Test cases: ``` 01. IsNumeric('-1') => true 02. IsNumeric('-1.5') => true 03. IsNumeric('0') => true 04. IsNumeric('0.42') => true 05. IsNumeric('.42') => true 06. IsNumeric('99,999') => false 07. IsNumeric('0x89f') => false 08. IsNumeric('#abcdef') => false 09. IsNumeric('1.2.3') => false 10. IsNumeric('') => false 11. IsNumeric('blah') => false ```
[@Joel's answer](https://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric/174921#174921) is pretty close, but it will fail in the following cases: ``` // Whitespace strings: IsNumeric(' ') == true; IsNumeric('\t\t') == true; IsNumeric('\n\r') == true; // Number literals: IsNumeric(-1) == false; IsNumeric(0) == false; IsNumeric(1.1) == false; IsNumeric(8e5) == false; ``` Some time ago I had to implement an `IsNumeric` function, to find out if a variable contained a numeric value, **regardless of its type**, it could be a `String` containing a numeric value (I had to consider also exponential notation, etc.), a `Number` object, virtually anything could be passed to that function, I couldn't make any type assumptions, taking care of type coercion (eg. `+true == 1;` but `true` shouldn't be considered as `"numeric"`). I think is worth sharing this set of [**+30 unit tests**](http://run.plnkr.co/plunks/93FPpacuIcXqqKMecLdk/) made to numerous function implementations, and also share the one that passes all my tests: ``` function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } ``` **P.S.** [isNaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN) & [isFinite](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite) have a confusing behavior due to forced conversion to number. In ES6, [Number.isNaN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN) & [Number.isFinite](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isFinite) would fix these issues. Keep that in mind when using them. --- **Update** : [Here's how jQuery does it now (2.2-stable)](https://github.com/jquery/jquery/blob/2.2-stable/src/core.js#L215): ``` isNumeric: function(obj) { var realStringObj = obj && obj.toString(); return !jQuery.isArray(obj) && (realStringObj - parseFloat(realStringObj) + 1) >= 0; } ``` **Update** : [Angular 4.3](https://github.com/angular/angular/blob/4.3.x/packages/common/src/pipes/number_pipe.ts#L172): ``` export function isNumeric(value: any): boolean { return !isNaN(value - parseFloat(value)); } ```
18,097
<p>In C#, if I have an inherited class with a default constructor, do I have to explicitly call the base class' constructor or will it be implicitly called?</p> <pre><code>class BaseClass { public BaseClass() { // ... some code } } class MyClass : BaseClass { public MyClass() // Do I need to put ": base()" here or is it implied? { // ... some code } } </code></pre>
[ { "answer_id": 18100, "author": "Lars Mæhlum", "author_id": 960, "author_profile": "https://Stackoverflow.com/users/960", "pm_score": 0, "selected": false, "text": "<p>AFAIK, you only need to call the base constructor if you need to pass down any values to it.</p>\n" }, { "answer...
2008/08/20
[ "https://Stackoverflow.com/questions/18097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
In C#, if I have an inherited class with a default constructor, do I have to explicitly call the base class' constructor or will it be implicitly called? ``` class BaseClass { public BaseClass() { // ... some code } } class MyClass : BaseClass { public MyClass() // Do I need to put ": base()" here or is it implied? { // ... some code } } ```
You do not need to explicitly call the base constructor, it will be implicitly called. Extend your example a little and create a Console Application and you can verify this behaviour for yourself: ``` using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { MyClass foo = new MyClass(); Console.ReadLine(); } } class BaseClass { public BaseClass() { Console.WriteLine("BaseClass constructor called."); } } class MyClass : BaseClass { public MyClass() { Console.WriteLine("MyClass constructor called."); } } } ```
18,166
<p>I am attempting to POST against a vendor's server using PHP 5.2 with cURL. I'm reading in an XML document to post against their server and then reading in a response:</p> <pre><code>$request = trim(file_get_contents('test.xml')); $curlHandle = curl_init($servletURL); curl_setopt($curlHandle, CURLOPT_POST, TRUE); curl_setopt($curlHandle, CURLOPT_POSTFIELDS, array('XML'=&gt;$request)); curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($curlHandle, CURLOPT_HEADER, FALSE); # Have also tried leaving this out $response = curl_exec($curlHandle); </code></pre> <p>That code, in an of itself, works OK, but the other server returns a response from it's XML parser stating:</p> <blockquote> <p>Content not allowed in prolog</p> </blockquote> <p>I looked that error up and this is normally caused by whitespace before the XML, but I made sure that the XML file itself has no whitespace and the trim() should clear that up anyway. I did a TCPDump on the connection while I ran the code and this is what is sent out:</p> <pre><code>POST {serverURL} HTTP/1.1 Host: {ip of server}:8080 Accept: */* Content-Length: 921 Expect: 100-continue Content-Type: multipart/form-data; boundry:---------------------------01e7cda3896f ---------------------------01e7cda3896f Content-Disposition: form-data; name="XML" [SNIP - the XML was displayed] ---------------------------01e7cda3896f-- </code></pre> <p>Before and after the [SNIP] line there is visible whitespace when I replay the session in Ethereal. Is this what is causing the problem and, if so, how can I remove it, or am I looking too far and this may be an issue with the server I'm posting against?</p>
[ { "answer_id": 18215, "author": "mercutio", "author_id": 1951, "author_profile": "https://Stackoverflow.com/users/1951", "pm_score": 2, "selected": false, "text": "<p>Not an answer, but I find the whole fopen/fread/fclose thing very dull to peruse when looking at code.</p>\n\n<p>You can ...
2008/08/20
[ "https://Stackoverflow.com/questions/18166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/204/" ]
I am attempting to POST against a vendor's server using PHP 5.2 with cURL. I'm reading in an XML document to post against their server and then reading in a response: ``` $request = trim(file_get_contents('test.xml')); $curlHandle = curl_init($servletURL); curl_setopt($curlHandle, CURLOPT_POST, TRUE); curl_setopt($curlHandle, CURLOPT_POSTFIELDS, array('XML'=>$request)); curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($curlHandle, CURLOPT_HEADER, FALSE); # Have also tried leaving this out $response = curl_exec($curlHandle); ``` That code, in an of itself, works OK, but the other server returns a response from it's XML parser stating: > > Content not allowed in prolog > > > I looked that error up and this is normally caused by whitespace before the XML, but I made sure that the XML file itself has no whitespace and the trim() should clear that up anyway. I did a TCPDump on the connection while I ran the code and this is what is sent out: ``` POST {serverURL} HTTP/1.1 Host: {ip of server}:8080 Accept: */* Content-Length: 921 Expect: 100-continue Content-Type: multipart/form-data; boundry:---------------------------01e7cda3896f ---------------------------01e7cda3896f Content-Disposition: form-data; name="XML" [SNIP - the XML was displayed] ---------------------------01e7cda3896f-- ``` Before and after the [SNIP] line there is visible whitespace when I replay the session in Ethereal. Is this what is causing the problem and, if so, how can I remove it, or am I looking too far and this may be an issue with the server I'm posting against?
It turns out it's an encoding issue. The app apparently needs the XML in www-form-urlencoded instead of form-data so I had to change: ``` # This sets the encoding to multipart/form-data curl_setopt($curlHandle, CURLOPT_POSTFIELDS, array('XML'=>$request)); ``` to ``` # This sets it to application/x-www-form-urlencoded curl_setopt($curlHandle, CURLOPT_POSTFIELDS, 'XML=' . urlencode($request)); ```
18,172
<p>I am looking for a robust way to copy files over a Windows network share that is tolerant of intermittent connectivity. The application is often used on wireless, mobile workstations in large hospitals, and I'm assuming connectivity can be lost either momentarily or for several minutes at a time. The files involved are typically about 200KB - 500KB in size. The application is written in VB6 (ugh), but we frequently end up using Windows DLL calls.</p> <p>Thanks!</p>
[ { "answer_id": 18178, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 3, "selected": false, "text": "<p>Try using BITS (Background Intelligent Transfer Service). It's the infrastructure that Windows Update uses, is acce...
2008/08/20
[ "https://Stackoverflow.com/questions/18172", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2144/" ]
I am looking for a robust way to copy files over a Windows network share that is tolerant of intermittent connectivity. The application is often used on wireless, mobile workstations in large hospitals, and I'm assuming connectivity can be lost either momentarily or for several minutes at a time. The files involved are typically about 200KB - 500KB in size. The application is written in VB6 (ugh), but we frequently end up using Windows DLL calls. Thanks!
I'm unclear as to what your actual problem is, so I'll throw out a few thoughts. * Do you want restartable copies (with such small file sizes, that doesn't seem like it'd be that big of a deal)? If so, look at [CopyFileEx with COPYFILERESTARTABLE](http://msdn.microsoft.com/en-us/library/aa363852.aspx) * Do you want verifiable copies? Sounds like you already have that by verifying hashes. * Do you want better performance? It's going to be tough, as it sounds like you can't run anything on the server. Otherwise, [TransmitFile](http://msdn.microsoft.com/en-us/library/ms740565%28VS.85%29.aspx) may help. * Do you just want a fire and forget operation? I suppose shelling out to robocopy, or [TeraCopy](http://www.codesector.com/teracopy.php) or something would work - but it seems a bit hacky to me. * Do you want to know when the network comes back? [IsNetworkAlive](http://msdn.microsoft.com/en-us/library/aa377522%28VS.85%29.aspx) has your answer. Based on what I know so far, I think the following pseudo-code would be my approach: ``` sourceFile = Compress("*.*"); destFile = "X:\files.zip"; int copyFlags = COPYFILEFAILIFEXISTS | COPYFILERESTARTABLE; while (CopyFileEx(sourceFile, destFile, null, null, false, copyFlags) == 0) { do { // optionally, increment a failed counter to break out at some point Sleep(1000); while (!IsNetworkAlive(NETWORKALIVELAN)); } ``` Compressing the files first saves you the tracking of which files you've successfully copied, and which you need to restart. It should also make the copy go faster (smaller total file size, and larger single file size), at the expense of some CPU power on both sides. A simple batch file can decompress it on the server side.
18,216
<p>I'm not quite sure if this is possible, or falls into the category of pivot tables, but I figured I'd go to the pros to see.</p> <p>I have three basic tables: Card, Property, and CardProperty. Since cards do not have the same properties, and often multiple values for the same property, I decided to use the union table approach to store data instead of having a really big column structure in my card table.</p> <p>The property table is a basic keyword/value type table. So you have the keyword ATK and the value assigned to it. There is another property called SpecialType which a card can have multiple values for, such as "Sycnro" and "DARK"</p> <p>What I'd like to do is create a view or stored procedure that gives me the Card Id, Card Name, and all the property keywords assigned to the card as columns and their values in the ResultSet for a card specified. So ideally I'd have a result set like:</p> <pre><code>ID NAME SPECIALTYPE 1 Red Dragon Archfiend Synchro 1 Red Dragon Archfiend DARK 1 Red Dragon Archfiend Effect </code></pre> <p>and I could tally my results that way.</p> <p>I guess even slicker would be to simply concatenate the properties together based on their keyword, so I could generate a ResultSet like:</p> <pre><code>1 Red Dragon Archfiend Synchro/DARK/Effect </code></pre> <p>..but I don't know if that's feasible.</p> <p>Help me stackoverflow Kenobi! You're my only hope.</p>
[ { "answer_id": 18236, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Don't collapse by concatenation for storage of related records in your database. Its not exactly best practices. </p>\n\n<...
2008/08/20
[ "https://Stackoverflow.com/questions/18216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/71/" ]
I'm not quite sure if this is possible, or falls into the category of pivot tables, but I figured I'd go to the pros to see. I have three basic tables: Card, Property, and CardProperty. Since cards do not have the same properties, and often multiple values for the same property, I decided to use the union table approach to store data instead of having a really big column structure in my card table. The property table is a basic keyword/value type table. So you have the keyword ATK and the value assigned to it. There is another property called SpecialType which a card can have multiple values for, such as "Sycnro" and "DARK" What I'd like to do is create a view or stored procedure that gives me the Card Id, Card Name, and all the property keywords assigned to the card as columns and their values in the ResultSet for a card specified. So ideally I'd have a result set like: ``` ID NAME SPECIALTYPE 1 Red Dragon Archfiend Synchro 1 Red Dragon Archfiend DARK 1 Red Dragon Archfiend Effect ``` and I could tally my results that way. I guess even slicker would be to simply concatenate the properties together based on their keyword, so I could generate a ResultSet like: ``` 1 Red Dragon Archfiend Synchro/DARK/Effect ``` ..but I don't know if that's feasible. Help me stackoverflow Kenobi! You're my only hope.
Is this for SQL server? If yes then [Concatenate Values From Multiple Rows Into One Column (2000)](http://wiki.lessthandot.com/index.php/Concatenate_Values_From_Multiple_Rows_Into_One_Column) [Concatenate Values From Multiple Rows Into One Column Ordered (2005+)](http://wiki.lessthandot.com/index.php/Concatenate_Values_From_Multiple_Rows_Into_One_Column_Ordered)
18,223
<p>I have a table in a SQL Server 2005 database with a trigger that is supposed to add a record to a different table whenever a new record is inserted. It seems to work fine, but if I execute an Insert Into on the master table that uses a subquery as the source of the values, the trigger only inserts one record in the other table, even though multiple records were added to the master. I want the trigger to fire for each new record added to the master table. Is that possible in 2005?</p> <p>The insert I'm doing is:</p> <pre><code>INSERT INTO [tblMenuItems] ([ID], [MenuID], [SortOrder], [ItemReference], [MenuReference], [ConcurrencyID]) SELECT [ID], [MenuID], [SortOrder], [ItemReference], [MenuReference], [ConcurrencyID] FROM [IVEEtblMenuItems] </code></pre> <p>Here is what the trigger looks like:</p> <pre><code>CREATE TRIGGER [dbo].[tblMenuItemInsertSecurity] ON [dbo].[tblMenuItems] FOR INSERT AS Declare @iRoleID int Declare @iMenuItemID int Select @iMenuItemID = [ID] from Inserted DECLARE tblUserRoles CURSOR FASTFORWARD FOR SELECT [ID] from tblUserRoles OPEN tblUserRoles FETCH NEXT FROM tblUserRoles INTO @iRoleID WHILE (@@FetchStatus = 0) BEGIN INSERT INTO tblRestrictedMenuItems( [RoleID], [MenuItemID], [RestrictLevel]) VALUES( @iRoleID, @iMenuItemID, 1) FETCH NEXT FROM tblUserRoles INTO @iRoleID END CLOSE tblUserRoles Deallocate tblUserRoles </code></pre>
[ { "answer_id": 18229, "author": "Andrew Rimmer", "author_id": 1982, "author_profile": "https://Stackoverflow.com/users/1982", "pm_score": 3, "selected": true, "text": "<p>Your trigger is only using the first row from 'Inserted'. This is a common misunderstanding when dealing with SQL tri...
2008/08/20
[ "https://Stackoverflow.com/questions/18223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/741/" ]
I have a table in a SQL Server 2005 database with a trigger that is supposed to add a record to a different table whenever a new record is inserted. It seems to work fine, but if I execute an Insert Into on the master table that uses a subquery as the source of the values, the trigger only inserts one record in the other table, even though multiple records were added to the master. I want the trigger to fire for each new record added to the master table. Is that possible in 2005? The insert I'm doing is: ``` INSERT INTO [tblMenuItems] ([ID], [MenuID], [SortOrder], [ItemReference], [MenuReference], [ConcurrencyID]) SELECT [ID], [MenuID], [SortOrder], [ItemReference], [MenuReference], [ConcurrencyID] FROM [IVEEtblMenuItems] ``` Here is what the trigger looks like: ``` CREATE TRIGGER [dbo].[tblMenuItemInsertSecurity] ON [dbo].[tblMenuItems] FOR INSERT AS Declare @iRoleID int Declare @iMenuItemID int Select @iMenuItemID = [ID] from Inserted DECLARE tblUserRoles CURSOR FASTFORWARD FOR SELECT [ID] from tblUserRoles OPEN tblUserRoles FETCH NEXT FROM tblUserRoles INTO @iRoleID WHILE (@@FetchStatus = 0) BEGIN INSERT INTO tblRestrictedMenuItems( [RoleID], [MenuItemID], [RestrictLevel]) VALUES( @iRoleID, @iMenuItemID, 1) FETCH NEXT FROM tblUserRoles INTO @iRoleID END CLOSE tblUserRoles Deallocate tblUserRoles ```
Your trigger is only using the first row from 'Inserted'. This is a common misunderstanding when dealing with SQL triggers for the first time. The trigger fires per update not per row. For example if you do the following:- update products set title = 'geoff de geoff' this would update all the products, but a trigger on the product table would only fire once. The Inserted 'table' you get in trigger would contain all the rows. You must either loop through Inserted with a cursor, or better join Inserted to the table you are updating.
18,265
<p>What methods are there for automatically getting a stack trace on Unix systems? I don't mean just getting a core file or attaching interactively with GDB, but having a SIGSEGV handler that dumps a backtrace to a text file. </p> <p>Bonus points for the following optional features:</p> <ul> <li>Extra information gathering at crash time (eg. config files).</li> <li>Email a crash info bundle to the developers.</li> <li>Ability to add this in a <code>dlopen</code>ed shared library</li> <li>Not requiring a GUI</li> </ul>
[ { "answer_id": 18406, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 4, "selected": true, "text": "<p>If you are on systems with the BSD <a href=\"http://linux.die.net/man/3/backtrace\" rel=\"nofollow noreferrer\"><code>back...
2008/08/20
[ "https://Stackoverflow.com/questions/18265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/954/" ]
What methods are there for automatically getting a stack trace on Unix systems? I don't mean just getting a core file or attaching interactively with GDB, but having a SIGSEGV handler that dumps a backtrace to a text file. Bonus points for the following optional features: * Extra information gathering at crash time (eg. config files). * Email a crash info bundle to the developers. * Ability to add this in a `dlopen`ed shared library * Not requiring a GUI
If you are on systems with the BSD [`backtrace`](http://linux.die.net/man/3/backtrace) functionality available (Linux, OSX 1.5, BSD of course), you can do this programmatically in your signal handler. For example ([`backtrace` code derived from IBM example](http://www-128.ibm.com/developerworks/linux/library/l-cppexcep.html?ca=dgr-lnxw07ExceptionTricks)): ```c #include <execinfo.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> void sig_handler(int sig) { void * array[25]; int nSize = backtrace(array, 25); char ** symbols = backtrace_symbols(array, nSize); for (int i = 0; i < nSize; i++) { puts(symbols[i]);; } free(symbols); signal(sig, &sig_handler); } void h() { kill(0, SIGSEGV); } void g() { h(); } void f() { g(); } int main(int argc, char ** argv) { signal(SIGSEGV, &sig_handler); f(); } ``` Output: ``` 0 a.out 0x00001f2d sig_handler + 35 1 libSystem.B.dylib 0x95f8f09b _sigtramp + 43 2 ??? 0xffffffff 0x0 + 4294967295 3 a.out 0x00001fb1 h + 26 4 a.out 0x00001fbe g + 11 5 a.out 0x00001fcb f + 11 6 a.out 0x00001ff5 main + 40 7 a.out 0x00001ede start + 54 ``` This doesn't get bonus points for the optional features (except not requiring a GUI), however, it does have the advantage of being very simple, and not requiring any additional libraries or programs.
18,407
<p>If I have a variable in C# that needs to be checked to determine if it is equal to one of a set of variables, what is the best way to do this?</p> <p>I'm not looking for a solution that stores the set in an array. I'm more curious to see if there is a solution that uses boolean logic in some way to get the answer.</p> <p>I know I could do something like this: </p> <pre><code>int baseCase = 5; bool testResult = baseCase == 3 || baseCase == 7 || baseCase == 12 || baseCase == 5; </code></pre> <p>I'm curious to see if I could do something more like this:</p> <pre><code>int baseCase = 5; bool testResult = baseCase == (3 | 7 | 12 | 5); </code></pre> <p>Obviously the above won't work, but I'm interested in seeing if there is something more succinct than my first example, which has to repeat the same variable over and over again for each test value.</p> <p><strong>UPDATE:</strong><br> I decided to accept CoreyN's answer as it seems like the most simple approach. It's practical, and still simple for a novice to understand, I think.</p> <p>Unfortunately where I work our system uses the .NET 2.0 framework and there's no chance of upgrading any time soon. Are there any other solutions out there that don't rely on the .NET 3.5 framework, besides the most obvious one I can think of: </p> <pre><code>new List&lt;int&gt;(new int[] { 3, 6, 7, 1 }).Contains(5); </code></pre>
[ { "answer_id": 18416, "author": "Corey", "author_id": 1595, "author_profile": "https://Stackoverflow.com/users/1595", "pm_score": 5, "selected": true, "text": "<pre><code> bool b = new int[] { 3,7,12,5 }.Contains(5);\n</code></pre>\n" }, { "answer_id": 18423, "author":...
2008/08/20
[ "https://Stackoverflow.com/questions/18407", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
If I have a variable in C# that needs to be checked to determine if it is equal to one of a set of variables, what is the best way to do this? I'm not looking for a solution that stores the set in an array. I'm more curious to see if there is a solution that uses boolean logic in some way to get the answer. I know I could do something like this: ``` int baseCase = 5; bool testResult = baseCase == 3 || baseCase == 7 || baseCase == 12 || baseCase == 5; ``` I'm curious to see if I could do something more like this: ``` int baseCase = 5; bool testResult = baseCase == (3 | 7 | 12 | 5); ``` Obviously the above won't work, but I'm interested in seeing if there is something more succinct than my first example, which has to repeat the same variable over and over again for each test value. **UPDATE:** I decided to accept CoreyN's answer as it seems like the most simple approach. It's practical, and still simple for a novice to understand, I think. Unfortunately where I work our system uses the .NET 2.0 framework and there's no chance of upgrading any time soon. Are there any other solutions out there that don't rely on the .NET 3.5 framework, besides the most obvious one I can think of: ``` new List<int>(new int[] { 3, 6, 7, 1 }).Contains(5); ```
``` bool b = new int[] { 3,7,12,5 }.Contains(5); ```
18,413
<p>I have a column of data that contains a percentage range as a string that I'd like to convert to a number so I can do easy comparisons.</p> <p>Possible values in the string:</p> <pre><code>'&lt;5%' '5-10%' '10-15%' ... '95-100%' </code></pre> <p>I'd like to convert this in my select where clause to just the first number, 5, 10, 15, etc. so that I can compare that value to a passed in "at least this" value.</p> <p>I've tried a bunch of variations on substring, charindex, convert, and replace, but I still can't seem to get something that works in all combinations.</p> <p>Any ideas?</p>
[ { "answer_id": 18437, "author": "Shazburg", "author_id": 2165, "author_profile": "https://Stackoverflow.com/users/2165", "pm_score": 0, "selected": false, "text": "<p>You can convert char data to other types of char (convert char(10) to varchar(10)), but you won't be able to convert char...
2008/08/20
[ "https://Stackoverflow.com/questions/18413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1097/" ]
I have a column of data that contains a percentage range as a string that I'd like to convert to a number so I can do easy comparisons. Possible values in the string: ``` '<5%' '5-10%' '10-15%' ... '95-100%' ``` I'd like to convert this in my select where clause to just the first number, 5, 10, 15, etc. so that I can compare that value to a passed in "at least this" value. I've tried a bunch of variations on substring, charindex, convert, and replace, but I still can't seem to get something that works in all combinations. Any ideas?
Try this, ``` SELECT substring(replace(interest , '<',''), patindex('%[0-9]%',replace(interest , '<','')), patindex('%[^0-9]%',replace(interest, '<',''))-1) FROM table1 ``` Tested at my end and it works, it's only my first try so you might be able to optimise it.
18,418
<p>When I am writing code in Python, I often need to remove items from a list or other sequence type based on some criteria. I haven't found a solution that is elegant and efficient, as removing items from a list you are currently iterating through is bad. For example, you can't do this:</p> <pre><code>for name in names: if name[-5:] == 'Smith': names.remove(name) </code></pre> <p>I usually end up doing something like this:</p> <pre><code>toremove = [] for name in names: if name[-5:] == 'Smith': toremove.append(name) for name in toremove: names.remove(name) del toremove </code></pre> <p>This is innefficient, fairly ugly and possibly buggy (how does it handle multiple 'John Smith' entries?). Does anyone have a more elegant solution, or at least a more efficient one? </p> <p>How about one that works with dictionaries?</p>
[ { "answer_id": 18424, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": -1, "selected": false, "text": "<p>Well, this is clearly an issue with the data structure you are using. Use a hashtable for example. Some implementations s...
2008/08/20
[ "https://Stackoverflow.com/questions/18418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1892/" ]
When I am writing code in Python, I often need to remove items from a list or other sequence type based on some criteria. I haven't found a solution that is elegant and efficient, as removing items from a list you are currently iterating through is bad. For example, you can't do this: ``` for name in names: if name[-5:] == 'Smith': names.remove(name) ``` I usually end up doing something like this: ``` toremove = [] for name in names: if name[-5:] == 'Smith': toremove.append(name) for name in toremove: names.remove(name) del toremove ``` This is innefficient, fairly ugly and possibly buggy (how does it handle multiple 'John Smith' entries?). Does anyone have a more elegant solution, or at least a more efficient one? How about one that works with dictionaries?
Two easy ways to accomplish just the filtering are: 1. Using `filter`: `names = filter(lambda name: name[-5:] != "Smith", names)` 2. Using list comprehensions: `names = [name for name in names if name[-5:] != "Smith"]` Note that both cases keep the values for which the predicate function evaluates to `True`, so you have to reverse the logic (i.e. you say "keep the people who do not have the last name Smith" instead of "remove the people who have the last name Smith"). **Edit** Funny... two people individually posted both of the answers I suggested as I was posting mine.
18,419
<p>I've got a combo-box that sits inside of a panel in Flex 3. Basically I want to fade the panel using a Fade effect in ActionScript. I can get the fade to work fine, however the label of the combo-box does not fade. I had this same issue with buttons and found that their fonts needed to be embedded. No problem. I embedded the font that I was using and the buttons' labels faded correctly. I've tried a similar approach to the combo-box, but it does not fade the selected item label.</p> <p>Here is what I've done so far: Embed code for the font at the top of my MXML in script:</p> <pre><code>[Embed("assets/trebuc.ttf", fontName="TrebuchetMS")] public var trebuchetMSFont:Class; </code></pre> <p>In my init function</p> <pre><code>//register the font. Font.registerFont(trebuchetMSFont); </code></pre> <p>The combobox's mxml:</p> <pre><code>&lt;mx:ComboBox id="FilterFields" styleName="FilterDropdown" left="10" right="10" top="10" fontSize="14"&gt; &lt;mx:itemRenderer&gt; &lt;mx:Component&gt; &lt;mx:Label fontSize="10" /&gt; &lt;/mx:Component&gt; &lt;/mx:itemRenderer&gt; &lt;/mx:ComboBox&gt; </code></pre> <p>And a style that I wrote to get the fonts applied to the combo-box:</p> <pre><code>.FilterDropdown { embedFonts: true; fontFamily: TrebuchetMS; fontWeight: normal; fontSize: 12; } </code></pre> <p>The reason I had to write a style instead of placing it in the "FontFamily" attribute was that the style made all the text on the combo-box the correct font where the "FontFamily" attribute only made the items in the drop-down use the correct font. ­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 18463, "author": "Matt MacLean", "author_id": 22, "author_profile": "https://Stackoverflow.com/users/22", "pm_score": 2, "selected": false, "text": "<p>Hmm, I am not sure why that isn't working for you. Here is an example of how I got it to work:</p>\n\n<pre><code>&lt;?xml...
2008/08/20
[ "https://Stackoverflow.com/questions/18419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1290/" ]
I've got a combo-box that sits inside of a panel in Flex 3. Basically I want to fade the panel using a Fade effect in ActionScript. I can get the fade to work fine, however the label of the combo-box does not fade. I had this same issue with buttons and found that their fonts needed to be embedded. No problem. I embedded the font that I was using and the buttons' labels faded correctly. I've tried a similar approach to the combo-box, but it does not fade the selected item label. Here is what I've done so far: Embed code for the font at the top of my MXML in script: ``` [Embed("assets/trebuc.ttf", fontName="TrebuchetMS")] public var trebuchetMSFont:Class; ``` In my init function ``` //register the font. Font.registerFont(trebuchetMSFont); ``` The combobox's mxml: ``` <mx:ComboBox id="FilterFields" styleName="FilterDropdown" left="10" right="10" top="10" fontSize="14"> <mx:itemRenderer> <mx:Component> <mx:Label fontSize="10" /> </mx:Component> </mx:itemRenderer> </mx:ComboBox> ``` And a style that I wrote to get the fonts applied to the combo-box: ``` .FilterDropdown { embedFonts: true; fontFamily: TrebuchetMS; fontWeight: normal; fontSize: 12; } ``` The reason I had to write a style instead of placing it in the "FontFamily" attribute was that the style made all the text on the combo-box the correct font where the "FontFamily" attribute only made the items in the drop-down use the correct font. ­­­­­­­­­­­­­­­­­­­­­­­­­
Hmm, I am not sure why that isn't working for you. Here is an example of how I got it to work: ``` <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="fx.play([panel])"> <mx:Style> @font-face { src: local("Arial"); fontFamily: ArialEm; } @font-face { src: local("Arial"); fontFamily: ArialEm; fontWeight: bold; } @font-face { src: local("Arial"); fontFamily: ArialEm; font-style: italic; } </mx:Style> <mx:XML id="items" xmlns=""> <items> <item label="Item 1" /> <item label="Item 2" /> <item label="Item 3" /> </items> </mx:XML> <mx:Panel id="panel" x="10" y="10" width="250" height="200" layout="absolute"> <mx:ComboBox fontFamily="ArialEm" x="35" y="10" dataProvider="{items.item}" labelField="@label"></mx:ComboBox> </mx:Panel> <mx:Fade id="fx" alphaFrom="0" alphaTo="1" duration="5000" /> </mx:Application> ``` Hope this helps you out.
18,449
<p>For those of us who use standard shared hosting packages, such as GoDaddy or Network Solutions, how do you handle datetime conversions when your hosting server (PHP) and MySQL server are in different time zones?</p> <p>Also, does anybody have some best practice advice for determining what time zone a visitor to your site is in and manipulating a datetime variable appropriately?</p>
[ { "answer_id": 18602, "author": "Joel Meador", "author_id": 1976, "author_profile": "https://Stackoverflow.com/users/1976", "pm_score": 4, "selected": false, "text": "<p>Store everything as UTC. You can do conversions at the client level, or on the server side using client settings.</p>...
2008/08/20
[ "https://Stackoverflow.com/questions/18449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2056/" ]
For those of us who use standard shared hosting packages, such as GoDaddy or Network Solutions, how do you handle datetime conversions when your hosting server (PHP) and MySQL server are in different time zones? Also, does anybody have some best practice advice for determining what time zone a visitor to your site is in and manipulating a datetime variable appropriately?
As of PHP 5.1.0 you can use [*date\_default\_timezone\_set()*](http://www.php.net/manual/en/function.date-default-timezone-set.php) function to set the default timezone used by all date/time functions in a script. For MySql (quoted from [MySQL Server Time Zone Support](http://dev.mysql.com/doc/refman/4.1/en/time-zone-support.html) page) > > Before MySQL 4.1.3, the server operates only in the system time zone set at startup. Beginning with MySQL 4.1.3, the server maintains several time zone settings, some of which can be modified at runtime. > > > Of interest to you is per-connection setting of the time zones, which you would use at the beginning of your scripts ``` SET timezone = 'Europe/London'; ``` As for detecting the client timezone setting, you could use a bit of JavaScript to get and save that information to a cookie, and use it on subsequent page reads, to calculate the proper timezone. ``` //Returns the offset (time difference) between Greenwich Mean Time (GMT) //and local time of Date object, in minutes. var offset = new Date().getTimezoneOffset(); document.cookie = 'timezoneOffset=' + escape(offset); ``` Or you could offer users the chioce to set their time zones themselves.
18,460
<p>What is the best way to authorize all users to one single page in a asp.net website.</p> <p>For except the login page and one other page, I deny all users from viewing pages in the website. </p> <p>How do you make this page accessible to all users?</p>
[ { "answer_id": 18469, "author": "Dillie-O", "author_id": 71, "author_profile": "https://Stackoverflow.com/users/71", "pm_score": 4, "selected": true, "text": "<p>I've been using forms authentication and creating the necessary GenericIdentity and CustomPrincipal objects that allows me to ...
2008/08/20
[ "https://Stackoverflow.com/questions/18460", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2172/" ]
What is the best way to authorize all users to one single page in a asp.net website. For except the login page and one other page, I deny all users from viewing pages in the website. How do you make this page accessible to all users?
I've been using forms authentication and creating the necessary GenericIdentity and CustomPrincipal objects that allows me to leverage the User.IsInRole type functions you typically only get with Windows authentication. That way in my web.config file, I can do stuff like... ``` <location path="Login.aspx"> <system.web> <authorization> <allow users ="*" /> </authorization> </system.web> </location> <location path="ManagementFolder"> <system.web> <authorization> <allow roles ="Administrator, Manager" /> </authorization> </system.web> </location> ```
18,465
<p>In .Net you can read a string value into another data type using either <code>&lt;datatype&gt;.parse</code> or <code>Convert.To&lt;DataType&gt;</code>. </p> <p>I'm not familiar with the fundamentals of parse versus convert so I am always at a loss when asked which one is better/faster/more appropriate. </p> <p>So - which way is best in what type of circumstances?</p>
[ { "answer_id": 18474, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 3, "selected": false, "text": "<p>Here's an answer for you:</p>\n\n<p><a href=\"http://www.dotnetspider.com/forum/ViewForum.aspx?ForumId=77428\" rel=...
2008/08/20
[ "https://Stackoverflow.com/questions/18465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/149/" ]
In .Net you can read a string value into another data type using either `<datatype>.parse` or `Convert.To<DataType>`. I'm not familiar with the fundamentals of parse versus convert so I am always at a loss when asked which one is better/faster/more appropriate. So - which way is best in what type of circumstances?
The `Convert.ToXXX()` methods are for objects that might be of the correct or similar type, while `.Parse()` and `.TryParse()` are specifically for strings: ``` //o is actually a boxed int object o = 12345; //unboxes it int castVal = (int) 12345; //o is a boxed enum object o = MyEnum.ValueA; //this will get the underlying int of ValueA int convVal = Convert.ToInt32( o ); //now we have a string string s = "12345"; //this will throw an exception if s can't be parsed int parseVal = int.Parse( s ); //alternatively: int tryVal; if( int.TryParse( s, out tryVal ) ) { //do something with tryVal } ``` If you compile with optimisation flags TryParse is very quick - it's the best way to get a number from a string. However if you have an object that might be an int or might be a string Convert.ToInt32 is quicker.
18,524
<p>I have a list of integers, <code>List&lt;Integer&gt;</code> and I'd like to convert all the integer objects into Strings, thus finishing up with a new <code>List&lt;String&gt;</code>.</p> <p>Naturally, I could create a new <code>List&lt;String&gt;</code> and loop through the list calling <code>String.valueOf()</code> for each integer, but I was wondering if there was a better (read: <em>more automatic</em>) way of doing it?</p>
[ { "answer_id": 18529, "author": "jsight", "author_id": 1432, "author_profile": "https://Stackoverflow.com/users/1432", "pm_score": 7, "selected": true, "text": "<p>As far as I know, iterate and instantiate is the only way to do this. Something like (for others potential help, since I'm ...
2008/08/20
[ "https://Stackoverflow.com/questions/18524", "https://Stackoverflow.com", "https://Stackoverflow.com/users/916/" ]
I have a list of integers, `List<Integer>` and I'd like to convert all the integer objects into Strings, thus finishing up with a new `List<String>`. Naturally, I could create a new `List<String>` and loop through the list calling `String.valueOf()` for each integer, but I was wondering if there was a better (read: *more automatic*) way of doing it?
As far as I know, iterate and instantiate is the only way to do this. Something like (for others potential help, since I'm sure you know how to do this): ``` List<Integer> oldList = ... /* Specify the size of the list up front to prevent resizing. */ List<String> newList = new ArrayList<>(oldList.size()); for (Integer myInt : oldList) { newList.add(String.valueOf(myInt)); } ```
18,538
<p>I'd like some sorthand for this:</p> <pre><code>Map rowToMap(row) { def rowMap = [:]; row.columns.each{ rowMap[it.name] = it.val } return rowMap; } </code></pre> <p>given the way the GDK stuff is, I'd expect to be able to do something like:</p> <pre><code>Map rowToMap(row) { row.columns.collectMap{ [it.name,it.val] } } </code></pre> <p>but I haven't seen anything in the docs... am I missing something? or am I just way too lazy?</p>
[ { "answer_id": 18981, "author": "danb", "author_id": 2031, "author_profile": "https://Stackoverflow.com/users/2031", "pm_score": 1, "selected": false, "text": "<p>I can't find anything built in... but using the ExpandoMetaClass I can do this: </p>\n\n<pre><code>ArrayList.metaClass.collec...
2008/08/20
[ "https://Stackoverflow.com/questions/18538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031/" ]
I'd like some sorthand for this: ``` Map rowToMap(row) { def rowMap = [:]; row.columns.each{ rowMap[it.name] = it.val } return rowMap; } ``` given the way the GDK stuff is, I'd expect to be able to do something like: ``` Map rowToMap(row) { row.columns.collectMap{ [it.name,it.val] } } ``` but I haven't seen anything in the docs... am I missing something? or am I just way too lazy?
I've recently came across the need to do exactly that: converting a list into a map. This question was posted before Groovy version 1.7.9 came out, so the method [`collectEntries`](http://docs.groovy-lang.org/latest/html/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html#collectEntries(java.lang.Iterable,%20groovy.lang.Closure)) didn't exist yet. It works exactly as the `collectMap` method [that was proposed](https://stackoverflow.com/questions/18538/shortcut-for-creating-a-map-from-a-list-in-groovy/19077#19077): ``` Map rowToMap(row) { row.columns.collectEntries{[it.name, it.val]} } ``` If for some reason you are stuck with an older Groovy version, the [`inject`](http://docs.groovy-lang.org/latest/html/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html#inject(java.lang.Object,%20groovy.lang.Closure)) method can also be used (as proposed [here](https://stackoverflow.com/questions/18538/shortcut-for-creating-a-map-from-a-list-in-groovy/198614#198614)). This is a slightly modified version that takes only one expression inside the closure (just for the sake of character saving!): ``` Map rowToMap(row) { row.columns.inject([:]) {map, col -> map << [(col.name): col.val]} } ``` The `+` operator can also be used instead of the `<<`.
18,584
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c">How do I calculate someone&#39;s age in C#?</a> </p> </blockquote> <p>Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calculate the exact age of someone, I have introduced my birthdate in my profile (01/12/1975) "dd/mm/yyyy" and it calculated 33 and I'm 32 actually still, isn't it better to calculate the exact age? </p> <p>Maybe</p> <pre><code>DateTime dt1 = DateTime.Now; TimeSpan dt2; dt2 = dt1.Subtract(new DateTime(1975, 12, 01)); double year = dt2.TotalDays / 365; </code></pre> <p>The result of year is 32.77405678074</p> <p>Could this code be OK?</p>
[ { "answer_id": 18603, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calcul...
2008/08/20
[ "https://Stackoverflow.com/questions/18584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1130097/" ]
> > **Possible Duplicate:** > > [How do I calculate someone's age in C#?](https://stackoverflow.com/questions/9/how-do-i-calculate-someones-age-in-c) > > > Maybe this could be silly but and I don't have issues with my age but sometimes it is good to calculate the exact age of someone, I have introduced my birthdate in my profile (01/12/1975) "dd/mm/yyyy" and it calculated 33 and I'm 32 actually still, isn't it better to calculate the exact age? Maybe ``` DateTime dt1 = DateTime.Now; TimeSpan dt2; dt2 = dt1.Subtract(new DateTime(1975, 12, 01)); double year = dt2.TotalDays / 365; ``` The result of year is 32.77405678074 Could this code be OK?
If you were born on January 12th 1975, you would be 33 years old today. If you were born on December 1st 1975, you would be 32 years old today. If you read the note by the birthday field when editing your profile you'll see it says "YYYY/MM/DD", I'm sure it will try to interpret dates of other formats but it looks like it interprets MM/DD/YYYY (US standard dates) in preference to DD/MM/YYYY (European standard dates). The easy fix is to enter the date of your birthday according to the suggested input style.
18,585
<h3>Update: Solved, with code</h3> <p><a href="https://stackoverflow.com/questions/18585/why-cant-you-bind-the-size-of-a-windows-form-to-applicationsettings#19056">I got it working, see my answer below for the code...</a></p> <h3>Original Post</h3> <p>As Tundey pointed out in <a href="https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c#18456">his answer</a> to my <a href="https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c">last question</a>, you can bind nearly everything about a windows forms control to ApplicationSettings pretty effortlessly. So is there really no way to do this with form Size? <a href="http://www.codeproject.com/KB/cs/UserSettings.aspx" rel="nofollow noreferrer">This tutorial</a> says you need to handle Size explicitly so you can save RestoreBounds instead of size if the window is maximized or minimized. However, I hoped I could just use a property like:</p> <pre><code>public Size RestoreSize { get { if (this.WindowState == FormWindowState.Normal) { return this.Size; } else { return this.RestoreBounds.Size; } } set { ... } } </code></pre> <p>But I can't see a way to bind this in the designer (Size is notably missing from the PropertyBinding list).</p>
[ { "answer_id": 18659, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 1, "selected": false, "text": "<p>Well I have had a quick play with this and you are correct, while there is no way to directly <em>bind</em> the size of t...
2008/08/20
[ "https://Stackoverflow.com/questions/18585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/229/" ]
### Update: Solved, with code [I got it working, see my answer below for the code...](https://stackoverflow.com/questions/18585/why-cant-you-bind-the-size-of-a-windows-form-to-applicationsettings#19056) ### Original Post As Tundey pointed out in [his answer](https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c#18456) to my [last question](https://stackoverflow.com/questions/18421/best-way-to-bind-windows-forms-properties-to-applicationsettings-in-c), you can bind nearly everything about a windows forms control to ApplicationSettings pretty effortlessly. So is there really no way to do this with form Size? [This tutorial](http://www.codeproject.com/KB/cs/UserSettings.aspx) says you need to handle Size explicitly so you can save RestoreBounds instead of size if the window is maximized or minimized. However, I hoped I could just use a property like: ``` public Size RestoreSize { get { if (this.WindowState == FormWindowState.Normal) { return this.Size; } else { return this.RestoreBounds.Size; } } set { ... } } ``` But I can't see a way to bind this in the designer (Size is notably missing from the PropertyBinding list).
I finally came up with a Form subclass that solves this, once and for all. To use it: 1. Inherit from RestorableForm instead of Form. 2. Add a binding in (ApplicationSettings) -> (PropertyBinding) to WindowRestoreState. 3. Call Properties.Settings.Default.Save() when the window is about to close. Now window position and state will be remembered between sessions. Following the suggestions from other posters below, I included a function ConstrainToScreen that makes sure the window fits nicely on the available displays when restoring itself. ### Code ``` // Consider this code public domain. If you want, you can even tell // your boss, attractive women, or the other guy in your cube that // you wrote it. Enjoy! using System; using System.Windows.Forms; using System.ComponentModel; using System.Drawing; namespace Utilities { public class RestorableForm : Form, INotifyPropertyChanged { // We invoke this event when the binding needs to be updated. public event PropertyChangedEventHandler PropertyChanged; // This stores the last window position and state private WindowRestoreStateInfo windowRestoreState; // Now we define the property that we will bind to our settings. [Browsable(false)] // Don't show it in the Properties list [SettingsBindable(true)] // But do enable binding to settings public WindowRestoreStateInfo WindowRestoreState { get { return windowRestoreState; } set { windowRestoreState = value; if (PropertyChanged != null) { // If anybody's listening, let them know the // binding needs to be updated: PropertyChanged(this, new PropertyChangedEventArgs("WindowRestoreState")); } } } protected override void OnClosing(CancelEventArgs e) { WindowRestoreState = new WindowRestoreStateInfo(); WindowRestoreState.Bounds = WindowState == FormWindowState.Normal ? Bounds : RestoreBounds; WindowRestoreState.WindowState = WindowState; base.OnClosing(e); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (WindowRestoreState != null) { Bounds = ConstrainToScreen(WindowRestoreState.Bounds); WindowState = WindowRestoreState.WindowState; } } // This helper class stores both position and state. // That way, we only have to set one binding. public class WindowRestoreStateInfo { Rectangle bounds; public Rectangle Bounds { get { return bounds; } set { bounds = value; } } FormWindowState windowState; public FormWindowState WindowState { get { return windowState; } set { windowState = value; } } } private Rectangle ConstrainToScreen(Rectangle bounds) { Screen screen = Screen.FromRectangle(WindowRestoreState.Bounds); Rectangle workingArea = screen.WorkingArea; int width = Math.Min(bounds.Width, workingArea.Width); int height = Math.Min(bounds.Height, workingArea.Height); // mmm....minimax int left = Math.Min(workingArea.Right - width, Math.Max(bounds.Left, workingArea.Left)); int top = Math.Min(workingArea.Bottom - height, Math.Max(bounds.Top, workingArea.Top)); return new Rectangle(left, top, width, height); } } } ``` ### Settings Bindings References * [SettingsBindableAttribute](http://msdn.microsoft.com/en-us/library/system.componentmodel.settingsbindableattribute.aspx) * [INotifyPropertyChanged](http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx)
18,608
<p>I've got a group of inter-related classes that are all overridden together to create a particular implementation. I'm wondering if it is a good idea to enclose the interrelated subclasses in a namespace.</p> <p>For example purposes, consider the following namespaces and classes:</p> <pre><code>namespace Protocol { public abstract class Message { } public abstract class Driver { } } namespace Protocol.Tcp { public class TcpMessage : Message { } public class TcpDriver : Driver { } } namespace Protocol.Ftp { public class FtpMessage : Message { } public class FtpDriver : Driver { } } </code></pre> <p>What is the best way to structure the namespaces? It seems unavoidable to expose the inheritance in the namespace since the base classes don't really belong in either the Protocol.Tcp namespace or the Protocol.Ftp namespace.</p>
[ { "answer_id": 18616, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 4, "selected": true, "text": "<p>I think you are perhaps worrying too much!</p>\n\n<p>Does it make sense logically? Do you know where to find your code wit...
2008/08/20
[ "https://Stackoverflow.com/questions/18608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/327/" ]
I've got a group of inter-related classes that are all overridden together to create a particular implementation. I'm wondering if it is a good idea to enclose the interrelated subclasses in a namespace. For example purposes, consider the following namespaces and classes: ``` namespace Protocol { public abstract class Message { } public abstract class Driver { } } namespace Protocol.Tcp { public class TcpMessage : Message { } public class TcpDriver : Driver { } } namespace Protocol.Ftp { public class FtpMessage : Message { } public class FtpDriver : Driver { } } ``` What is the best way to structure the namespaces? It seems unavoidable to expose the inheritance in the namespace since the base classes don't really belong in either the Protocol.Tcp namespace or the Protocol.Ftp namespace.
I think you are perhaps worrying too much! Does it make sense logically? Do you know where to find your code within the namespaces? I would much rather see a codebase like the above with a small number of classes, relevant to the name with a hierarchy, than one large namespace where everything is interrelated.. Remember, namespacing is there for precisely this, to **organise your codebase logically** What you have seems logical :) EDIT: As an example: ``` using System.Data; using System.Data.Sql; ``` ;)
18,617
<p>How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?</p>
[ { "answer_id": 18623, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 8, "selected": true, "text": "<p>Several connectors are configured, and each connector has an optional \"address\" attribute where you can set the IP addr...
2008/08/20
[ "https://Stackoverflow.com/questions/18617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1310/" ]
How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?
Several connectors are configured, and each connector has an optional "address" attribute where you can set the IP address. 1. Edit `tomcat/conf/server.xml`. 2. Specify a bind address for that connector: ``` <Connector port="8080" protocol="HTTP/1.1" address="127.0.0.1" connectionTimeout="20000" redirectPort="8443" /> ```
18,661
<p>Is it possible to get UI text from an external application in C#. </p> <p>In particular, is there a way to read Unicode text from a label (I assume it's a normal Windows label control) from an external Win32 app that was written by a 3rd party? The text is visible, but not selectable by mouse in the UI.</p> <p>I assume there is some accessibility API (e.g. meant for screen readers) that allows this. </p> <p>Edit: Currently looking into using something like the <a href="http://msdn.microsoft.com/en-us/magazine/cc163617.aspx" rel="nofollow noreferrer">Managed Spy App</a> but would still appreciate any other leads.</p>
[ { "answer_id": 18698, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 3, "selected": false, "text": "<p>You could do it if that unicode text is actually a window with a caption by sending a <a href=\"http://msdn.microsof...
2008/08/20
[ "https://Stackoverflow.com/questions/18661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/838/" ]
Is it possible to get UI text from an external application in C#. In particular, is there a way to read Unicode text from a label (I assume it's a normal Windows label control) from an external Win32 app that was written by a 3rd party? The text is visible, but not selectable by mouse in the UI. I assume there is some accessibility API (e.g. meant for screen readers) that allows this. Edit: Currently looking into using something like the [Managed Spy App](http://msdn.microsoft.com/en-us/magazine/cc163617.aspx) but would still appreciate any other leads.
You could do it if that unicode text is actually a window with a caption by sending a [WM\_GETTEXT](http://msdn.microsoft.com/en-us/library/ms632627.aspx) message. ``` [DllImport("user32.dll")] public static extern int SendMessage (IntPtr hWnd, int msg, int Param, System.Text.StringBuilder text); System.Text.StringBuilder text = new System.Text.StringBuilder(255) ; // or length from call with GETTEXTLENGTH int RetVal = Win32.SendMessage( hWnd , WM_GETTEXT, text.Capacity, text); ``` If it is just painted on the canvas you might have some luck if you know what framework the application uses. If it uses WinForms or Borland's VCL you could use that knowledge to get to the text.
18,676
<p>I need to generate a random integer between 1 and n (where n is a positive whole number) to use for a unit test. I don't need something overly complicated to ensure true randomness - just an old-fashioned random number.</p> <p>How would I do that?</p>
[ { "answer_id": 18680, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 7, "selected": true, "text": "<p>To get a random integer value between 1 and N (inclusive) you can use the following.</p>\n\n<pre><code>CInt(Math.Ceiling(Rnd...
2008/08/20
[ "https://Stackoverflow.com/questions/18676", "https://Stackoverflow.com", "https://Stackoverflow.com/users/225/" ]
I need to generate a random integer between 1 and n (where n is a positive whole number) to use for a unit test. I don't need something overly complicated to ensure true randomness - just an old-fashioned random number. How would I do that?
To get a random integer value between 1 and N (inclusive) you can use the following. ``` CInt(Math.Ceiling(Rnd() * n)) + 1 ```