qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
102,631 | <p>I have had thoughts of trying to write a simple crawler that might crawl and produce a list of its findings for our NPO's websites and content.</p>
<p>Does anybody have any thoughts on how to do this? Where do you point the crawler to get started? How does it send back its findings and still keep crawling? How does it know what it finds, etc,etc.</p>
| [
{
"answer_id": 102665,
"author": "whatsisname",
"author_id": 8159,
"author_profile": "https://Stackoverflow.com/users/8159",
"pm_score": 0,
"selected": false,
"text": "<p>Use wget, do a recursive web suck, which will dump all the files onto your harddrive, then write another script to go through all the downloaded files and analyze them.</p>\n\n<p>Edit: or maybe curl instead of wget, but I am not familiar with curl, I do not know if it does recursive downloads like wget.</p>\n"
},
{
"answer_id": 102705,
"author": "Gero",
"author_id": 13116,
"author_profile": "https://Stackoverflow.com/users/13116",
"pm_score": 2,
"selected": false,
"text": "<p>You could make a list of words and make a thread for each word searched at google.<br> Then each thread will create a new thread for each link it find in the page.<br> Each thread should write what it finds in a database. When each thread finishes reading the page, it terminates.<br>And there you have a very big database of links in your database.<br></p>\n"
},
{
"answer_id": 102716,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 3,
"selected": false,
"text": "<p>Crawlers are simple in concept.</p>\n\n<p>You get a root page via a HTTP GET, parse it to find URLs and put them on a queue unless they've been parsed already (so you need a global record of pages you have already parsed).</p>\n\n<p>You can use the Content-type header to find out what the type of content is, and limit your crawler to only parsing the HTML types.</p>\n\n<p>You can strip out the HTML tags to get the plain text, which you can do text analysis on (to get tags, etc, the meat of the page). You could even do that on the alt/title tags for images if you got that advanced.</p>\n\n<p>And in the background you can have a pool of threads eating URLs from the Queue and doing the same. You want to limit the number of threads of course.</p>\n"
},
{
"answer_id": 102719,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 2,
"selected": false,
"text": "<p>Wikipedia has a good article about <a href=\"http://en.wikipedia.org/wiki/Web_crawler\" rel=\"nofollow noreferrer\">web crawlers</a>, covering many of the algorithms and considerations.</p>\n\n<p>However, I wouldn't bother writing my own crawler. It's a lot of work, and since you only need a \"simple crawler\", I'm thinking all you really need is an <a href=\"http://en.wikipedia.org/wiki/Web_crawler#Open-source_crawlers\" rel=\"nofollow noreferrer\">off-the-shelf crawler</a>. There are a lot of free and open-source crawlers that will likely do everything you need, with very little work on your part.</p>\n"
},
{
"answer_id": 102725,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": false,
"text": "<p>If your NPO's sites are relatively big or complex (having dynamic pages that'll effectively create a 'black hole' like a calendar with a 'next day' link) you'd be better using a real web crawler, like <a href=\"http://crawler.archive.org/\" rel=\"noreferrer\">Heritrix.</a></p>\n\n<p>If the sites total a few number of pages you can get away with just using curl or wget or your own. Just remember if they start to get big or you start making your script more complex to just use a real crawler or at least look at its source to see what are they doing and why.</p>\n\n<p>Some issues (there are more):</p>\n\n<ul>\n<li>Black holes (as described)</li>\n<li>Retries (what if you get a 500?)</li>\n<li>Redirects</li>\n<li>Flow control (else you can be a burden on the sites)</li>\n<li>robots.txt implementation</li>\n</ul>\n"
},
{
"answer_id": 102820,
"author": "slim",
"author_id": 7512,
"author_profile": "https://Stackoverflow.com/users/7512",
"pm_score": 7,
"selected": false,
"text": "<p>You'll be reinventing the wheel, to be sure. But here's the basics:</p>\n\n<ul>\n<li>A list of unvisited URLs - seed this with one or more starting pages</li>\n<li>A list of visited URLs - so you don't go around in circles</li>\n<li>A set of rules for URLs you're not interested in - so you don't index the whole Internet</li>\n</ul>\n\n<p>Put these in persistent storage, so you can stop and start the crawler without losing state.</p>\n\n<p>Algorithm is:</p>\n\n<pre><code>while(list of unvisited URLs is not empty) {\n take URL from list\n remove it from the unvisited list and add it to the visited list\n fetch content\n record whatever it is you want to about the content\n if content is HTML {\n parse out URLs from links\n foreach URL {\n if it matches your rules\n and it's not already in either the visited or unvisited list\n add it to the unvisited list\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8562237,
"author": "lexmooze",
"author_id": 999304,
"author_profile": "https://Stackoverflow.com/users/999304",
"pm_score": 5,
"selected": false,
"text": "<p>The complicated part of a crawler is if you want to scale it to a huge number of websites/requests.\nIn this situation you will have to deal with some issues like:</p>\n\n<ul>\n<li><p>Impossibility to keep info all in one database.</p></li>\n<li><p>Not enough RAM to deal with huge index(s)</p></li>\n<li><p>Multithread performance and concurrency</p></li>\n<li><p>Crawler traps (infinite loop created by changing urls, calendars, sessions ids...) and duplicated content.</p></li>\n<li><p>Crawl from more than one computer</p></li>\n<li><p>Malformed HTML codes</p></li>\n<li><p>Constant http errors from servers</p></li>\n<li><p>Databases without compression, wich make your need for space about 8x bigger.</p></li>\n<li><p>Recrawl routines and priorities.</p></li>\n<li><p>Use requests with compression (Deflate/gzip) (good for any kind of crawler).</p></li>\n</ul>\n\n<p><strong>And some important things</strong></p>\n\n<ul>\n<li><p>Respect robots.txt</p></li>\n<li><p>And a crawler delay on each request to dont suffocate web servers.</p></li>\n</ul>\n"
},
{
"answer_id": 11261987,
"author": "Sathishkumar",
"author_id": 1365709,
"author_profile": "https://Stackoverflow.com/users/1365709",
"pm_score": 0,
"selected": false,
"text": "<p>I'm using Open search server for my company internal search, try this : <a href=\"http://open-search-server.com\" rel=\"nofollow\">http://open-search-server.com</a> its also open soruce.</p>\n"
},
{
"answer_id": 13843277,
"author": "alienCoder",
"author_id": 1723861,
"author_profile": "https://Stackoverflow.com/users/1723861",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Multithreaded Web Crawler</strong><br></p>\n\n<p>If you want to crawl large sized website then you should write a multi-threaded crawler.\nconnecting,fetching and writing crawled information in files/database - these are the three steps of crawling but if you use a single threaded than your CPU and network utilization will be pour.</p>\n\n<p>A multi threaded web crawler needs two data structures- linksVisited(this should be implemented as a hashmap or trai) and linksToBeVisited(this is a queue). </p>\n\n<p>Web crawler uses BFS to traverse world wide web.</p>\n\n<p>Algorithm of a basic web crawler:-</p>\n\n<ol>\n<li>Add one or more seed urls to linksToBeVisited. The method to add a url to linksToBeVisited must be synchronized.</li>\n<li>Pop an element from linksToBeVisited and add this to linksVisited. This pop method to pop url from linksToBeVisited must be synchronized.</li>\n<li>Fetch the page from internet.</li>\n<li>Parse the file and add any till now not visited link found in the page to linksToBeVisited. URL's can be filtered if needed. The user can give a set of rules to filter which url's to be scanned.</li>\n<li>The necessary information found on the page is saved in database or file.</li>\n<li><p>repeat step 2 to 5 until queue is linksToBeVisited empty.</p>\n\n<p>Here is a code snippet on how to synchronize the threads....</p>\n\n<pre><code> public void add(String site) {\n synchronized (this) {\n if (!linksVisited.contains(site)) {\n linksToBeVisited.add(site);\n }\n }\n }\n\n public String next() {\n if (linksToBeVisited.size() == 0) {\n return null;\n }\n synchronized (this) {\n // Need to check again if size has changed\n if (linksToBeVisited.size() > 0) {\n String s = linksToBeVisited.get(0);\n linksToBeVisited.remove(0);\n linksVisited.add(s);\n return s;\n }\n return null;\n }\n }\n</code></pre></li>\n</ol>\n\n<p></p>\n"
},
{
"answer_id": 16977478,
"author": "Misterhex",
"author_id": 1610747,
"author_profile": "https://Stackoverflow.com/users/1610747",
"pm_score": 0,
"selected": false,
"text": "<p>i did a simple web crawler using reactive extension in .net.</p>\n\n<p><a href=\"https://github.com/Misterhex/WebCrawler\" rel=\"nofollow\">https://github.com/Misterhex/WebCrawler</a></p>\n\n<pre><code>public class Crawler\n {\n class ReceivingCrawledUri : ObservableBase<Uri>\n {\n public int _numberOfLinksLeft = 0;\n\n private ReplaySubject<Uri> _subject = new ReplaySubject<Uri>();\n private Uri _rootUri;\n private IEnumerable<IUriFilter> _filters;\n\n public ReceivingCrawledUri(Uri uri)\n : this(uri, Enumerable.Empty<IUriFilter>().ToArray())\n { }\n\n public ReceivingCrawledUri(Uri uri, params IUriFilter[] filters)\n {\n _filters = filters;\n\n CrawlAsync(uri).Start();\n }\n\n protected override IDisposable SubscribeCore(IObserver<Uri> observer)\n {\n return _subject.Subscribe(observer);\n }\n\n private async Task CrawlAsync(Uri uri)\n {\n using (HttpClient client = new HttpClient() { Timeout = TimeSpan.FromMinutes(1) })\n {\n IEnumerable<Uri> result = new List<Uri>();\n\n try\n {\n string html = await client.GetStringAsync(uri);\n result = CQ.Create(html)[\"a\"].Select(i => i.Attributes[\"href\"]).SafeSelect(i => new Uri(i));\n result = Filter(result, _filters.ToArray());\n\n result.ToList().ForEach(async i =>\n {\n Interlocked.Increment(ref _numberOfLinksLeft);\n _subject.OnNext(i);\n await CrawlAsync(i);\n });\n }\n catch\n { }\n\n if (Interlocked.Decrement(ref _numberOfLinksLeft) == 0)\n _subject.OnCompleted();\n }\n }\n\n private static List<Uri> Filter(IEnumerable<Uri> uris, params IUriFilter[] filters)\n {\n var filtered = uris.ToList();\n foreach (var filter in filters.ToList())\n {\n filtered = filter.Filter(filtered);\n }\n return filtered;\n }\n }\n\n public IObservable<Uri> Crawl(Uri uri)\n {\n return new ReceivingCrawledUri(uri, new ExcludeRootUriFilter(uri), new ExternalUriFilter(uri), new AlreadyVisitedUriFilter());\n }\n\n public IObservable<Uri> Crawl(Uri uri, params IUriFilter[] filters)\n {\n return new ReceivingCrawledUri(uri, filters);\n }\n}\n</code></pre>\n\n<p>and you can use it as follows:</p>\n\n<pre><code>Crawler crawler = new Crawler();\nIObservable observable = crawler.Crawl(new Uri(\"http://www.codinghorror.com/\"));\nobservable.Subscribe(onNext: Console.WriteLine, \nonCompleted: () => Console.WriteLine(\"Crawling completed\"));\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102631",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have had thoughts of trying to write a simple crawler that might crawl and produce a list of its findings for our NPO's websites and content.
Does anybody have any thoughts on how to do this? Where do you point the crawler to get started? How does it send back its findings and still keep crawling? How does it know what it finds, etc,etc. | You'll be reinventing the wheel, to be sure. But here's the basics:
* A list of unvisited URLs - seed this with one or more starting pages
* A list of visited URLs - so you don't go around in circles
* A set of rules for URLs you're not interested in - so you don't index the whole Internet
Put these in persistent storage, so you can stop and start the crawler without losing state.
Algorithm is:
```
while(list of unvisited URLs is not empty) {
take URL from list
remove it from the unvisited list and add it to the visited list
fetch content
record whatever it is you want to about the content
if content is HTML {
parse out URLs from links
foreach URL {
if it matches your rules
and it's not already in either the visited or unvisited list
add it to the unvisited list
}
}
}
``` |
102,690 | <p>This question comes out of the discussion on <a href="https://stackoverflow.com/questions/101825/whats-the-best-way-of-using-a-pair-triple-etc-of-values-as-one-value-in-c">tuples</a>.</p>
<p>I started thinking about the hash code that a tuple should have.
What if we will accept KeyValuePair class as a tuple? It doesn't override the GetHashCode() method, so probably it won't be aware of the hash codes of it's "children"... So, run-time will call Object.GetHashCode(), which is not aware of the real object structure.</p>
<p>Then we can make two instances of some reference type, which are actually Equal, because of the overloaded GetHashCode() and Equals(). And use them as "children" in tuples to "cheat" the dictionary.</p>
<p>But it doesn't work! Run-time somehow figures out the structure of our tuple and calls the overloaded GetHashCode of our class!</p>
<p>How does it work? What's the analysis made by Object.GetHashCode()? </p>
<p>Can it affect the performance in some bad scenario, when we use some complicated keys? (probably, impossible scenario... but still)</p>
<p>Consider this code as an example:</p>
<pre><code>namespace csharp_tricks
{
class Program
{
class MyClass
{
int keyValue;
int someInfo;
public MyClass(int key, int info)
{
keyValue = key;
someInfo = info;
}
public override bool Equals(object obj)
{
MyClass other = obj as MyClass;
if (other == null) return false;
return keyValue.Equals(other.keyValue);
}
public override int GetHashCode()
{
return keyValue.GetHashCode();
}
}
static void Main(string[] args)
{
Dictionary<object, object> dict = new Dictionary<object, object>();
dict.Add(new KeyValuePair<MyClass,object>(new MyClass(1, 1), 1), 1);
//here we get the exception -- an item with the same key was already added
//but how did it figure out the hash code?
dict.Add(new KeyValuePair<MyClass,object>(new MyClass(1, 2), 1), 1);
return;
}
}
}
</code></pre>
<p><strong>Update</strong> I think I've found an explanation for this as stated below in my answer. The main outcomes of it are:</p>
<ul>
<li>Be careful with your keys and their hash codes :-)</li>
<li>For complicated dictionary keys you must override Equals() and GetHashCode() correctly.</li>
</ul>
| [
{
"answer_id": 102757,
"author": "Dan Blair",
"author_id": 1327,
"author_profile": "https://Stackoverflow.com/users/1327",
"pm_score": 0,
"selected": false,
"text": "<p>I don't have the book reference anymore, and I'll have to find it just to confirm, but I thought the default base hash just hashed together all of the members of your object. It got access to them because of the way the CLR worked, so it wasn't something that you could write as well as they had.</p>\n\n<p>That is completely from memory of something I briefly read so take it for what you will.</p>\n\n<p><strong>Edit:</strong> The book was <strong>Inside C#</strong> from MS Press. The one with the Saw blade on the cover. The author spent a good deal of time explaining how things were implemented in the CLR, how the language translated down to MSIL, ect. ect. If you can find the book it's not a bad read.</p>\n\n<p><strong>Edit:</strong> Form the link provided it looks like</p>\n\n<blockquote>\n <p>Object.GetHashCode() uses an\n internal field in the System.Object class to generate the hash value. Each\n object created is assigned a unique object key, stored as an integer,when it\n is created. These keys start at 1 and increment every time a new object of\n any type gets created.</p>\n</blockquote>\n\n<p>Hmm I guess I need to write a few of my own hash codes, if I expect to use objects as hash keys.</p>\n"
},
{
"answer_id": 102836,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 4,
"selected": false,
"text": "<p>Don't override GetHashcode() and Equals() on mutable classes, only override it on immutable classes or structures, else if you modify a object used as key the hash table won't function properly anymore (you won't be able to retrieve the value associated to the key after the key object was modified)</p>\n\n<p>Also hash tables don't use hashcodes to identify objects they use the key objects themselfes as identifiers, it's not required that all keys that are used to add entries in a hash table return different hashcodes, but it is recommended that they do, else performance suffers greatly. </p>\n"
},
{
"answer_id": 102974,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 2,
"selected": false,
"text": "<p>Check out this <a href=\"http://blogs.msdn.com/brada/archive/2003/09/30/50396.aspx\" rel=\"nofollow noreferrer\">post</a> by Brad Abrams and also the comment by Brian Grunkemeyer for some more information on how object.GetHashCode works. Also, take a look at the first comment on Ayande's blog <a href=\"http://ayende.com/Blog/archive/2006/12/10/InterviewQuestionsFromHellTakeIV.aspx\" rel=\"nofollow noreferrer\">post</a>. I don't know if the current releases of the Framework still follow these rules or if they have actually changed it like Brad implied.</p>\n"
},
{
"answer_id": 103114,
"author": "Cory R. King",
"author_id": 16742,
"author_profile": "https://Stackoverflow.com/users/16742",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>so probably it won't be aware of the hash codes of it's \"children\".</p>\n</blockquote>\n\n<p>Your example seems to prove otherwise :-) The hash code for the key <code>MyClass</code> and the value <code>1</code> is the same for both <code>KeyValuePair</code>'s . The KeyValuePair implementation must be using both its <code>Key</code> and <code>Value</code> for its own hash code </p>\n\n<p>Moving up, the dictionary class wants unique keys. It is using the hashcode provided by each key to figure things out. Remember that the runtime isn't calling <code>Object.GetHashCode()</code>, but it is calling the GetHashCode() implementation provided by the instance you give it.</p>\n\n<p>Consider a more complex case:</p>\n\n<pre><code>public class HappyClass\n{\n\n enum TheUnit\n {\n Points,\n Picas,\n Inches\n }\n\n class MyDistanceClass\n {\n int distance;\n TheUnit units;\n\n public MyDistanceClass(int theDistance, TheUnit unit)\n {\n distance = theDistance;\n\n units = unit;\n }\n public static int ConvertDistance(int oldDistance, TheUnit oldUnit, TheUnit newUnit)\n {\n // insert real unit conversion code here :-)\n return oldDistance * 100;\n }\n\n /// <summary>\n /// Figure out if we are equal distance, converting into the same units of measurement if we have to\n /// </summary>\n /// <param name=\"obj\">the other guy</param>\n /// <returns>true if we are the same distance</returns>\n public override bool Equals(object obj)\n {\n MyDistanceClass other = obj as MyDistanceClass;\n if (other == null) return false;\n\n if (other.units != this.units)\n {\n int newDistance = MyDistanceClass.ConvertDistance(other.distance, other.units, this.units);\n return distance.Equals(newDistance);\n }\n else\n {\n return distance.Equals(other.distance);\n }\n\n\n }\n\n public override int GetHashCode()\n {\n // even if the distance is equal in spite of the different units, the objects are not\n return distance.GetHashCode() * units.GetHashCode();\n }\n }\n static void Main(string[] args)\n {\n\n // these are the same distance... 72 points = 1 inch\n MyDistanceClass distPoint = new MyDistanceClass(72, TheUnit.Points);\n MyDistanceClass distInch = new MyDistanceClass(1, TheUnit.Inch);\n\n Debug.Assert(distPoint.Equals(distInch), \"these should be true!\");\n Debug.Assert(distPoint.GetHashCode() != distInch.GetHashCode(), \"But yet they are fundimentally different values\");\n\n Dictionary<object, object> dict = new Dictionary<object, object>();\n\n dict.Add(new KeyValuePair<MyDistanceClass, object>(distPoint, 1), 1);\n\n //this should not barf\n dict.Add(new KeyValuePair<MyDistanceClass, object>(distInch, 1), 1);\n\n return;\n }\n\n}\n</code></pre>\n\n<p>Basically... in the case of my example, you'd want two objects that are the same distance to return \"true\" for Equals, but yet return different hash codes.</p>\n"
},
{
"answer_id": 103587,
"author": "Max Galkin",
"author_id": 2351099,
"author_profile": "https://Stackoverflow.com/users/2351099",
"pm_score": 2,
"selected": true,
"text": "<p>It seems that I have a clue now.</p>\n\n<p>I thought KeyValuePair is a reference type, but it is not, it is a struct. And so it uses ValueType.GetHashCode() method. MSDN for it says: \"One or more fields of the derived type is used to calculate the return value\".</p>\n\n<p>If you will take a real reference type as a \"tuple-provider\" you'll cheat the dictionary (or yourself...).</p>\n\n<pre><code>using System.Collections.Generic;\n\nnamespace csharp_tricks\n{\n class Program\n {\n class MyClass\n {\n int keyValue;\n int someInfo;\n\n public MyClass(int key, int info)\n {\n keyValue = key;\n someInfo = info;\n }\n\n public override bool Equals(object obj)\n {\n MyClass other = obj as MyClass;\n if (other == null) return false;\n\n return keyValue.Equals(other.keyValue);\n }\n\n public override int GetHashCode()\n {\n return keyValue.GetHashCode();\n }\n }\n\n class Pair<T, R>\n {\n public T First { get; set; }\n public R Second { get; set; }\n }\n\n static void Main(string[] args)\n {\n var dict = new Dictionary<Pair<int, MyClass>, object>();\n\n dict.Add(new Pair<int, MyClass>() { First = 1, Second = new MyClass(1, 2) }, 1);\n\n //this is a pair of the same values as previous! but... no exception this time...\n dict.Add(new Pair<int, MyClass>() { First = 1, Second = new MyClass(1, 3) }, 1);\n\n return;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 154081,
"author": "Rinat Abdullin",
"author_id": 47366,
"author_profile": "https://Stackoverflow.com/users/47366",
"pm_score": 2,
"selected": false,
"text": "<p>Here are the proper Hash and equality implementations for the Quad tuple (contains 4 tuple components inside). This code ensures proper usage of this specific tuple in HashSets and the dictionaries.</p>\n\n<p>More on the subject (including the source code) <a href=\"http://rabdullin.com/using-tuples-in-c/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p><strong>Note</strong> usage of the <em>unchecked</em> keyword (to avoid overflows) and throwing NullReferenceException if obj is null (as required by the base method)</p>\n\n<pre><code>public override bool Equals(object obj)\n{\n if (ReferenceEquals(null, obj))\n throw new NullReferenceException(\"obj is null\");\n if (ReferenceEquals(this, obj)) return true;\n if (obj.GetType() != typeof (Quad<T1, T2, T3, T4>)) return false;\n return Equals((Quad<T1, T2, T3, T4>) obj);\n}\n\npublic bool Equals(Quad<T1, T2, T3, T4> obj)\n{\n if (ReferenceEquals(null, obj)) return false;\n if (ReferenceEquals(this, obj)) return true;\n return Equals(obj.Item1, Item1)\n && Equals(obj.Item2, Item2)\n && Equals(obj.Item3, Item3)\n && Equals(obj.Item4, Item4);\n}\n\npublic override int GetHashCode()\n{\n unchecked\n {\n int result = Item1.GetHashCode();\n result = (result*397) ^ Item2.GetHashCode();\n result = (result*397) ^ Item3.GetHashCode();\n result = (result*397) ^ Item4.GetHashCode();\n return result;\n }\n}\npublic static bool operator ==(Quad<T1, T2, T3, T4> left, Quad<T1, T2, T3, T4> right)\n{\n return Equals(left, right);\n}\n\n\npublic static bool operator !=(Quad<T1, T2, T3, T4> left, Quad<T1, T2, T3, T4> right)\n{\n return !Equals(left, right);\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2351099/"
]
| This question comes out of the discussion on [tuples](https://stackoverflow.com/questions/101825/whats-the-best-way-of-using-a-pair-triple-etc-of-values-as-one-value-in-c).
I started thinking about the hash code that a tuple should have.
What if we will accept KeyValuePair class as a tuple? It doesn't override the GetHashCode() method, so probably it won't be aware of the hash codes of it's "children"... So, run-time will call Object.GetHashCode(), which is not aware of the real object structure.
Then we can make two instances of some reference type, which are actually Equal, because of the overloaded GetHashCode() and Equals(). And use them as "children" in tuples to "cheat" the dictionary.
But it doesn't work! Run-time somehow figures out the structure of our tuple and calls the overloaded GetHashCode of our class!
How does it work? What's the analysis made by Object.GetHashCode()?
Can it affect the performance in some bad scenario, when we use some complicated keys? (probably, impossible scenario... but still)
Consider this code as an example:
```
namespace csharp_tricks
{
class Program
{
class MyClass
{
int keyValue;
int someInfo;
public MyClass(int key, int info)
{
keyValue = key;
someInfo = info;
}
public override bool Equals(object obj)
{
MyClass other = obj as MyClass;
if (other == null) return false;
return keyValue.Equals(other.keyValue);
}
public override int GetHashCode()
{
return keyValue.GetHashCode();
}
}
static void Main(string[] args)
{
Dictionary<object, object> dict = new Dictionary<object, object>();
dict.Add(new KeyValuePair<MyClass,object>(new MyClass(1, 1), 1), 1);
//here we get the exception -- an item with the same key was already added
//but how did it figure out the hash code?
dict.Add(new KeyValuePair<MyClass,object>(new MyClass(1, 2), 1), 1);
return;
}
}
}
```
**Update** I think I've found an explanation for this as stated below in my answer. The main outcomes of it are:
* Be careful with your keys and their hash codes :-)
* For complicated dictionary keys you must override Equals() and GetHashCode() correctly. | It seems that I have a clue now.
I thought KeyValuePair is a reference type, but it is not, it is a struct. And so it uses ValueType.GetHashCode() method. MSDN for it says: "One or more fields of the derived type is used to calculate the return value".
If you will take a real reference type as a "tuple-provider" you'll cheat the dictionary (or yourself...).
```
using System.Collections.Generic;
namespace csharp_tricks
{
class Program
{
class MyClass
{
int keyValue;
int someInfo;
public MyClass(int key, int info)
{
keyValue = key;
someInfo = info;
}
public override bool Equals(object obj)
{
MyClass other = obj as MyClass;
if (other == null) return false;
return keyValue.Equals(other.keyValue);
}
public override int GetHashCode()
{
return keyValue.GetHashCode();
}
}
class Pair<T, R>
{
public T First { get; set; }
public R Second { get; set; }
}
static void Main(string[] args)
{
var dict = new Dictionary<Pair<int, MyClass>, object>();
dict.Add(new Pair<int, MyClass>() { First = 1, Second = new MyClass(1, 2) }, 1);
//this is a pair of the same values as previous! but... no exception this time...
dict.Add(new Pair<int, MyClass>() { First = 1, Second = new MyClass(1, 3) }, 1);
return;
}
}
}
``` |
102,720 | <p>I just finished a medium sized web site and one thing I noticed about my css organization was that I have a lot of hard coded colour values throughout. This obviously isn't great for maintainability. Generally, when I design a site I pick 3-5 main colours for a theme. I end up setting some default values for paragraphs, links, etc... at the beginning of my main css, but some components will change the colour (like the legend tag for example) and require me to restyle with the colour I wanted. How do you avoid this? I was thinking of creating separate rules for each colour and just use those when I need to restyle.</p>
<p>i.e.</p>
<pre><code>.color1 {
color: #3d444d;
}
</code></pre>
| [
{
"answer_id": 102791,
"author": "JeeBee",
"author_id": 17832,
"author_profile": "https://Stackoverflow.com/users/17832",
"pm_score": 0,
"selected": false,
"text": "<p>You could have a colours.css file with just the colours/images for each tag in.\nThen you can change the colours just by replacing the file, or having a dynamically generated CSS file, or having different CSS files available and selecting based upon website URL/subfolder/property/etc.</p>\n\n<p>Or you can have colour tags as you write, but then your HTML turns into:</p>\n\n<p><p style=\"body grey\">Blah</p></p>\n\n<p>CSS should have a feature where you can define values for things like colours that you wish to be consistent through a style but are defined in one place only. Still, there's search and replace.</p>\n"
},
{
"answer_id": 102792,
"author": "Kolten",
"author_id": 13959,
"author_profile": "https://Stackoverflow.com/users/13959",
"pm_score": 0,
"selected": false,
"text": "<p>So you're saying you don't want to go back into your CSS to change color values if you find another color 'theme' that might work better?</p>\n\n<p>Unfortunately, I don't see a way around this. CSS defines styles, and with color being one of them, the only way to change it is to go into the css and change it.</p>\n\n<p>Of course, you could build yourself a little program that will allow you to change the css file by picking a color wheel on a webpage or something, which will then write that value into the css file using the filesystemobject or something, but that's a lot more work than required for sure.</p>\n"
},
{
"answer_id": 102796,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 0,
"selected": false,
"text": "<p>Generally it's better to just find and replace the colours you are changing.</p>\n\n<p>Anything more powerful than that will be more complex with few benefits.</p>\n"
},
{
"answer_id": 102817,
"author": "Josh Millard",
"author_id": 13600,
"author_profile": "https://Stackoverflow.com/users/13600",
"pm_score": 2,
"selected": false,
"text": "<p>One thing I've done here is break out my palette declarations from other style/layout markup, grouping commonly-colored items in lists, e.g.</p>\n\n<pre><code>h1 { \n padding...\n margin...\n font-family...\n}\n\np {\n ...\n}\n\ncode {\n ...\n}\n\n/* time passes */\n\n/* these elements are semantically grouped by color in the design */\nh1, p, code { \n color: #ff0000;\n}\n</code></pre>\n\n<p>On preview, JeeBee's suggestion is a logical extension of this: if it makes sense to handle your color declarations (and, of course, this can apply to other style issues, though color has the unique properties of not changing layout), you might consider pushing it out to a separate css file, yeah. This makes it easier to hot-swap color-only thematic variations, too, by just targeting one or another colorxxx.css profile as your include.</p>\n"
},
{
"answer_id": 102838,
"author": "naspinski",
"author_id": 14777,
"author_profile": "https://Stackoverflow.com/users/14777",
"pm_score": 3,
"selected": true,
"text": "<p>That's exactly what you should do. </p>\n\n<p>The more centralized you can make your css, the easier it will be to make changes in the future. And let's be serious, you will want to change colors in the future. </p>\n\n<p>You should almost never hard-code any css into your html, it should <strong>all</strong> be in the css. </p>\n\n<p>Also, something I have started doing more often is to layer your css classes on eachother to make it even easier to change colors once... represent everywhere.</p>\n\n<p>Sample (random color) css:</p>\n\n<pre><code>.main_text {color:#444444;}\n.secondary_text{color:#765123;}\n.main_color {background:#343434;}\n.secondary_color {background:#765sda;}\n</code></pre>\n\n<p>Then some markup, notice how I am using the colors layer with otehr classes, that way I can just change ONE css class:</p>\n\n<pre><code><body class='main_text'>\n <div class='main_color secondary_text'>\n <span class='secondary color main_text'>bla bla bla</span>\n </div>\n <div class='main_color secondary_text>\n You get the idea...\n </div>\n</body>\n</code></pre>\n\n<p>Remember... inline css = bad (most of the time)</p>\n"
},
{
"answer_id": 102842,
"author": "Aaron Jensen",
"author_id": 11229,
"author_profile": "https://Stackoverflow.com/users/11229",
"pm_score": 0,
"selected": false,
"text": "<p>CSS is not your answer. You want to look into an abstraction on top of CSS like <a href=\"http://haml.hamptoncatlin.com/docs/rdoc/classes/Sass.html\" rel=\"nofollow noreferrer\">SASS</a>. This will allow you to define constants and generally clean up your css. </p>\n\n<p>Here is a list of <a href=\"http://speckyboy.com/2008/03/28/top-12-css-frameworks-and-how-to-understand-them/\" rel=\"nofollow noreferrer\">CSS Frameworks</a>.</p>\n"
},
{
"answer_id": 102849,
"author": "Terhorst",
"author_id": 8062,
"author_profile": "https://Stackoverflow.com/users/8062",
"pm_score": 0,
"selected": false,
"text": "<p>I keep a list of all the colors I've used at the top of the file.</p>\n"
},
{
"answer_id": 102890,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>When the CSS is served by a server-side script, eg. PHP, usually coders make the CSS as a template file and substitute the colors at run-time. This might be used to let users choose a color model, too.</p>\n\n<p>Another way, to avoid parsing this file each time (although cache should take care of that), or just if you have a static site, is to make such template and parse it with some script/static template engine before uploading to the server.</p>\n\n<p>Search/replace can work, except when two initially distinct colors end up being the same: hard to separate them again after that! :-)</p>\n\n<p>If I am not mistaken, CSS3 should allow such parametrization. But I won't hold my breath until this feature will be available in 90% of browsers surfing the Net!</p>\n"
},
{
"answer_id": 102903,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 1,
"selected": false,
"text": "<p>See: <a href=\"https://stackoverflow.com/questions/47487/create-a-variable-in-css-file-for-use-within-that-css-file\">Create a variable in .CSS file for use within that .CSS file</a></p>\n\n<p>To summarize, you have three basic option:</p>\n\n<ol>\n<li>Use a macro pre-processor to replace constant color names in your stylesheets.</li>\n<li>Use client-side scripting to configure styles.</li>\n<li>Use a single rule for every color, listing all selectors for which it should apply (my fav...)</li>\n</ol>\n"
},
{
"answer_id": 102930,
"author": "rampion",
"author_id": 9859,
"author_profile": "https://Stackoverflow.com/users/9859",
"pm_score": 1,
"selected": false,
"text": "<p>Maybe pull all the color information into one part of your stylesheet. For example change this:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>p .frog tr.mango {\n color: blue;\n margin: 1px 3em 2.5em 4px;\n position: static;\n}\n#eta .beta span.pi {\n background: green;\n color: red;\n font-size: small;\n float: left;\n}\n// ...\n</code></pre>\n\n<p>to this:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>p .frog tr.mango {\n color: blue;\n}\n#eta .beta span.pi {\n background: green;\n color: red;\n}\n//...\np .frog tr.mango {\n margin: 1px 3em 2.5em 4px;\n position: static;\n}\n#eta .beta span.pi {\n font-size: small;\n float: left;\n}\n// ...\n</code></pre>\n"
},
{
"answer_id": 103888,
"author": "Matthew Rapati",
"author_id": 15000,
"author_profile": "https://Stackoverflow.com/users/15000",
"pm_score": 1,
"selected": false,
"text": "<p>I sometimes use PHP, and make the file something like style.css.php.\nThen you can do this:</p>\n\n<pre><code><?php \n header(\"Content-Type: text/css\");\n $colour1 = '#ff9'; \n?>\n.username {color: <?=$colour1;?>; }\n</code></pre>\n\n<p>Now you can use that colour wherever you want, and only have to change it in one place. This also works for values other then colours of course.</p>\n"
},
{
"answer_id": 104205,
"author": "neuroguy123",
"author_id": 12529,
"author_profile": "https://Stackoverflow.com/users/12529",
"pm_score": 0,
"selected": false,
"text": "<p>I like the idea of separating the colour information into a separate file, no matter how I do it. I would accept multiple answers here if I could, because I like Josh Millard's as well. I like the idea of having separate colour rules though because a particular tag might have different colours depending on where it occurs. Maybe a combination of both of these techniques would be good:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>h1, p, code {\n color: #ff0000;\n}\n</code></pre>\n\n<p>and then also have</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.color1 {\n color: #ff0000;\n}\n</code></pre>\n\n<p>for when you need to restyle.</p>\n"
},
{
"answer_id": 58487562,
"author": "Awais",
"author_id": 11393381,
"author_profile": "https://Stackoverflow.com/users/11393381",
"pm_score": 0,
"selected": false,
"text": "<p>This is where <a href=\"https://sass-lang.com/\" rel=\"nofollow noreferrer\">SASS</a> comes to help you.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12529/"
]
| I just finished a medium sized web site and one thing I noticed about my css organization was that I have a lot of hard coded colour values throughout. This obviously isn't great for maintainability. Generally, when I design a site I pick 3-5 main colours for a theme. I end up setting some default values for paragraphs, links, etc... at the beginning of my main css, but some components will change the colour (like the legend tag for example) and require me to restyle with the colour I wanted. How do you avoid this? I was thinking of creating separate rules for each colour and just use those when I need to restyle.
i.e.
```
.color1 {
color: #3d444d;
}
``` | That's exactly what you should do.
The more centralized you can make your css, the easier it will be to make changes in the future. And let's be serious, you will want to change colors in the future.
You should almost never hard-code any css into your html, it should **all** be in the css.
Also, something I have started doing more often is to layer your css classes on eachother to make it even easier to change colors once... represent everywhere.
Sample (random color) css:
```
.main_text {color:#444444;}
.secondary_text{color:#765123;}
.main_color {background:#343434;}
.secondary_color {background:#765sda;}
```
Then some markup, notice how I am using the colors layer with otehr classes, that way I can just change ONE css class:
```
<body class='main_text'>
<div class='main_color secondary_text'>
<span class='secondary color main_text'>bla bla bla</span>
</div>
<div class='main_color secondary_text>
You get the idea...
</div>
</body>
```
Remember... inline css = bad (most of the time) |
102,742 | <p>Like many of you, I use ReSharper to speed up the development process. When you use it to override the equality members of a class, the code-gen it produces for <code>GetHashCode()</code> looks like:</p>
<pre class="lang-cs prettyprint-override"><code> public override int GetHashCode()
{
unchecked
{
int result = (Key != null ? Key.GetHashCode() : 0);
result = (result * 397) ^ (EditableProperty != null ? EditableProperty.GetHashCode() : 0);
result = (result * 397) ^ ObjectId;
return result;
}
}
</code></pre>
<p>Of course I have some of my own members in there, but what I am wanting to know is why 397?</p>
<ul>
<li>EDIT: So my question would be better worded as, is there something 'special' about the 397 prime number outside of it being a prime number?</li>
</ul>
| [
{
"answer_id": 102878,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 8,
"selected": true,
"text": "<p>Probably because 397 is a prime of sufficient size to cause the result variable to overflow and mix the bits of the hash somewhat, providing a better distribution of hash codes. There's nothing particularly special about 397 that distinguishes it from other primes of the same magnitude.</p>\n"
},
{
"answer_id": 34154509,
"author": "kybernetikos",
"author_id": 412335,
"author_profile": "https://Stackoverflow.com/users/412335",
"pm_score": 4,
"selected": false,
"text": "<p>The hash that resharper uses looks like a variant of the <a href=\"https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function\" rel=\"noreferrer\">FNV</a> hash. FNV is frequently implemented with different primes. There's a discussion on the appropriate choice of primes for FNV <a href=\"http://www.isthe.com/chongo/tech/comp/fnv/#fnv-prime\" rel=\"noreferrer\">here</a>.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5289/"
]
| Like many of you, I use ReSharper to speed up the development process. When you use it to override the equality members of a class, the code-gen it produces for `GetHashCode()` looks like:
```cs
public override int GetHashCode()
{
unchecked
{
int result = (Key != null ? Key.GetHashCode() : 0);
result = (result * 397) ^ (EditableProperty != null ? EditableProperty.GetHashCode() : 0);
result = (result * 397) ^ ObjectId;
return result;
}
}
```
Of course I have some of my own members in there, but what I am wanting to know is why 397?
* EDIT: So my question would be better worded as, is there something 'special' about the 397 prime number outside of it being a prime number? | Probably because 397 is a prime of sufficient size to cause the result variable to overflow and mix the bits of the hash somewhat, providing a better distribution of hash codes. There's nothing particularly special about 397 that distinguishes it from other primes of the same magnitude. |
102,759 | <p>Everyone has accidentally forgotten the <code>WHERE</code> clause on a <code>DELETE</code> query and blasted some un-backed up data once or twice. I was pondering that problem, and I was wondering if the solution I came up with is practical.</p>
<p>What if, in place of actual <code>DELETE</code> queries, the application and maintenance scripts did something like:</p>
<pre><code>UPDATE foo SET to_be_deleted=1 WHERE blah = 50;
</code></pre>
<p>And then a cron job was set to go through and actually delete everything with the flag? The downside would be that pretty much every other query would need to have <code>WHERE to_be_deleted != 1</code> appended to it, but the upside would be that you'd never mistakenly lose data again. You could see "2,349,325 rows affected" and say, "Hmm, looks like I forgot the <code>WHERE</code> clause," and reset the flags. You could even make the to_be_deleted field a <code>DATE</code> column, so the cron job would check to see if a row's time had come yet.</p>
<p>Also, you could remove <code>DELETE</code> permission from the production database user, so even if someone managed to inject some SQL into your site, they wouldn't be able to remove anything.</p>
<p>So, my question is: Is this a good idea, or are there pitfalls I'm not seeing? </p>
| [
{
"answer_id": 102809,
"author": "Ken Ray",
"author_id": 12253,
"author_profile": "https://Stackoverflow.com/users/12253",
"pm_score": 1,
"selected": false,
"text": "<p>You could set up a view on that table that selects WHERE to_be_deleted != 1, and all of your normal selects are done on that view - that avoids having to put the WHERE on all of your queries.</p>\n"
},
{
"answer_id": 102814,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 0,
"selected": false,
"text": "<p>The pitfall is that it's unnecessarily complicated and someone will inadvertently forget too check the flag in their query. There's also the issue of potentially needing to delete something immediately instead of wait for the scheduled job to run.</p>\n"
},
{
"answer_id": 102825,
"author": "Aaron Smith",
"author_id": 12969,
"author_profile": "https://Stackoverflow.com/users/12969",
"pm_score": 0,
"selected": false,
"text": "<p>To avoid the to_be_deleted WHERE clause you could create a trigger before the delete command fires off to insert the deleted rows into a separate table. This table could be cleared out when you're sure everything in it really needs to be deleted, or you could keep it around for archive purposes.</p>\n"
},
{
"answer_id": 102826,
"author": "Arthur Thomas",
"author_id": 14009,
"author_profile": "https://Stackoverflow.com/users/14009",
"pm_score": 3,
"selected": true,
"text": "<p>That is fine if you want to do that, but it seems like a lot of work. How many people are manually changing the database? It should be very few, especially if your users have an app to work with.</p>\n\n<p>When I work on the production db I put EVERYTHING I do in a transaction so if I mess up I can rollback. Just having a standard practice like that for me has helped me.</p>\n\n<p>I don't see anything really wrong with that though other than ever single point of data manipulation in each applicaiton will have to be aware of this functionality and not just the data it wants.</p>\n"
},
{
"answer_id": 102844,
"author": "micahwittman",
"author_id": 11181,
"author_profile": "https://Stackoverflow.com/users/11181",
"pm_score": 0,
"selected": false,
"text": "<p>You also get a \"soft delete\" feature so you can give the(certain) end-users the power of \"undo\" - there would have to be a pretty strong downside in the mix to cancel the benefits of soft deleting.</p>\n"
},
{
"answer_id": 102845,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>This would be fine as long as your appliction does not require that the data is immediately deleted since you have to wait for the next interval of the cron job.</p>\n\n<p>I think a better solution and the more common practice is to use a development server and a production server. If your development database gets blown out, simply reload it. No harm done. If you're testing code on your production database, you deserve anything bad that happens.</p>\n"
},
{
"answer_id": 102861,
"author": "Cervo",
"author_id": 16219,
"author_profile": "https://Stackoverflow.com/users/16219",
"pm_score": 2,
"selected": false,
"text": "<p>A lot of people have a delete flag or a row status flag. But if someone is doing a change through the back end (and they will be doing it since often people need batch changes done that can't be accomplished through the front end) and they make a mistake they will still often go for delete. Ultimately this is no substitute for testing the script before applying it to a production environment.</p>\n\n<p>Also...what happens if the following query gets executed \"UPDATE foo SET to_be_deleted=1\" because they left off the where clause. Unless you have auditing columns with a time stamp how do you know which columns were deleted and which ones were done in error? But even if you have auditing columns with a time stamp, if the auditing is done via a stored procedure or programmer convention then these back end queries may not supply information letting you know that they were just applied.</p>\n"
},
{
"answer_id": 102872,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 2,
"selected": false,
"text": "<p>Too complicated. The standard approach to this is to do all your work inside a transaction, so if you screw up and forget a WHERE clause, then you simply roll back when you see the \"2,349,325 rows affected\" result.</p>\n"
},
{
"answer_id": 102876,
"author": "Pseudo Masochist",
"author_id": 8529,
"author_profile": "https://Stackoverflow.com/users/8529",
"pm_score": 0,
"selected": false,
"text": "<p>The \"WHERE to_be_deleted <> 1\" on every other query is a huge one. Another is once you've ran your accidentally rogue query, how will you determine which of the 2,349,325 were <em>previously</em> marked as deleted?</p>\n\n<p>I think the practical solution is regular backups, and failing that, perhaps a delete trigger that captures the tuples to be axed.</p>\n"
},
{
"answer_id": 102915,
"author": "yukondude",
"author_id": 726,
"author_profile": "https://Stackoverflow.com/users/726",
"pm_score": 2,
"selected": false,
"text": "<p>It may be easier to create a parallel table for deleted rows. A <code>DELETE</code> trigger (and <code>UPDATE</code> too if you want to undo changes as well) on the original table could copy the affected rows to the parallel table. Adding a datetime column to the parallel table to record the date & time of the change would let you permanently remove rows past a certain age using your cron job.</p>\n\n<p>That way, you'd use normal <code>DELETE</code> statements on the original table, so there's no chance you'll forget to run your special \"<code>DELETE</code>\" statement. You also sidestep the <code>to_be_deleted != 1</code> expression, which is just a bug waiting to happen when someone inevitably forgets.</p>\n"
},
{
"answer_id": 102926,
"author": "jinsungy",
"author_id": 1316,
"author_profile": "https://Stackoverflow.com/users/1316",
"pm_score": 0,
"selected": false,
"text": "<p>The other option would be to create a delete trigger on each table. When anything is deleted, it would insert that \"to be deleted\" record into another table, ideally named TABLENAME_deleted. </p>\n\n<p>The downside would be that the db would have twice as many tables. </p>\n\n<p>I don't recommend triggers in general, but it might be what you are looking for.</p>\n"
},
{
"answer_id": 102933,
"author": "user11318",
"author_id": 11318,
"author_profile": "https://Stackoverflow.com/users/11318",
"pm_score": 0,
"selected": false,
"text": "<p>This is why, whenever you are editing data by hand, you should BEGIN TRAN, edit your data, check that it looks good (for instance that you didn't delete more data than you were expecting) and then END TRAN. If you're using Postgres then you want to create lots of savepoints as well so that a typo doesn't wipe out your intermediate work.</p>\n\n<p>But that said, in many applications it does make sense to have software mark records as invalid rather than deleting them. Add a last_modified date that is automatically updated, and you are all prepared to set up incremental updates into a data warehouse. Even if you don't have a data warehouse <strong>now</strong>, it never hurts to prepare for the future when preparing is cheap. Plus in the event of manual mistakes you still have the data, and can just find all of the records that got \"deleted\" when you made your mistake and fix them. (You should still use transactions though.)</p>\n"
},
{
"answer_id": 102938,
"author": "Mike McAllister",
"author_id": 16247,
"author_profile": "https://Stackoverflow.com/users/16247",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like you're describing three cases here.</p>\n\n<ol>\n<li><p>Case 1 - maintenance scripts. Risk can be minimized by developing them and testing them in an environment other than your production box. For quick maintenance, do the maintenance in a single transaction, and check everything before committing. If you made a mistake, issue the rollback command. For more serious maintenance that you can't necessarily wait around for, or do in a single transaction, consider taking a backup directly before running the maintenance job, so that you can always restore back to the point before you ran your script if you encounter serious problems.</p></li>\n<li><p>Case 2 - SQL Injection. This is an architecture issue. Your application shouldn't pass SQL into the database, access should be controlled through packages / stored procedures / functions, and values that are going to come from the UI and be used in a DDL statement should be applied using bind variables, rather than by creating dynamic SQL by appending strings together.</p></li>\n<li><p>Case 3 - Regular batch jobs. These should have been tested before being deployed to production. If you delete too much, you have a bug, and are going to have to rely on your backup strategy.</p></li>\n</ol>\n"
},
{
"answer_id": 105978,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Everyone has accidentally forgotten\n the WHERE clause on a DELETE query and\n blasted some un-backed up data once or\n twice.</p>\n</blockquote>\n\n<p>No. I always prototype my <code>DELETE</code>s as <code>SELECT</code>s and only if the latter gives the results I want to delete change the statement before <code>WHERE</code> to a <code>DELETE</code>. This let's me inspect in any needed detail the rows I want to affect before doing anything.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102759",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16034/"
]
| Everyone has accidentally forgotten the `WHERE` clause on a `DELETE` query and blasted some un-backed up data once or twice. I was pondering that problem, and I was wondering if the solution I came up with is practical.
What if, in place of actual `DELETE` queries, the application and maintenance scripts did something like:
```
UPDATE foo SET to_be_deleted=1 WHERE blah = 50;
```
And then a cron job was set to go through and actually delete everything with the flag? The downside would be that pretty much every other query would need to have `WHERE to_be_deleted != 1` appended to it, but the upside would be that you'd never mistakenly lose data again. You could see "2,349,325 rows affected" and say, "Hmm, looks like I forgot the `WHERE` clause," and reset the flags. You could even make the to\_be\_deleted field a `DATE` column, so the cron job would check to see if a row's time had come yet.
Also, you could remove `DELETE` permission from the production database user, so even if someone managed to inject some SQL into your site, they wouldn't be able to remove anything.
So, my question is: Is this a good idea, or are there pitfalls I'm not seeing? | That is fine if you want to do that, but it seems like a lot of work. How many people are manually changing the database? It should be very few, especially if your users have an app to work with.
When I work on the production db I put EVERYTHING I do in a transaction so if I mess up I can rollback. Just having a standard practice like that for me has helped me.
I don't see anything really wrong with that though other than ever single point of data manipulation in each applicaiton will have to be aware of this functionality and not just the data it wants. |
102,850 | <p>Doesn't work with other modules, but to give an example. I installed Text::CSV_XS with a CPAN setting:</p>
<pre><code>'makepl_arg' => q[PREFIX=~/lib],
</code></pre>
<p>When I try running a test.pl script:</p>
<blockquote>
<p>$ perl test.pl</p>
</blockquote>
<pre><code>#!/usr/bin/perl
use lib "/homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi";
use Text::CSV_XS;
print "test";
</code></pre>
<p>I get</p>
<pre>
Can't load '/homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi/auto/Text/CSV_XS/CSV_XS.so' for module Text::CSV_XS: /homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi/auto/Text/CSV_XS/CSV_XS.so: cannot open shared object file: No such file or directory at /www/common/perl/lib/5.8.2/i686-linux/DynaLoader.pm line 229.
at test.pl line 6
Compilation failed in require at test.pl line 6.
BEGIN failed--compilation aborted at test.pl line 6.
</pre>
<p>I traced the error back to DynaLoader.pm it happens at this line:</p>
<pre><code># Many dynamic extension loading problems will appear to come from
# this section of code: XYZ failed at line 123 of DynaLoader.pm.
# Often these errors are actually occurring in the initialisation
# C code of the extension XS file. Perl reports the error as being
# in this perl code simply because this was the last perl code
# it executed.
my $libref = dl_load_file($file, $module->dl_load_flags) or
croak("Can't load '$file' for module $module: ".dl_error());
</code></pre>
<p><b>CSV_XS.so exists in the above directory</b></p>
| [
{
"answer_id": 103018,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 2,
"selected": false,
"text": "<p>Try this instead:</p>\n\n<pre><code>'makepl_arg' => q[PREFIX=~/]\n</code></pre>\n\n<p>PREFIX sets the base for all the directories you will be installing into (bin, lib, and so forth.)</p>\n\n<p>You may also be running into shell expansion problems with your '~'. You can try to expand it yourself:</p>\n\n<pre><code>'makepl_arg' => q[PREFIX=/home/users/foobar]\n</code></pre>\n\n<p>It would also be helpful if you included the commands you used to get the error you are asking about.</p>\n"
},
{
"answer_id": 103501,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 0,
"selected": false,
"text": "<p>Does the file in question (CSV_XS.so) exist?</p>\n\n<p>Does it exist at the listed location?</p>\n\n<p>If you do:</p>\n\n<pre><code>set |grep PERL\n</code></pre>\n\n<p>What is the output?</p>\n\n<p>Have you successfully installed other local perl modules?</p>\n"
},
{
"answer_id": 103987,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 3,
"selected": false,
"text": "<p>When you installed the module, did you watch the output? Where did it say it installed the module? Look in <i>lib</i>. Do you see the next directory you expect?</p>\n<p>Look in ~/lib to see where eveything ended up to verify that you have the right directory name in your <code>use lib</code> statement:</p>\n<pre><code>% find ~/lib -name CSV_XS.so\n</code></pre>\n<p>Once you see where it is installed, use that directory name in your <code>use lib</code> (or PERL5LIB or whatever).</p>\n<p>I expect you have a <code>lib/lib</code> in there somehow. The <code>PREFIX</code> is just the, well, prefix, and the installer appends other directory portions to that base path. That includes lib, man, bin, <i>etc</i>.</p>\n"
},
{
"answer_id": 105440,
"author": "skiphoppy",
"author_id": 18103,
"author_profile": "https://Stackoverflow.com/users/18103",
"pm_score": 0,
"selected": false,
"text": "<p>I strongly suggest installing your own perl in your own home directory, if you have space. Then you can keep everything under your control and keep your own module set, as well as escaping if the admins are keeping you on an older version of perl. (Not to mention preserving yourself if they upgrade some day and leave out all the modules you are relying on.)</p>\n"
},
{
"answer_id": 273967,
"author": "Sherm Pendley",
"author_id": 27631,
"author_profile": "https://Stackoverflow.com/users/27631",
"pm_score": 1,
"selected": false,
"text": "<p>It looks from the error message (\"at /www/common ...\") that your script is a CGI or mod_perl script. The web server is probably not running as the user 'foo', under whose home directory you've installed the module - that could result in the web server being unable to read that directory.</p>\n\n<p>It may also be running in a \"<a href=\"http://en.wikipedia.org/wiki/Chroot_jail\" rel=\"nofollow noreferrer\">chroot jail</a>\", which would mean that the directory in which you've installed the module may not be visible to the script.</p>\n\n<p>In other words, just because <em>you</em> can see the module, does not mean that the web server, and therefore your script, can do so. You should check the relevant file permissions, and if the server is chrooted, whether your module directory is mounted within the virtual file system.</p>\n"
},
{
"answer_id": 471533,
"author": "Fayland Lam",
"author_id": 55276,
"author_profile": "https://Stackoverflow.com/users/55276",
"pm_score": 3,
"selected": true,
"text": "<p>Personally I would suggest to use <a href=\"http://search.cpan.org/dist/local-lib/\" rel=\"nofollow noreferrer\">local::lib</a>. :)</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10523/"
]
| Doesn't work with other modules, but to give an example. I installed Text::CSV\_XS with a CPAN setting:
```
'makepl_arg' => q[PREFIX=~/lib],
```
When I try running a test.pl script:
>
> $ perl test.pl
>
>
>
```
#!/usr/bin/perl
use lib "/homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi";
use Text::CSV_XS;
print "test";
```
I get
```
Can't load '/homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi/auto/Text/CSV_XS/CSV_XS.so' for module Text::CSV_XS: /homes/foobar/lib/lib64/perl5/site_perl/5.8.8/x86_64-linux-thread-multi/auto/Text/CSV_XS/CSV_XS.so: cannot open shared object file: No such file or directory at /www/common/perl/lib/5.8.2/i686-linux/DynaLoader.pm line 229.
at test.pl line 6
Compilation failed in require at test.pl line 6.
BEGIN failed--compilation aborted at test.pl line 6.
```
I traced the error back to DynaLoader.pm it happens at this line:
```
# Many dynamic extension loading problems will appear to come from
# this section of code: XYZ failed at line 123 of DynaLoader.pm.
# Often these errors are actually occurring in the initialisation
# C code of the extension XS file. Perl reports the error as being
# in this perl code simply because this was the last perl code
# it executed.
my $libref = dl_load_file($file, $module->dl_load_flags) or
croak("Can't load '$file' for module $module: ".dl_error());
```
**CSV\_XS.so exists in the above directory** | Personally I would suggest to use [local::lib](http://search.cpan.org/dist/local-lib/). :) |
102,881 | <p>I am running some queries to track down a problem with our backup logs and would like to display datetime fields in 24-hour military time. Is there a simple way to do this? I've tried googling and could find nothing.</p>
| [
{
"answer_id": 102906,
"author": "Nick Craver",
"author_id": 13249,
"author_profile": "https://Stackoverflow.com/users/13249",
"pm_score": 0,
"selected": false,
"text": "<p>It's not oracle that determines the display of the date, it's the tool you're using to run queries. What are you using to display results? Then we can point you to the correct settings hopefully.</p>\n"
},
{
"answer_id": 102909,
"author": "Joe Skora",
"author_id": 14057,
"author_profile": "https://Stackoverflow.com/users/14057",
"pm_score": 5,
"selected": true,
"text": "<pre><code>select to_char(sysdate,'DD/MM/YYYY HH24:MI:SS') from dual;\n</code></pre>\n\n<p>Give the time in 24 hour format.</p>\n\n<p>More options are described <a href=\"http://www.oradev.com/oracle_date_format.jsp\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 102918,
"author": "Grant Johnson",
"author_id": 12518,
"author_profile": "https://Stackoverflow.com/users/12518",
"pm_score": 1,
"selected": false,
"text": "<p>Use a <code>to_char(field,'YYYYMMDD HH24MISS')</code>.</p>\n\n<p>A good list of date formats is available <a href=\"http://www.ss64.com/orasyntax/fmt.html\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 107044,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 2,
"selected": false,
"text": "<p>If you want all queries in your session to show the full datetime, then do</p>\n\n<pre><code>alter session set NLS_DATE_FORMAT='DD/MM/YYYY HH24:MI:SS'\n</code></pre>\n\n<p>at the start of your session.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
]
| I am running some queries to track down a problem with our backup logs and would like to display datetime fields in 24-hour military time. Is there a simple way to do this? I've tried googling and could find nothing. | ```
select to_char(sysdate,'DD/MM/YYYY HH24:MI:SS') from dual;
```
Give the time in 24 hour format.
More options are described [here](http://www.oradev.com/oracle_date_format.jsp). |
102,964 | <p>I have a Java bean like this:</p>
<pre><code>class Person {
int age;
String name;
}
</code></pre>
<p>I'd like to iterate over a collection of these beans in a JSP, showing each person in a HTML table row, and in the last row of the table I'd like to show the total of all the ages.</p>
<p>The code to generate the table rows will look something like this:</p>
<pre><code><c:forEach var="person" items="${personList}">
<tr><td>${person.name}<td><td>${person.age}</td></tr>
</c:forEach>
</code></pre>
<p>However, I'm struggling to find a way to calculate the age total that will be shown in the final row <strong>without resorting to scriptlet code</strong>, any suggestions?</p>
| [
{
"answer_id": 103009,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It's a bit hacky, but in your controller code you could just create a dummy Person object with the total in it!</p>\n\n<p>How are you retrieving your objects? HTML lets you set a <a href=\"http://www.w3schools.com/tags/tag_tfoot.asp\" rel=\"nofollow noreferrer\"><TFOOT></a> element which will sit at the bottom of any data you have, therefore you could just set the total separately from the Person objects and output it on the page as-is without any computation on the JSP page.</p>\n"
},
{
"answer_id": 103021,
"author": "zmf",
"author_id": 13285,
"author_profile": "https://Stackoverflow.com/users/13285",
"pm_score": 2,
"selected": false,
"text": "<p>Check out display tag. <a href=\"http://displaytag.sourceforge.net/11/tut_basic.html\" rel=\"nofollow noreferrer\">http://displaytag.sourceforge.net/11/tut_basic.html</a></p>\n"
},
{
"answer_id": 103065,
"author": "ScArcher2",
"author_id": 1310,
"author_profile": "https://Stackoverflow.com/users/1310",
"pm_score": 3,
"selected": false,
"text": "<p>Are you trying to add up all the ages?</p>\n\n<p>You could calculate it in your controller and only display the result in the jsp.</p>\n\n<p>You can write a custom tag to do the calculation.</p>\n\n<p>You can calculate it in the jsp using jstl like this.</p>\n\n<pre><code><c:set var=\"ageTotal\" value=\"${0}\" />\n<c:forEach var=\"person\" items=\"${personList}\">\n <c:set var=\"ageTotal\" value=\"${ageTotal + person.age}\" />\n <tr><td>${person.name}<td><td>${person.age}</td></tr>\n</c:forEach>\n${ageTotal}\n</code></pre>\n"
},
{
"answer_id": 103219,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 1,
"selected": false,
"text": "<p>ScArcher2 has the simplest <a href=\"https://stackoverflow.com/questions/102964/jstl-collection-iteration/103065#103065\">solution</a>. If you wanted something as compact as possible, you could create a tag library with a \"sum\" function in it. Something like:</p>\n\n<pre><code>class MySum {\npublic double sum(List list) {...}\n}\n</code></pre>\n\n<p>In your TLD:</p>\n\n<pre><code><function>\n<name>sum</name>\n<function-class>my.MySum</function-class>\n<function-signature>double sum(List)</function-signature>\n</function>\n</code></pre>\n\n<p>In your JSP, you'd have something like:</p>\n\n<pre><code><%@ taglib uri=\"/myfunc\" prefix=\"f\" %>\n\n${f:sum(personList)}\n</code></pre>\n"
},
{
"answer_id": 103973,
"author": "Jon-Erik",
"author_id": 15832,
"author_profile": "https://Stackoverflow.com/users/15832",
"pm_score": 6,
"selected": true,
"text": "<p><strong><em>Note:</strong> I tried combining answers to make a comprehensive list. I mentioned names where appropriate to give credit where it is due.</em></p>\n\n<p>There are many ways to solve this problem, with pros/cons associated with each:</p>\n\n<p><strong>Pure JSP Solution</strong></p>\n\n<p>As ScArcher2 mentioned above, a very easy and simple solution to the problem is to implement it directly in the JSP as so:</p>\n\n<pre><code><c:set var=\"ageTotal\" value=\"${0}\" />\n<c:forEach var=\"person\" items=\"${personList}\">\n <c:set var=\"ageTotal\" value=\"${ageTotal + person.age}\" />\n <tr><td>${person.name}<td><td>${person.age}</td></tr>\n</c:forEach>\n${ageTotal}\n</code></pre>\n\n<p>The problem with this solution is that the JSP becomes confusing to the point where you might as well have introduced scriplets. If you anticipate that everyone looking at the page will be able to follow the rudimentary logic present it is a fine choice.</p>\n\n<p><strong>Pure EL solution</strong></p>\n\n<p>If you're already on EL 3.0 (Java EE 7 / Servlet 3.1), use new support for <a href=\"http://docs.oracle.com/javaee/7/tutorial/jsf-el004.htm\" rel=\"noreferrer\">streams and lambdas</a>:</p>\n\n<pre><code><c:forEach var=\"person\" items=\"${personList}\">\n <tr><td>${person.name}<td><td>${person.age}</td></tr>\n</c:forEach>\n${personList.stream().map(person -> person.age).sum()}\n</code></pre>\n\n<p><strong>JSP EL Functions</strong></p>\n\n<p>Another way to output the total without introducing scriplet code into your JSP is to use an EL function. EL functions allow you to call a public static method in a public class. For example, if you would like to iterate over your collection and sum the values you could define a public static method called sum(List people) in a public class, perhaps called PersonUtils. In your tld file you would place the following declaration:</p>\n\n<pre><code><function>\n <name>sum</name>\n <function-class>com.example.PersonUtils</function-class>\n <function-signature>int sum(java.util.List people)</function-signature>\n</function> \n</code></pre>\n\n<p>Within your JSP you would write:</p>\n\n<pre><code><%@ taglib prefix=\"f\" uri=\"/your-tld-uri\"%>\n...\n<c:out value=\"${f:sum(personList)}\"/>\n</code></pre>\n\n<p>JSP EL Functions have a few benefits. They allow you to use existing Java methods without the need to code to a specific UI (Custom Tag Libraries). They are also compact and will not confuse a non-programming oriented person.</p>\n\n<p><strong>Custom Tag</strong> </p>\n\n<p>Yet another option is to roll your own custom tag. This option will involve the most setup but will give you what I think you are esentially looking for, absolutly no scriptlets. A nice tutorial for using simple custom tags can be found at <a href=\"http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags5.html#74701\" rel=\"noreferrer\">http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags5.html#74701</a></p>\n\n<p>The steps involved include subclassing TagSupport:</p>\n\n<pre><code>public PersonSumTag extends TagSupport {\n\n private List personList;\n\n public List getPersonList(){\n return personList;\n }\n\n public void setPersonList(List personList){\n this.personList = personList;\n }\n\n public int doStartTag() throws JspException {\n try {\n int sum = 0;\n for(Iterator it = personList.iterator(); it.hasNext()){\n Person p = (Person)it.next();\n sum+=p.getAge();\n } \n pageContext.getOut().print(\"\"+sum);\n } catch (Exception ex) {\n throw new JspTagException(\"SimpleTag: \" + \n ex.getMessage());\n }\n return SKIP_BODY;\n }\n public int doEndTag() {\n return EVAL_PAGE;\n }\n}\n</code></pre>\n\n<p>Define the tag in a tld file:</p>\n\n<pre><code><tag>\n <name>personSum</name>\n <tag-class>example.PersonSumTag</tag-class>\n <body-content>empty</body-content>\n ...\n <attribute>\n <name>personList</name>\n <required>true</required>\n <rtexprvalue>true</rtexprvalue>\n <type>java.util.List</type>\n </attribute>\n ...\n</tag>\n</code></pre>\n\n<p>Declare the taglib on the top of your JSP:</p>\n\n<pre><code><%@ taglib uri=\"/you-taglib-uri\" prefix=\"p\" %>\n</code></pre>\n\n<p>and use the tag:</p>\n\n<pre><code><c:forEach var=\"person\" items=\"${personList}\">\n <tr><td>${person.name}<td><td>${person.age}</td></tr>\n</c:forEach>\n<p:personSum personList=\"${personList}\"/>\n</code></pre>\n\n<p><strong>Display Tag</strong></p>\n\n<p>As zmf mentioned earlier, you could also use the display tag, although you will need to include the appropriate libraries:</p>\n\n<p><a href=\"http://displaytag.sourceforge.net/11/tut_basic.html\" rel=\"noreferrer\">http://displaytag.sourceforge.net/11/tut_basic.html</a></p>\n"
},
{
"answer_id": 10442349,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>you can iterate over a collection using JSTL according to following</p>\n\n<pre><code><c:forEach items=\"${numList}\" var=\"item\">\n ${item}\n</c:forEach>\n</code></pre>\n\n<p>if it is a map you can do on the following</p>\n\n<pre><code><c:forEach items=\"${numMap}\" var=\"entry\">\n ${entry.key},${entry.value}<br/>\n</c:forEach>\n</code></pre>\n"
},
{
"answer_id": 15715507,
"author": "Thomas W",
"author_id": 768795,
"author_profile": "https://Stackoverflow.com/users/768795",
"pm_score": 0,
"selected": false,
"text": "<p>Calculating Totals/ or other summaries in the controller -- not in the JSP -- is really strongly preferable.</p>\n\n<p>Use Java code & an MVC approach, eg Spring MVC framework, instead of trying to do too much in JSP or JSTL; doing significant calculation in these languages is weak & slow, and makes your JSP pages much less clear.</p>\n\n<p>Example:</p>\n\n<pre><code>class PersonList_Controller implements Controller {\n ...\n protected void renderModel (List<Person> items, Map model) {\n int totalAge = 0;\n for (Person person : items) {\n totalAge += person.getAge();\n }\n model.put(\"items\", items);\n model.put(\"totalAge\", totalAge);\n }\n}\n</code></pre>\n\n<p>Design decision-wise -- anywhere a total is required, could conceivably next month be extended to require an average, a median, a standard deviation.</p>\n\n<p>JSTL calculations & summarization are scarcely holding together, in just getting a total. Are you really going to want to meet any further summary requirements in JSTL? I believe the answer is NO -- and that therefore the correct design decision is to calculate in the Controller, as equally/ more simple and definitely more plausible-requirements extensible.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/102964",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
]
| I have a Java bean like this:
```
class Person {
int age;
String name;
}
```
I'd like to iterate over a collection of these beans in a JSP, showing each person in a HTML table row, and in the last row of the table I'd like to show the total of all the ages.
The code to generate the table rows will look something like this:
```
<c:forEach var="person" items="${personList}">
<tr><td>${person.name}<td><td>${person.age}</td></tr>
</c:forEach>
```
However, I'm struggling to find a way to calculate the age total that will be shown in the final row **without resorting to scriptlet code**, any suggestions? | ***Note:*** I tried combining answers to make a comprehensive list. I mentioned names where appropriate to give credit where it is due.
There are many ways to solve this problem, with pros/cons associated with each:
**Pure JSP Solution**
As ScArcher2 mentioned above, a very easy and simple solution to the problem is to implement it directly in the JSP as so:
```
<c:set var="ageTotal" value="${0}" />
<c:forEach var="person" items="${personList}">
<c:set var="ageTotal" value="${ageTotal + person.age}" />
<tr><td>${person.name}<td><td>${person.age}</td></tr>
</c:forEach>
${ageTotal}
```
The problem with this solution is that the JSP becomes confusing to the point where you might as well have introduced scriplets. If you anticipate that everyone looking at the page will be able to follow the rudimentary logic present it is a fine choice.
**Pure EL solution**
If you're already on EL 3.0 (Java EE 7 / Servlet 3.1), use new support for [streams and lambdas](http://docs.oracle.com/javaee/7/tutorial/jsf-el004.htm):
```
<c:forEach var="person" items="${personList}">
<tr><td>${person.name}<td><td>${person.age}</td></tr>
</c:forEach>
${personList.stream().map(person -> person.age).sum()}
```
**JSP EL Functions**
Another way to output the total without introducing scriplet code into your JSP is to use an EL function. EL functions allow you to call a public static method in a public class. For example, if you would like to iterate over your collection and sum the values you could define a public static method called sum(List people) in a public class, perhaps called PersonUtils. In your tld file you would place the following declaration:
```
<function>
<name>sum</name>
<function-class>com.example.PersonUtils</function-class>
<function-signature>int sum(java.util.List people)</function-signature>
</function>
```
Within your JSP you would write:
```
<%@ taglib prefix="f" uri="/your-tld-uri"%>
...
<c:out value="${f:sum(personList)}"/>
```
JSP EL Functions have a few benefits. They allow you to use existing Java methods without the need to code to a specific UI (Custom Tag Libraries). They are also compact and will not confuse a non-programming oriented person.
**Custom Tag**
Yet another option is to roll your own custom tag. This option will involve the most setup but will give you what I think you are esentially looking for, absolutly no scriptlets. A nice tutorial for using simple custom tags can be found at <http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/JSPTags5.html#74701>
The steps involved include subclassing TagSupport:
```
public PersonSumTag extends TagSupport {
private List personList;
public List getPersonList(){
return personList;
}
public void setPersonList(List personList){
this.personList = personList;
}
public int doStartTag() throws JspException {
try {
int sum = 0;
for(Iterator it = personList.iterator(); it.hasNext()){
Person p = (Person)it.next();
sum+=p.getAge();
}
pageContext.getOut().print(""+sum);
} catch (Exception ex) {
throw new JspTagException("SimpleTag: " +
ex.getMessage());
}
return SKIP_BODY;
}
public int doEndTag() {
return EVAL_PAGE;
}
}
```
Define the tag in a tld file:
```
<tag>
<name>personSum</name>
<tag-class>example.PersonSumTag</tag-class>
<body-content>empty</body-content>
...
<attribute>
<name>personList</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>java.util.List</type>
</attribute>
...
</tag>
```
Declare the taglib on the top of your JSP:
```
<%@ taglib uri="/you-taglib-uri" prefix="p" %>
```
and use the tag:
```
<c:forEach var="person" items="${personList}">
<tr><td>${person.name}<td><td>${person.age}</td></tr>
</c:forEach>
<p:personSum personList="${personList}"/>
```
**Display Tag**
As zmf mentioned earlier, you could also use the display tag, although you will need to include the appropriate libraries:
<http://displaytag.sourceforge.net/11/tut_basic.html> |
103,000 | <p>I need to retrieve a record from a database, display it on a web page (I'm using ASP.NET) but store the ID (primary key) from that record somewhere so I can go back to the database later with that ID (perhaps to do an update).</p>
<p>I know there are probably a few ways to do this, such as storing the ID in ViewState or a hidden field, but what is the best method and what are the reasons I might choose this method over any others?</p>
| [
{
"answer_id": 103024,
"author": "Chris James",
"author_id": 3193,
"author_profile": "https://Stackoverflow.com/users/3193",
"pm_score": -1,
"selected": false,
"text": "<pre><code>Session[\"MyId\"]=myval;\n</code></pre>\n\n<p>It would be a little safer and essentially offers the same mechanics as putting it in the viewstate</p>\n"
},
{
"answer_id": 103042,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 0,
"selected": false,
"text": "<p>ViewState is an option. It is only valid for the page that you are on. It does not carry across requests to other resources like the Session object.</p>\n\n<p>Hidden fields work too, but you are leaking and little bit of information about your application to anyone smart enough to view the source of your page.</p>\n\n<p>You could also store your entire record in ViewState and maybe avoid another round trip to th server.</p>\n"
},
{
"answer_id": 103073,
"author": "Mike Becatti",
"author_id": 6617,
"author_profile": "https://Stackoverflow.com/users/6617",
"pm_score": 0,
"selected": false,
"text": "<p>I personally am very leery about putting anything in the session. Too many times our worker processes have cycled and we lost our session state. </p>\n\n<p>As you described your problem, I would put it in a hidden field or in the viewstate of the page. </p>\n\n<p>Also, when determining where to put data like this, always look at the scope of the data. Is it scoped to a single page, or to the entire session? If the answer is 'session' for us, we put it in a cookie. (Disclaimer: We write intranet apps where we know cookies are enabled.)</p>\n"
},
{
"answer_id": 103103,
"author": "blowdart",
"author_id": 2525,
"author_profile": "https://Stackoverflow.com/users/2525",
"pm_score": 4,
"selected": true,
"text": "<p>It depends.</p>\n\n<p>Do you care if anyone sees the record id? If you do then both hidden fields and viewstate are not suitable; you need to store it in session state, or encrypt viewstate.</p>\n\n<p>Do you care if someone submits the form with a bogus id? If you do then you can't use a hidden field (and you need to look at CSRF protection as a bonus)</p>\n\n<p>Do you want it unchangable but don't care about it being open to viewing (with some work)? Use viewstate and set enableViewStateMac=\"true\" on your page (or globally)</p>\n\n<p>Want it hidden and protected but can't use session state? Encrypt your viewstate by setting the following web.config entries</p>\n\n<pre><code><pages enableViewState=\"true\" enableViewStateMac=\"true\" />\n<machineKey ... validation=\"3DES\" />\n</code></pre>\n"
},
{
"answer_id": 103124,
"author": "Loofer",
"author_id": 5552,
"author_profile": "https://Stackoverflow.com/users/5552",
"pm_score": -1,
"selected": false,
"text": "<p>I tend to stick things like that in hidden fields just do a little</p>\n\n<pre><code> <asp:label runat=server id=lblThingID visible=false />\n</code></pre>\n"
},
{
"answer_id": 103141,
"author": "Claus Thomsen",
"author_id": 15555,
"author_profile": "https://Stackoverflow.com/users/15555",
"pm_score": 0,
"selected": false,
"text": "<p>If its a simple id will choose to pass it in querystring, that way you do not need to do postbacks and page is more accessible for users and search engines.</p>\n"
},
{
"answer_id": 103145,
"author": "digiguru",
"author_id": 5055,
"author_profile": "https://Stackoverflow.com/users/5055",
"pm_score": 2,
"selected": false,
"text": "<p>Do you want the end user to know the ID? For example if the id value is a standard 1,1 seed from the database I could look at the number and see how many customers you have. If you encrypt the value (as the viewstate can) I would find it much harder to decypher the key (but not impossible). </p>\n\n<p>The alternative is to store it in the session, this will put a (very small if its just an integer) performance hit on your application but mean that I as a user never see that primary key. It also exposes the object to other parts of your application, that you may or may not want it to be exposed to (session objects remain until cleared, a set time (like 5 mins) passes or the browser window is closed - whichever happens sooner.</p>\n\n<p>View state values cause extra load on the client after every post back, because the viewstate not only saves objects for the page, but remembers objects if you use the back button. That means after every post back it viewstate gets slightly bigger and harder to use. They will only exist on he page until the browser goes to another page.</p>\n\n<p>Whenever I store an ID in the page like this, I always create a property </p>\n\n<pre><code>public int CustomerID {\n get { return ViewState(\"CustomerID\"); }\n set { ViewState(\"CustomerID\") = value; }\n}\n</code></pre>\n\n<p>or</p>\n\n<pre><code> Public Property CustomerID() As Integer\n Get\n Return ViewState(\"CustomerID\")\n End Get\n Set(ByVal value As Integer)\n ViewState(\"CustomerID\") = value\n End Set\n End Property\n</code></pre>\n\n<p>That way if you decide to change it from Viewstate to a session variable or a hidden form field, it's just a case of changing it in the property reference, the rest of the page can access the variable using \"Page.CustomerID\".</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103000",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4605/"
]
| I need to retrieve a record from a database, display it on a web page (I'm using ASP.NET) but store the ID (primary key) from that record somewhere so I can go back to the database later with that ID (perhaps to do an update).
I know there are probably a few ways to do this, such as storing the ID in ViewState or a hidden field, but what is the best method and what are the reasons I might choose this method over any others? | It depends.
Do you care if anyone sees the record id? If you do then both hidden fields and viewstate are not suitable; you need to store it in session state, or encrypt viewstate.
Do you care if someone submits the form with a bogus id? If you do then you can't use a hidden field (and you need to look at CSRF protection as a bonus)
Do you want it unchangable but don't care about it being open to viewing (with some work)? Use viewstate and set enableViewStateMac="true" on your page (or globally)
Want it hidden and protected but can't use session state? Encrypt your viewstate by setting the following web.config entries
```
<pages enableViewState="true" enableViewStateMac="true" />
<machineKey ... validation="3DES" />
``` |
103,005 | <p>Here is my situation:</p>
<p>Table one contains a set of data that uses an id for an unique identifier. This table has a one to many relationship with about 6 other tables such that.</p>
<p>Given Table 1 with Id of 001:
Table 2 might have 3 rows with foreign key: 001
Table 3 might have 12 rows with foreign key: 001
Table 4 might have 0 rows with foreign key: 001
Table 5 might have 28 rows with foreign key: 001</p>
<p>I need to write a report that lists all of the rows from Table 1 for a specified time frame followed by all of the data contained in the handful of tables that reference it.</p>
<p>My current approach in pseudo code would look like this:</p>
<pre><code>select * from table 1
foreach(result) {
print result;
select * from table 2 where id = result.id;
foreach(result2) {
print result2;
}
select * from table 3 where id = result.id
foreach(result3) {
print result3;
}
//continued for each table
}
</code></pre>
<p>This means that the single report can run in the neighbor hood of 1000 queries. I know this is excessive however my sql-fu is a little weak and I could use some help. </p>
| [
{
"answer_id": 103044,
"author": "Forgotten Semicolon",
"author_id": 1960,
"author_profile": "https://Stackoverflow.com/users/1960",
"pm_score": 2,
"selected": false,
"text": "<p>LEFT OUTER JOIN Tables2-N on Table1</p>\n\n<pre><code>SELECT Table1.*, Table2.*, Table3.*, Table4.*, Table5.*\nFROM Table1\nLEFT OUTER JOIN Table2 ON Table1.ID = Table2.ID\nLEFT OUTER JOIN Table3 ON Table1.ID = Table3.ID\nLEFT OUTER JOIN Table4 ON Table1.ID = Table4.ID\nLEFT OUTER JOIN Table5 ON Table1.ID = Table5.ID\nWHERE (CRITERIA)\n</code></pre>\n"
},
{
"answer_id": 103048,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 1,
"selected": false,
"text": "<p>Ah! Procedural! My SQL would look like this, if you needed to order the results from the other tables after the results from the first table.</p>\n\n<blockquote>\n<pre><code>Insert Into #rows Select id from Table1 where date between '12/30' and '12/31'\nSelect * from Table1 t join #rows r on t.id = r.id\nSelect * from Table2 t join #rows r on t.id = r.id\n--etc\n</code></pre>\n</blockquote>\n\n<p>If you wanted to group the results by the initial ID, use a Left Outer Join, as mentioned previously.</p>\n"
},
{
"answer_id": 103056,
"author": "Grant Johnson",
"author_id": 12518,
"author_profile": "https://Stackoverflow.com/users/12518",
"pm_score": 1,
"selected": false,
"text": "<p>You may be best off to use a reporting tool like Crystal or Jasper, or even XSL-FO if you are feeling bold. They have things built in to handle specifically this. This is not something the would work well in raw SQL.</p>\n\n<p>If the format of all of the rows (the headers as well as all of the details) is the same, it would also be pretty easy to do it as a stored procedure.</p>\n\n<p>What I would do: Do it as a join, so you will have the header data on every row, then use a reporting tool to do the grouping.</p>\n"
},
{
"answer_id": 103067,
"author": "Josh Bush",
"author_id": 1672,
"author_profile": "https://Stackoverflow.com/users/1672",
"pm_score": 0,
"selected": false,
"text": "<p>Join all of the tables together.</p>\n\n<pre><code>select * from table_1 left join table_2 using(id) left join table_3 using(id);\n</code></pre>\n\n<p>Then, you'll want to roll up the columns in code to format your report as you see fit.</p>\n"
},
{
"answer_id": 103109,
"author": "evilhomer",
"author_id": 2806,
"author_profile": "https://Stackoverflow.com/users/2806",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT * FROM table1 t1\nINNER JOIN table2 t2 ON t1.id = t2.resultid -- this could be a left join if the table is not guaranteed to have entries for t1.id\nINNER JOIN table2 t3 ON t1.id = t3.resultid -- etc\n</code></pre>\n\n<p>OR if the data is all in the same format you could do.</p>\n\n<pre><code>SELECT cola,colb FROM table1 WHERE id = @id\nUNION ALL\nSELECT cola,colb FROM table2 WHERE resultid = @id\nUNION ALL\nSELECT cola,colb FROM table3 WHERE resultid = @id\n</code></pre>\n\n<p>It really depends on the format you require the data in for output to the report.</p>\n\n<p>If you can give a sample of how you would like the output I could probably help more.</p>\n"
},
{
"answer_id": 103137,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": false,
"text": "<p>Join doesn't do it for me. I hate having to de-tangle the data on the client side. All those nulls from left-joining.</p>\n\n<p>Here's a set-based solution that doesn't use Joins.</p>\n\n<pre><code>INSERT INTO @LocalCollection (theKey)\nSELECT id\nFROM Table1\nWHERE ...\n\n\nSELECT * FROM Table1 WHERE id in (SELECT theKey FROM @LocalCollection)\n\nSELECT * FROM Table2 WHERE id in (SELECT theKey FROM @LocalCollection)\n\nSELECT * FROM Table3 WHERE id in (SELECT theKey FROM @LocalCollection)\n\nSELECT * FROM Table4 WHERE id in (SELECT theKey FROM @LocalCollection)\n\nSELECT * FROM Table5 WHERE id in (SELECT theKey FROM @LocalCollection)\n</code></pre>\n"
},
{
"answer_id": 103153,
"author": "user11318",
"author_id": 11318,
"author_profile": "https://Stackoverflow.com/users/11318",
"pm_score": 0,
"selected": false,
"text": "<p>What I would do is open up cursors on the following queries:</p>\n\n<pre><code>SELECT * from table1 order by id\nSELECT * from table1 r, table2 t where t.table1_id = r.id order by r.id\nSELECT * from table1 r, table3 t where t.table1_id = r.id order by r.id\n</code></pre>\n\n<p>And then I would walk those cursors in parallel, printing your results. You can do this because all appear in the same order. (Note that I would suggest that while the primary ID for table1 might be named id, it <strong>won't</strong> have that name in the other tables.)</p>\n"
},
{
"answer_id": 103215,
"author": "Cervo",
"author_id": 16219,
"author_profile": "https://Stackoverflow.com/users/16219",
"pm_score": 0,
"selected": false,
"text": "<p>Do all the tables have the same format? If not, then if you have to have a report that can display the <code>n</code> different types of rows. If you are only interested in the same columns then it is easier.</p>\n\n<p>Most databases have some form of dynamic SQL. In that case you can do the following:</p>\n\n<pre><code>create temporary table from\nselect * from table1 where rows within time frame\n\nx integer\nsql varchar(something)\nx = 1\nwhile x <= numresults {\n sql = 'SELECT * from table' + CAST(X as varchar) + ' where id in (select id from temporary table'\n execute sql\n x = x + 1\n}\n</code></pre>\n\n<p>But I mean basically here you are running one query on your main table to get the rows that you need, then running one query for each sub table to get rows that match your main table.</p>\n\n<p>If the report requires the same 2 or 3 columns for each table you could change the <code>select * from tablex</code> to be an <code>insert into</code> and get a single result set at the end...</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103005",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2246765/"
]
| Here is my situation:
Table one contains a set of data that uses an id for an unique identifier. This table has a one to many relationship with about 6 other tables such that.
Given Table 1 with Id of 001:
Table 2 might have 3 rows with foreign key: 001
Table 3 might have 12 rows with foreign key: 001
Table 4 might have 0 rows with foreign key: 001
Table 5 might have 28 rows with foreign key: 001
I need to write a report that lists all of the rows from Table 1 for a specified time frame followed by all of the data contained in the handful of tables that reference it.
My current approach in pseudo code would look like this:
```
select * from table 1
foreach(result) {
print result;
select * from table 2 where id = result.id;
foreach(result2) {
print result2;
}
select * from table 3 where id = result.id
foreach(result3) {
print result3;
}
//continued for each table
}
```
This means that the single report can run in the neighbor hood of 1000 queries. I know this is excessive however my sql-fu is a little weak and I could use some help. | LEFT OUTER JOIN Tables2-N on Table1
```
SELECT Table1.*, Table2.*, Table3.*, Table4.*, Table5.*
FROM Table1
LEFT OUTER JOIN Table2 ON Table1.ID = Table2.ID
LEFT OUTER JOIN Table3 ON Table1.ID = Table3.ID
LEFT OUTER JOIN Table4 ON Table1.ID = Table4.ID
LEFT OUTER JOIN Table5 ON Table1.ID = Table5.ID
WHERE (CRITERIA)
``` |
103,006 | <p>I've got a CSV file containing latitude and longitude values, such as:</p>
<blockquote>
<p>"25°36'55.57""E","45°39'12.52""N"</p>
</blockquote>
<p>Anyone have a quick and simple piece of C# code to convert this to double values?</p>
<p>Thanks</p>
| [
{
"answer_id": 103057,
"author": "ine",
"author_id": 4965,
"author_profile": "https://Stackoverflow.com/users/4965",
"pm_score": 5,
"selected": true,
"text": "<p>If you mean C# code to do this:</p>\n\n<p>result = 25 + (36 / 60) + (55.57 / 3600)</p>\n\n<p>First you'll need to parse the expression with Regex or some other mechanism and split it into the individual parts. Then:</p>\n\n<pre><code>String hour = \"25\";\nString minute = \"36\";\nString second = \"55.57\";\nDouble result = (hour) + (minute) / 60 + (second) / 3600;\n</code></pre>\n\n<p>And of course a switch to flip sign depending on N/S or E/S. Wikipedia has a little on that:</p>\n\n<blockquote>\n <p>For calculations, the West/East suffix is replaced by a negative sign in the western hemisphere. Confusingly, the convention of negative for East is also sometimes seen. The preferred convention -- that East be positive -- is consistent with a right-handed Cartesian coordinate system with the North Pole up. A specific longitude may then be combined with a specific latitude (usually positive in the northern hemisphere) to give a precise position on the Earth's surface.\n (<a href=\"http://en.wikipedia.org/wiki/Longitude\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Longitude</a>)</p>\n</blockquote>\n"
},
{
"answer_id": 103134,
"author": "Dan Blair",
"author_id": 1327,
"author_profile": "https://Stackoverflow.com/users/1327",
"pm_score": 0,
"selected": false,
"text": "<p>What are you wanting to represent it as? Arc seconds?\nThen 60 min in every degree, 60 seconds in every minute.\nYou would then have to keep E and N by yourself. </p>\n\n<p>This is not how it's done generally though.</p>\n\n<p>The easiest representation I've seen to work with is a point plotted on the globe on a grid system that has its origin through the center of the earth.[Thus a nice position vector.] The problem with this is that while it's easy to use the data, getting it into and out of the system correctly can be tough, because the earth is not round, or for that matter uniform.</p>\n"
},
{
"answer_id": 103357,
"author": "Nick Randell",
"author_id": 5932,
"author_profile": "https://Stackoverflow.com/users/5932",
"pm_score": 3,
"selected": false,
"text": "<p>Thanks for all the quick answers. Based on the answer by amdfan, I put this code together that does the job in C#.</p>\n\n<pre><code>/// <summary>The regular expression parser used to parse the lat/long</summary>\nprivate static Regex Parser = new Regex(\"^(?<deg>[-+0-9]+)[^0-9]+(?<min>[0-9]+)[^0-9]+(?<sec>[0-9.,]+)[^0-9.,ENSW]+(?<pos>[ENSW]*)$\");\n\n/// <summary>Parses the lat lon value.</summary>\n/// <param name=\"value\">The value.</param>\n/// <remarks>It must have at least 3 parts 'degrees' 'minutes' 'seconds'. If it \n/// has E/W and N/S this is used to change the sign.</remarks>\n/// <returns></returns>\npublic static double ParseLatLonValue(string value)\n{\n // If it starts and finishes with a quote, strip them off\n if (value.StartsWith(\"\\\"\") && value.EndsWith(\"\\\"\"))\n {\n value = value.Substring(1, value.Length - 2).Replace(\"\\\"\\\"\", \"\\\"\");\n }\n\n // Now parse using the regex parser\n Match match = Parser.Match(value);\n if (!match.Success)\n {\n throw new ArgumentException(string.Format(CultureInfo.CurrentUICulture, \"Lat/long value of '{0}' is not recognised\", value));\n }\n\n // Convert - adjust the sign if necessary\n double deg = double.Parse(match.Groups[\"deg\"].Value);\n double min = double.Parse(match.Groups[\"min\"].Value);\n double sec = double.Parse(match.Groups[\"sec\"].Value);\n double result = deg + (min / 60) + (sec / 3600);\n if (match.Groups[\"pos\"].Success)\n {\n char ch = match.Groups[\"pos\"].Value[0];\n result = ((ch == 'S') || (ch == 'W')) ? -result : result;\n }\n return result;\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5932/"
]
| I've got a CSV file containing latitude and longitude values, such as:
>
> "25°36'55.57""E","45°39'12.52""N"
>
>
>
Anyone have a quick and simple piece of C# code to convert this to double values?
Thanks | If you mean C# code to do this:
result = 25 + (36 / 60) + (55.57 / 3600)
First you'll need to parse the expression with Regex or some other mechanism and split it into the individual parts. Then:
```
String hour = "25";
String minute = "36";
String second = "55.57";
Double result = (hour) + (minute) / 60 + (second) / 3600;
```
And of course a switch to flip sign depending on N/S or E/S. Wikipedia has a little on that:
>
> For calculations, the West/East suffix is replaced by a negative sign in the western hemisphere. Confusingly, the convention of negative for East is also sometimes seen. The preferred convention -- that East be positive -- is consistent with a right-handed Cartesian coordinate system with the North Pole up. A specific longitude may then be combined with a specific latitude (usually positive in the northern hemisphere) to give a precise position on the Earth's surface.
> (<http://en.wikipedia.org/wiki/Longitude>)
>
>
> |
103,016 | <p>When you pipe two process and kill the one at the "output" of the pipe, the first process used to receive the "Broken Pipe" signal, which usually terminated it aswell. E.g. running</p>
<pre><code>$> do_something_intensive | less
</code></pre>
<p>and then exiting <em>less</em> used to return you immediately to a responsive shell, on a SuSE8 or former releases.
when i'm trying that today, <em>do_something_intensive</em> is obviously still running until i kill it manually. It seems that something has changed (glib ? shell ?) that makes program ignore "broken pipes" ...</p>
<p>Anyone of you has hints on this ? how to restore the former behaviour ? why it has been changed (or why it always existed multiple semantics) ?</p>
<p><em>edit</em> : further tests (using strace) reveal that "SIGPIPE" <em>is</em> generated, but that the program is not interrupted. A simple</p>
<pre><code>#include <stdio.h>
int main()
{
while(1) printf("dumb test\n");
exit(0);
}
</code></pre>
<p>will go on with an endless</p>
<pre><code>--- SIGPIPE (Broken pipe) @ 0 (0) ---
write(1, "dumb test\ndumb test\ndumb test\ndu"..., 1024) = -1 EPIPE (Broken pipe)
</code></pre>
<p>when <em>less</em> is killed. I could for sure program a signal handler in my program and ensure it terminates, but i'm more looking for some environment variable or a shell option that would force programs to terminate on SIGPIPE</p>
<p><em>edit again</em>: it seems to be a tcsh-specific issue (bash handles it properly) and terminal-dependent (Eterm 0.9.4)</p>
| [
{
"answer_id": 103079,
"author": "Daniel Papasian",
"author_id": 7548,
"author_profile": "https://Stackoverflow.com/users/7548",
"pm_score": 3,
"selected": false,
"text": "<p>Well, if there is an attempt to write to a pipe after the reader has gone away, a SIGPIPE signal gets generated. The application has the ability to catch this signal, but if it doesn't, the process is killed.</p>\n\n<p>The SIGPIPE won't be generated until the calling process attempts to write, so if there's no more output, it won't be generated. </p>\n"
},
{
"answer_id": 103445,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 2,
"selected": false,
"text": "<p>Has \"do something intensive\" changed at all?</p>\n\n<p>As Daniel has mentioned SIGPIPE is not a magic \"your pipe went away\" signal but rather a \"nice try, you can no longer read/write that pipe\" signal.</p>\n\n<p>If you have control of \"do something intensive\" you could change it to write out some \"progress indicator\" output as it spins. This would raise the SIGPIPE in a timely fashion.</p>\n"
},
{
"answer_id": 121892,
"author": "PypeBros",
"author_id": 15304,
"author_profile": "https://Stackoverflow.com/users/15304",
"pm_score": 1,
"selected": true,
"text": "<p>Thanks for your advices, the solution is getting closer...</p>\n\n<p>According to the manpage of tcsh, \"non-login shells inherit the terminate behavior from their parents. Other signals have the values which the shell inherited from its parent.\"</p>\n\n<p>Which suggest my <em>terminal</em> is actually the root of the problem ... if it ignored SIGPIPE, the shell itself will ignore SIGPIPE as well ... </p>\n\n<p><em>edit:</em> i have the definitive confirmation that the problem only arise with Eterm+tcsh and found a suspiciously missing signal(SIGPIPE,SIG_DFL) in Eterm source code. I think that close the case.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15304/"
]
| When you pipe two process and kill the one at the "output" of the pipe, the first process used to receive the "Broken Pipe" signal, which usually terminated it aswell. E.g. running
```
$> do_something_intensive | less
```
and then exiting *less* used to return you immediately to a responsive shell, on a SuSE8 or former releases.
when i'm trying that today, *do\_something\_intensive* is obviously still running until i kill it manually. It seems that something has changed (glib ? shell ?) that makes program ignore "broken pipes" ...
Anyone of you has hints on this ? how to restore the former behaviour ? why it has been changed (or why it always existed multiple semantics) ?
*edit* : further tests (using strace) reveal that "SIGPIPE" *is* generated, but that the program is not interrupted. A simple
```
#include <stdio.h>
int main()
{
while(1) printf("dumb test\n");
exit(0);
}
```
will go on with an endless
```
--- SIGPIPE (Broken pipe) @ 0 (0) ---
write(1, "dumb test\ndumb test\ndumb test\ndu"..., 1024) = -1 EPIPE (Broken pipe)
```
when *less* is killed. I could for sure program a signal handler in my program and ensure it terminates, but i'm more looking for some environment variable or a shell option that would force programs to terminate on SIGPIPE
*edit again*: it seems to be a tcsh-specific issue (bash handles it properly) and terminal-dependent (Eterm 0.9.4) | Thanks for your advices, the solution is getting closer...
According to the manpage of tcsh, "non-login shells inherit the terminate behavior from their parents. Other signals have the values which the shell inherited from its parent."
Which suggest my *terminal* is actually the root of the problem ... if it ignored SIGPIPE, the shell itself will ignore SIGPIPE as well ...
*edit:* i have the definitive confirmation that the problem only arise with Eterm+tcsh and found a suspiciously missing signal(SIGPIPE,SIG\_DFL) in Eterm source code. I think that close the case. |
103,034 | <p>I'm having an odd problem with my vs debugger. When running my program under the vs debugger, the debugger does not break on an unhandled exception. Instead control is returned to VS as if the program exited normally. If I look in the output tab, There is a first-chance exeption listed just before the thread termination.</p>
<p>I understand how to use the "Exceptions" box from the Debug menu. I have the break on unhandled exceptions checked. If I check first-chance exceptions for the specific exeption that is occuring, the debugger will stop.</p>
<p>However, it is my understanding that the debugger should also stop on any 'Unhandled-Exceptions'. It is not doing this for me.</p>
<p>Here are the last few lines of my Output tab:</p>
<pre><code>A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
The thread 0x60c has exited with code 0 (0x0).
The program '[3588] ALMSSecurityManager.vshost.exe: Managed' has exited with code -532459699 (0xe0434f4d).
</code></pre>
<p>I don't understand why the exception is flagges as a "first chance" exception when it is unhandled.</p>
<p>I believe that the 0xe0434f4d exit code is a generic COM error.</p>
<p>Any Ideas?</p>
<p>Metro.</p>
| [
{
"answer_id": 103049,
"author": "hova",
"author_id": 2170,
"author_profile": "https://Stackoverflow.com/users/2170",
"pm_score": 0,
"selected": false,
"text": "<p>There are two checkboxes in the \"Exceptions...\" box, I usually have to have them both checked to get it to break on unhandled exceptions. Regardless that it only reads like you need to have one checked.</p>\n"
},
{
"answer_id": 103050,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Ctl-D, E brings up the Exceptions window. You can set what exceptions you want to, and don't want to, break on.</p>\n"
},
{
"answer_id": 103150,
"author": "Morten Christiansen",
"author_id": 4055,
"author_profile": "https://Stackoverflow.com/users/4055",
"pm_score": 0,
"selected": false,
"text": "<p>Once every while this happens to me as well. It seems like a bug or something, as when I replicate the scenario the exception is caught and shown as usual.</p>\n"
},
{
"answer_id": 103367,
"author": "Metro",
"author_id": 18978,
"author_profile": "https://Stackoverflow.com/users/18978",
"pm_score": 3,
"selected": false,
"text": "<p>When I read the answer about having two check boxes in the \"Exception...\" dialog, I went back and opened the dialog again. I only had one column of check boxes -- for break on \"Thrown\".</p>\n\n<p>As it turns out, if you do not have \"Enable Just My Code (Managed Only)\" checked in the Debug options, the \"User-Unhandled\" column does not show in the \"Exceptions\" dialog.</p>\n\n<p>I selected the \"Enable Just My Code\" option and verified that the \"User-unhandled\" checkbox on the \"Exceptions\" dialog was selected for all of the exception categories.</p>\n\n<p>I was able to get unhandled exceptions to break into the debugger for one session. But when I came back the next day, the behavior was as before.</p>\n\n<p>Metro.</p>\n"
},
{
"answer_id": 4354724,
"author": "Granger",
"author_id": 530545,
"author_profile": "https://Stackoverflow.com/users/530545",
"pm_score": 4,
"selected": true,
"text": "<p>If you're on a 64-bit OS, there's a pretty good chance you're being bitten by an OS-level behavior that causes exceptions to disappear. The most reliable way to reproduce it is to make a new WinForm application that simply throws an exception in OnLoad; it will appear to not get thrown. Take a look at these:</p>\n\n<ol>\n<li>Visual Studio doesn't break on unhandled exception with windows 64-bit\n\n<ul>\n<li>http: // social.msdn.microsoft.com/Forums/en/vsdebug/thread/69a0b831-7782-4bd9-b910-25c85f18bceb</li>\n</ul></li>\n<li><a href=\"http://blog.paulbetts.org/index.php/2010/07/20/the-case-of-the-disappearing-onload-exception-user-mode-callback-exceptions-in-x64/\" rel=\"noreferrer\">The case of the disappearing OnLoad exception</a> </li>\n<li>Silent exceptions on x64 development machines (Microsoft Connect)\n\n<ul>\n<li>https: // connect.microsoft.com/VisualStudio/feedback/details/357311/silent-exceptions-on-x64-development-machines</li>\n</ul></li>\n</ol>\n\n<p>The first is what I found from Google (after this thread didn't help), and that thread led me to the following two. The second has the best explanation, and the third is the Microsoft bug/ticket (that re-affirms that this is \"by design\" behavior).</p>\n\n<p>So, basically, if your application throws an Exception that hits a kernel-mode boundary on its way back up the stack, it gets blocked at that boundary. And the Windows team decided the best way to deal with it was to pretend the exception was handled; execution continues as if everything completed normally.</p>\n\n<p>Oh, and this happens <em>everywhere</em>. Debug versus Release is irrelevant. .Net vs C++ is irrelevant. This is OS-level behavior. </p>\n\n<p>Imagine you have to write some critical data to disk, but it fails on the wrong side of a kernal-mode boundary. Other code tries to use it later and, if you're lucky, you detect something's wrong with the data ...but why? I bet you never consider that your application failed to write the data---because you expected an exception would be thrown.</p>\n\n<p>Jerks.</p>\n"
},
{
"answer_id": 11638482,
"author": "yoel halb",
"author_id": 640195,
"author_profile": "https://Stackoverflow.com/users/640195",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar problem, and checking \"Enable Just My Code (Managed Only)\" fixed the problem, while if I turned it back off then the problem came back, no clue why (but it is possible that some DLL's that appear to get loaded when it is unchecked cause the behavior).</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103034",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18978/"
]
| I'm having an odd problem with my vs debugger. When running my program under the vs debugger, the debugger does not break on an unhandled exception. Instead control is returned to VS as if the program exited normally. If I look in the output tab, There is a first-chance exeption listed just before the thread termination.
I understand how to use the "Exceptions" box from the Debug menu. I have the break on unhandled exceptions checked. If I check first-chance exceptions for the specific exeption that is occuring, the debugger will stop.
However, it is my understanding that the debugger should also stop on any 'Unhandled-Exceptions'. It is not doing this for me.
Here are the last few lines of my Output tab:
```
A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll
The thread 0x60c has exited with code 0 (0x0).
The program '[3588] ALMSSecurityManager.vshost.exe: Managed' has exited with code -532459699 (0xe0434f4d).
```
I don't understand why the exception is flagges as a "first chance" exception when it is unhandled.
I believe that the 0xe0434f4d exit code is a generic COM error.
Any Ideas?
Metro. | If you're on a 64-bit OS, there's a pretty good chance you're being bitten by an OS-level behavior that causes exceptions to disappear. The most reliable way to reproduce it is to make a new WinForm application that simply throws an exception in OnLoad; it will appear to not get thrown. Take a look at these:
1. Visual Studio doesn't break on unhandled exception with windows 64-bit
* http: // social.msdn.microsoft.com/Forums/en/vsdebug/thread/69a0b831-7782-4bd9-b910-25c85f18bceb
2. [The case of the disappearing OnLoad exception](http://blog.paulbetts.org/index.php/2010/07/20/the-case-of-the-disappearing-onload-exception-user-mode-callback-exceptions-in-x64/)
3. Silent exceptions on x64 development machines (Microsoft Connect)
* https: // connect.microsoft.com/VisualStudio/feedback/details/357311/silent-exceptions-on-x64-development-machines
The first is what I found from Google (after this thread didn't help), and that thread led me to the following two. The second has the best explanation, and the third is the Microsoft bug/ticket (that re-affirms that this is "by design" behavior).
So, basically, if your application throws an Exception that hits a kernel-mode boundary on its way back up the stack, it gets blocked at that boundary. And the Windows team decided the best way to deal with it was to pretend the exception was handled; execution continues as if everything completed normally.
Oh, and this happens *everywhere*. Debug versus Release is irrelevant. .Net vs C++ is irrelevant. This is OS-level behavior.
Imagine you have to write some critical data to disk, but it fails on the wrong side of a kernal-mode boundary. Other code tries to use it later and, if you're lucky, you detect something's wrong with the data ...but why? I bet you never consider that your application failed to write the data---because you expected an exception would be thrown.
Jerks. |
103,136 | <p>I am trying to execute some stored procedures in groovy way. I am able to do it quite easily by using straight JDBC but this does not seem in the spirit of Grails.</p>
<p>I am trying to call the stored procedure as:</p>
<pre><code>sql.query( "{call web_GetCityStateByZip(?,?,?,?,?)}",[params.postalcode,
sql.out(java.sql.Types.VARCHAR), sql.out(java.sql.Types.VARCHAR),
sql.out(java.sql.Types.INTEGER), sql.out(java.sql.Types.VARCHAR)]) { rs ->
params.city = rs.getString(2)
params.state = rs.getString(3)
}
</code></pre>
<p>I tried various ways like <code>sql.call</code>. I was trying to get output variable value after this.</p>
<p>Everytime error:</p>
<pre><code>Message: Cannot register out parameter.
Caused by: java.sql.SQLException: Cannot register out parameter.
Class: SessionExpirationFilter
</code></pre>
<p>but this does not seem to work.</p>
<p>Can anyone point me in the right direction?</p>
| [
{
"answer_id": 107518,
"author": "Internet Friend",
"author_id": 18037,
"author_profile": "https://Stackoverflow.com/users/18037",
"pm_score": 1,
"selected": false,
"text": "<p>This is still unanswered, so I did a bit of digging although I don't fully understand the problem. The following turned up from the Groovy source, perhaps it's of some help:</p>\n\n<p>This line seems to be the origin of the exception:</p>\n\n<p><a href=\"http://groovy.codehaus.org/xref/groovy/sql/Sql.html#1173\" rel=\"nofollow noreferrer\">http://groovy.codehaus.org/xref/groovy/sql/Sql.html#1173</a></p>\n\n<p>This would seem to indicate that you have a Statement object implementing PreparedStatement, when you need the subinterface CallableStatement, which has the registerOutParameter() method which should be ultimately invoked.</p>\n"
},
{
"answer_id": 116620,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks Internet Friend,\nIf i write code like-</p>\n\n<pre><code> Sql sql = new Sql(dataSource)\nConnection conn\nResultSet rs\ntry {\n conn = sql.createConnection()\n CallableStatement callable = conn.prepareCall(\n \"{call web_GetCityStateByZip(?,?,?,?,?)}\")\n callable.setString(\"@p_Zip\",params.postalcode)\n callable.registerOutParameter(\"@p_City\",java.sql.Types.VARCHAR)\n callable.registerOutParameter(\"@p_State\",java.sql.Types.VARCHAR)\n callable.registerOutParameter(\"@p_RetCode\",java.sql.Types.INTEGER)\n callable.registerOutParameter(\"@p_Msg\",java.sql.Types.VARCHAR)\n callable.execute()\n params.city = callable.getString(2)\n params.state = callable.getString(3)\n }\n</code></pre>\n\n<p>It working well in JDBC way. But i wanted to try it like the previous code using sql.query/sql.call.</p>\n\n<p>Any comments??</p>\n\n<p>Thanks\nSadhna </p>\n"
},
{
"answer_id": 681588,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>groovy way could be this code:</p>\n\n<pre><code>def getHours(java.sql.Date date, User user) throws CallProceduresServiceException {\n\n log.info \"Calling stored procedure for getting hours statistics.\"\n def procedure\n def hour\n try {\n def sql = Sql.newInstance(dataSource.url, user.username, user.password, dataSource.driverClassName)\n log.debug \"Date(first param): '${date}'\"\n\n procedure = \"call ${dbPrefixName}.GK_WD_GET_SCHEDULED_TIME_SUM(?, ?, ?, ?)\"\n log.debug \"procedure: ${procedure}\"\n\n sql.call(\"{${procedure}}\", [date, Sql.out(Sql.VARCHAR.getType()), Sql.out(Sql.VARCHAR.getType()), Sql.out(Sql.VARCHAR.getType())]) {\n hourInDay, hourInWeek, hourInMonth -> \n log.debug \"Hours in day: '${hourInDay}'\"\n log.debug \"Hours in week: '${hourInWeek}'\"\n log.debug \"Hours in month: '${hourInMonth}'\"\n hour = new Hour(hourInDay, hourInWeek, hourInMonth)\n }\n log.info \"Procedure was executed.\"\n } \n catch (SQLException e) {\n throw new CallProceduresServiceException(\"Executing sql procedure failed!\"\n + \"\\nProcedure: ${procedure}\", e)\n } \n return hour \n}\n</code></pre>\n\n<p>In my app it works great.</p>\n\n<p>Tomas Peterka</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am trying to execute some stored procedures in groovy way. I am able to do it quite easily by using straight JDBC but this does not seem in the spirit of Grails.
I am trying to call the stored procedure as:
```
sql.query( "{call web_GetCityStateByZip(?,?,?,?,?)}",[params.postalcode,
sql.out(java.sql.Types.VARCHAR), sql.out(java.sql.Types.VARCHAR),
sql.out(java.sql.Types.INTEGER), sql.out(java.sql.Types.VARCHAR)]) { rs ->
params.city = rs.getString(2)
params.state = rs.getString(3)
}
```
I tried various ways like `sql.call`. I was trying to get output variable value after this.
Everytime error:
```
Message: Cannot register out parameter.
Caused by: java.sql.SQLException: Cannot register out parameter.
Class: SessionExpirationFilter
```
but this does not seem to work.
Can anyone point me in the right direction? | This is still unanswered, so I did a bit of digging although I don't fully understand the problem. The following turned up from the Groovy source, perhaps it's of some help:
This line seems to be the origin of the exception:
<http://groovy.codehaus.org/xref/groovy/sql/Sql.html#1173>
This would seem to indicate that you have a Statement object implementing PreparedStatement, when you need the subinterface CallableStatement, which has the registerOutParameter() method which should be ultimately invoked. |
103,157 | <p>Can someone please remind me how to create a .Net class from an XML file?<br></p>
<p>I would prefer the batch commands, or a way to integrate it into the shell.<br></p>
<p>Thanks!</p>
| [
{
"answer_id": 103191,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": 0,
"selected": false,
"text": "<p>You might be able to use the xsd.exe tool to generate a class, otherwise you probably have to implement a custom solution against your XML</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.80).aspx\" rel=\"nofollow noreferrer\">XML Schema Definition Tool</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms950721.aspx\" rel=\"nofollow noreferrer\">XML Serialization</a></p>\n"
},
{
"answer_id": 104260,
"author": "Nescio",
"author_id": 14484,
"author_profile": "https://Stackoverflow.com/users/14484",
"pm_score": 2,
"selected": false,
"text": "<p>The below batch will create a .Net <strong>Class</strong> from <strong>XML</strong> in the current directory.<br>\nSo... XML -> XSD -> VB</p>\n\n<p>(Feel free to substitute CS for Language)</p>\n\n<p>Create a <strong>Convert2Class.Bat</strong> in the %UserProfile%\\SendTo directory.<br>\nThen copy/save the below:</p>\n\n<pre><code>@Echo off\nSet XsdExePath=\"C:\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\\Bin\\XSD.exe\"\nSet Language=VB\n%~d1\nCD %~d1%~p1 \n%XsdExePath% \"%~n1.xml\" /nologo\n%XsdExePath% \"%~n1.xsd\" /nologo /c /language:%Language%\n</code></pre>\n\n<p>Works on my machine - Good Luck!!<br></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103157",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14484/"
]
| Can someone please remind me how to create a .Net class from an XML file?
I would prefer the batch commands, or a way to integrate it into the shell.
Thanks! | The below batch will create a .Net **Class** from **XML** in the current directory.
So... XML -> XSD -> VB
(Feel free to substitute CS for Language)
Create a **Convert2Class.Bat** in the %UserProfile%\SendTo directory.
Then copy/save the below:
```
@Echo off
Set XsdExePath="C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\XSD.exe"
Set Language=VB
%~d1
CD %~d1%~p1
%XsdExePath% "%~n1.xml" /nologo
%XsdExePath% "%~n1.xsd" /nologo /c /language:%Language%
```
Works on my machine - Good Luck!! |
103,177 | <p>How do you enumerate the fields of a certificate help in a store. Specifically, I am trying to enumerate the fields of personal certificates issued to the logged on user.</p>
| [
{
"answer_id": 103228,
"author": "Duncan Smart",
"author_id": 1278,
"author_profile": "https://Stackoverflow.com/users/1278",
"pm_score": 1,
"selected": false,
"text": "<p>See <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509store.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509store.aspx</a></p>\n\n<pre><code>using System.Security.Cryptography.X509Certificates;\n...\nvar store = new X509Store(StoreName.My);\nforeach(var cert in store.Certificates)\n...\n</code></pre>\n"
},
{
"answer_id": 318407,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You also must use <strong>store.open()</strong> before you can access the store.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| How do you enumerate the fields of a certificate help in a store. Specifically, I am trying to enumerate the fields of personal certificates issued to the logged on user. | See <http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509store.aspx>
```
using System.Security.Cryptography.X509Certificates;
...
var store = new X509Store(StoreName.My);
foreach(var cert in store.Certificates)
...
``` |
103,179 | <p>I know I can specify one for each form, or for the root form and then it'll cascade through to all of the children forms, but I'd like to have a way of overriding the default Java Coffee Cup for all forms even those I might forget.</p>
<p>Any suggestions?</p>
| [
{
"answer_id": 103223,
"author": "Andreas Bakurov",
"author_id": 7400,
"author_profile": "https://Stackoverflow.com/users/7400",
"pm_score": 0,
"selected": false,
"text": "<p>Extend the JDialog class (for example name it MyDialog) and set the icon in constructor. Then all dialogs should extend your implementation (MyDialog).</p>\n"
},
{
"answer_id": 103295,
"author": "Paul Brinkley",
"author_id": 18160,
"author_profile": "https://Stackoverflow.com/users/18160",
"pm_score": 4,
"selected": true,
"text": "<p>You can make the root form (by which I assume you mean <code>JFrame</code>) be your own subclass of <code>JFrame</code>, and put standard functionality in its constructor, such as:</p>\n\n<pre><code>this.setIconImage(STANDARD_ICON);\n</code></pre>\n\n<p>You can bundle other standard stuff in here too, such as memorizing the frame's window metrics as a user preference, managing splash panes, etc.</p>\n\n<p>Any new frames spawned by this one would also be instances of this <code>JFrame</code> subclass. The only thing you have to remember is to instantiate your subclass, instead of <code>JFrame</code>. I don't think there's any substitute for remembering to do this, but at least now it's a matter of remembering a subclass instead of a <code>setIconImage</code> call (among possibly other features).</p>\n"
},
{
"answer_id": 103979,
"author": "John Gardner",
"author_id": 13687,
"author_profile": "https://Stackoverflow.com/users/13687",
"pm_score": 1,
"selected": false,
"text": "<p>Also, if you have one \"main\" window, and set its icon properly, as long as you use that main window as the \"parent\" for any Dialog classes, they will inherit the icon. Any new Frames need to have the icon set on them, though.</p>\n\n<p>as Paul/Andreas said, subclassing JFrame is going to be your best bet.</p>\n"
},
{
"answer_id": 103996,
"author": "John Gardner",
"author_id": 13687,
"author_profile": "https://Stackoverflow.com/users/13687",
"pm_score": 2,
"selected": false,
"text": "<p>There is another way, but its more of a \"hack\" then a real fix....</p>\n\n<p>If you are distributing the JRE with your Application, you could replace the coffee cup icon resource in the java exe/dll/rt.jar wherever that is with your own icon. It might not be very legit, but it is a possibility...</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
]
| I know I can specify one for each form, or for the root form and then it'll cascade through to all of the children forms, but I'd like to have a way of overriding the default Java Coffee Cup for all forms even those I might forget.
Any suggestions? | You can make the root form (by which I assume you mean `JFrame`) be your own subclass of `JFrame`, and put standard functionality in its constructor, such as:
```
this.setIconImage(STANDARD_ICON);
```
You can bundle other standard stuff in here too, such as memorizing the frame's window metrics as a user preference, managing splash panes, etc.
Any new frames spawned by this one would also be instances of this `JFrame` subclass. The only thing you have to remember is to instantiate your subclass, instead of `JFrame`. I don't think there's any substitute for remembering to do this, but at least now it's a matter of remembering a subclass instead of a `setIconImage` call (among possibly other features). |
103,203 | <p>We recently had a security audit and it exposed several weaknesses in the systems that are in place here. One of the tasks that resulted from it is that we need to update our partner credentials system make it more secure. </p>
<p>The "old" way of doing things was to generate a (bad) password, give it to the partner with an ID and then they would send that ID and a Base 64 encoded copy of that password in with all of their XML requests over https. We then decode them and validate them.</p>
<p>These passwords won't change (because then our partners would have to make coding/config changes to change them and coordinating password expirations with hundreds of partners for multiple environments would be a nightmare) and they don't have to be entered by a human or human readable. I am open to changing this if there is a better but still relatively simple implementation for our partners.</p>
<p>Basically it comes down to two things: I need a more secure Java password generation system and to ensure that they are transmitted in a secure way.</p>
<p>I've found a few hand-rolled password generators but nothing that really stood out as a standard way to do this (maybe for good reason). There may also be a more secure way to transmit them than simple Base 64 encoding over https. </p>
<p>What would you do for the password generator and do you think that the transmission method in place is secure enough for it?</p>
<p>Edit: The XML comes in a SOAP message and the credentials are in the header not in the XML itself. Also, since the passwords are a one-off operation for each partner when we set them up we're not too worried about efficiency of the generator.</p>
| [
{
"answer_id": 103648,
"author": "delfuego",
"author_id": 16414,
"author_profile": "https://Stackoverflow.com/users/16414",
"pm_score": 0,
"selected": false,
"text": "<p>I'm unclear why transmitting the passwords over SSL -- via HTTPS -- is being considered \"insecure\" by your audit team. So when you ask for two things, it seems the second -- ensuring that the passwords are being transmitted in a secure way -- is already being handled just fine.</p>\n\n<p>As for the first, we'd have to know what about the audit exposed your passwords as insecure...</p>\n"
},
{
"answer_id": 103768,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 4,
"selected": true,
"text": "<h3>Password Generation</h3>\n\n<p>As far as encoding a password for transmission, the only encoding that will truly add security is encryption. Using Base-64 or hexadecimal isn't for security, but just to be able to include it in a text format like XML.</p>\n\n<p>Entropy is used to measure password quality. So, choosing each bit with a random \"coin-flip\" will give you the best quality password. You'd want passwords to be as strong as other cryptographic keys, so I'd recommend a minimum of 128 bits of entropy. </p>\n\n<p>There are two easy methods, depending on how you want to encode the password as text (which really doesn't matter from a security standpoint).</p>\n\n<p>For <a href=\"http://en.wikipedia.org/wiki/Base64\" rel=\"nofollow noreferrer\">Base-64</a>, use something like this:</p>\n\n<pre><code> SecureRandom rnd = new SecureRandom();\n /* Byte array length is multiple of LCM(log2(64), 8) / 8 = 3. */\n byte[] password = new byte[18];\n rnd.nextBytes(password);\n String encoded = Base64.encode(password);\n</code></pre>\n\n<p>The following doesn't require you to come up with a Base-64 encoder. The resulting encoding is not as compact (26 characters instead of 24) and the password doesn't have as much entropy. (But 130 bits is already a lot, comparable to a password of at least 30 characters chosen by a human.)</p>\n\n<pre><code>SecureRandom rnd = new SecureRandom();\n/* Bit length is multiple of log2(32) = 5. */\nString encoded = new BigInteger(130, rnd).toString(32); \n</code></pre>\n\n<p>Creating new SecureRandom objects is computationally expensive, so if you are going to generate passwords frequently, you may want to create one instance and keep it around.</p>\n\n<h3>A Better Approach</h3>\n\n<p>Embedding the password in the XML itself seems like a mistake.</p>\n\n<p>First of all, it seems like you would want to authenticate a sender before processing any documents they send you. Suppose I hate your guts, and start sending you giant XML files to execute a denial of service attack. Do you want to have to parse the XML only to find out that I'm not a legitimate partner? Wouldn't it be better if the servlet just rejected requests from unauthenticated users up front? </p>\n\n<p>Second, the passwords of your legitimate partners were protected during transmission by HTTPS, but now they are likely stored \"in the clear\" on your system somewhere. That's bad security.</p>\n\n<p>A better approach would be to authenticate partners when they send you a document with credentials in the HTTP request headers. If you only allow HTTPS, you can take the password out of the document completely and put it into an <a href=\"http://www.ietf.org/rfc/rfc2617.txt\" rel=\"nofollow noreferrer\">HTTP \"Basic\" authentication</a> header instead. It's secured by SSL during transmission, and not stored on your system in the clear (you only store a one-way hash for authentication purposes).</p>\n\n<p>HTTP Basic authentication is simple, widely supported, and will be much easier for you and your partners to implement than SSL client certificates.</p>\n\n<h3>Protecting Document Content</h3>\n\n<p>If the content of the documents themselves is sensitive, they really should be encrypted by the sender, and stored by you in their encrypted form. The best way to do this is with public key cryptography, but that would be a subject for another question.</p>\n"
},
{
"answer_id": 127853,
"author": "Oli",
"author_id": 15296,
"author_profile": "https://Stackoverflow.com/users/15296",
"pm_score": 0,
"selected": false,
"text": "<p>I'd abandon the whole password approach and start using client certificates allowing a 2 side authenticated SSL connection.</p>\n\n<p>You have to generate and sign individual certificates for each client. In the SSL handshake, you request the client's certificate and verify it. If it fails, the connection ends with a 401 status code.</p>\n\n<p>Certificates can be revoked at any time be your side, allowing easily disconnecting former customers.</p>\n\n<p>Since all this happens in the handshake prior to the communication, is is not possible to flood your server with data.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103203",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12662/"
]
| We recently had a security audit and it exposed several weaknesses in the systems that are in place here. One of the tasks that resulted from it is that we need to update our partner credentials system make it more secure.
The "old" way of doing things was to generate a (bad) password, give it to the partner with an ID and then they would send that ID and a Base 64 encoded copy of that password in with all of their XML requests over https. We then decode them and validate them.
These passwords won't change (because then our partners would have to make coding/config changes to change them and coordinating password expirations with hundreds of partners for multiple environments would be a nightmare) and they don't have to be entered by a human or human readable. I am open to changing this if there is a better but still relatively simple implementation for our partners.
Basically it comes down to two things: I need a more secure Java password generation system and to ensure that they are transmitted in a secure way.
I've found a few hand-rolled password generators but nothing that really stood out as a standard way to do this (maybe for good reason). There may also be a more secure way to transmit them than simple Base 64 encoding over https.
What would you do for the password generator and do you think that the transmission method in place is secure enough for it?
Edit: The XML comes in a SOAP message and the credentials are in the header not in the XML itself. Also, since the passwords are a one-off operation for each partner when we set them up we're not too worried about efficiency of the generator. | ### Password Generation
As far as encoding a password for transmission, the only encoding that will truly add security is encryption. Using Base-64 or hexadecimal isn't for security, but just to be able to include it in a text format like XML.
Entropy is used to measure password quality. So, choosing each bit with a random "coin-flip" will give you the best quality password. You'd want passwords to be as strong as other cryptographic keys, so I'd recommend a minimum of 128 bits of entropy.
There are two easy methods, depending on how you want to encode the password as text (which really doesn't matter from a security standpoint).
For [Base-64](http://en.wikipedia.org/wiki/Base64), use something like this:
```
SecureRandom rnd = new SecureRandom();
/* Byte array length is multiple of LCM(log2(64), 8) / 8 = 3. */
byte[] password = new byte[18];
rnd.nextBytes(password);
String encoded = Base64.encode(password);
```
The following doesn't require you to come up with a Base-64 encoder. The resulting encoding is not as compact (26 characters instead of 24) and the password doesn't have as much entropy. (But 130 bits is already a lot, comparable to a password of at least 30 characters chosen by a human.)
```
SecureRandom rnd = new SecureRandom();
/* Bit length is multiple of log2(32) = 5. */
String encoded = new BigInteger(130, rnd).toString(32);
```
Creating new SecureRandom objects is computationally expensive, so if you are going to generate passwords frequently, you may want to create one instance and keep it around.
### A Better Approach
Embedding the password in the XML itself seems like a mistake.
First of all, it seems like you would want to authenticate a sender before processing any documents they send you. Suppose I hate your guts, and start sending you giant XML files to execute a denial of service attack. Do you want to have to parse the XML only to find out that I'm not a legitimate partner? Wouldn't it be better if the servlet just rejected requests from unauthenticated users up front?
Second, the passwords of your legitimate partners were protected during transmission by HTTPS, but now they are likely stored "in the clear" on your system somewhere. That's bad security.
A better approach would be to authenticate partners when they send you a document with credentials in the HTTP request headers. If you only allow HTTPS, you can take the password out of the document completely and put it into an [HTTP "Basic" authentication](http://www.ietf.org/rfc/rfc2617.txt) header instead. It's secured by SSL during transmission, and not stored on your system in the clear (you only store a one-way hash for authentication purposes).
HTTP Basic authentication is simple, widely supported, and will be much easier for you and your partners to implement than SSL client certificates.
### Protecting Document Content
If the content of the documents themselves is sensitive, they really should be encrypted by the sender, and stored by you in their encrypted form. The best way to do this is with public key cryptography, but that would be a subject for another question. |
103,261 | <p>I recently inherited an old visual basic 6/ crystal reports project which connects to a sql server database. The error message I get (Error# -2147191803 A String is required here) when I attempt to run the project seems to be narrowed down to the .Printout command in the following code: </p>
<pre>
'Login to database
Set Tables = Report.Database.Tables
Set Table = Tables.Item(1)
Table.SetLogOnInfo ConnName, DBName, user, pass
DomainName = CStr(selected)
'Set parameter Fields
'Declare parameter holders
Set ParamDefs = Report.ParameterFields
'Store parameter objects
For Each ParamDef In ParamDefs
With ParamDef
MsgBox("DomainName : " + DomainName)
Select Case .ParameterFieldName
Case "Company Name"
.SetCurrentValue DomainName
End Select
Select Case .Name
Case "{?Company Name}"
.SetCurrentValue DomainName
End Select
'Flag to see what is assigned to Current value
MsgBox("paramdef: " + ParamDef.Value)
End With
Next
Report.EnableParameterPrompting = False
Screen.MousePointer = vbHourglass
'CRViewer1.ReportSource = Report
'CRViewer1.ViewReport
test = 1
**Report.PrintOut**
test = test + 3
currenttime = Str(Now)
currenttime = Replace(currenttime, "/", "-")
currenttime = Replace(currenttime, ":", "-")
DomainName = Replace(DomainName, ".", "")
startName = mPath + "\crysta~1.pdf"
endName = mPath + "\" + DomainName + "\" + DomainName + " " + currenttime + ".pdf"
rc = MsgBox("Wait for PDF job to finish", vbInformation, "H/W Report")
Name startName As endName
Screen.MousePointer = vbDefault
End If
</pre>
<p>During the run, the form shows up, the ParamDef variable sets the "company name" and when it gets to the <strong>Report.PrintOut</strong> line which prompts to print, it throws the error. I'm guessing the crystal report isn't receiving the "Company Name" to properly run the crystal report. Does any one know how to diagnose this...either on the vb6 or crystal reports side to determine what I'm missing here? </p>
<p><strong>UPDATE:</strong> </p>
<ul>
<li>inserted CStr(selected) to force DomainName to be a string</li>
<li>inserted msgboxes into the for loop above and below the .setcurrentvalue line </li>
<li>inserted Case "{?Company Name}" statement to see if that helps setting the value</li>
<li>tried .AddCurrentValue and .SetCurrentValue functions as suggested by other forum websites</li>
<li>ruled out that it was my development environement..loaded it on another machine with the exact same vb6 crystal reports 8.5 running on winxp prof sp2 and the same errors come up. </li>
</ul>
<p>and when I run the MsgBox(ParamDef.Value) and it also turns up blank with the same missing string error. I also can't find any documentation on the craxdrt.ParameterFieldDefinition class to see what other hidden functions are available. When I see the list of methods and property variables, it doesn't list SetCurrentValue as one of the functions.
Any ideas on this?</p>
| [
{
"answer_id": 103346,
"author": "Arthur Miller",
"author_id": 13085,
"author_profile": "https://Stackoverflow.com/users/13085",
"pm_score": 1,
"selected": false,
"text": "<p>What is the value of your selected variable?</p>\n\n<p>Table.SetLogOnInfo ConnName, DBName, user, pass<br />\n<strong>DomainName = selected</strong><br />\n'Set parameter Fields<br /></p>\n\n<p>If it is not a string, then that might be the problem. Crystal expects a string variable and when it doesn't receive what it expects, it throws errors.</p>\n"
},
{
"answer_id": 103451,
"author": "phill",
"author_id": 18853,
"author_profile": "https://Stackoverflow.com/users/18853",
"pm_score": 1,
"selected": false,
"text": "<p>selected is a string variable input taken from a form with a drop down select box. I previously put a message box there to ensure there the variable is passing through right before the Report.Printout and it does come up. DomainName variable is also declared as a string type.</p>\n"
},
{
"answer_id": 104259,
"author": "nathaniel",
"author_id": 11947,
"author_profile": "https://Stackoverflow.com/users/11947",
"pm_score": 1,
"selected": false,
"text": "<p>Here's how I set my parameters in Crystal (that came with .NET -- don't know if it helps you).</p>\n\n<pre><code>Dim dv As New ParameterDiscreteValue\ndv.Value = showphone\nrpt.ParameterFields(\"showphone\").CurrentValues.Add(dv)\n</code></pre>\n"
},
{
"answer_id": 114059,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This can happen in crystal reports 8.5 if you changed the length of a string column you use in your report so that it exceeds 255 bytes. This can also happen if you change the column type from varchar to nvarchar (double byte string!)</p>\n\n<p>The reason for this is that crystal reports 8.5 treats all strings longer than 255 bytes as memo fields.</p>\n\n<p>I would suggest youe upgrade to crystal reports XI - the API has not changed that much.</p>\n"
},
{
"answer_id": 131863,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>From my point of view you should get the same error message if you open the report in the Crystal Reports Designer and switch to preview mode. The Designer should also show you a message with the exact location of the problem, e.g. the field which can not be treated as a string. </p>\n\n<p>The problem is not that a field longer than 255 bytes cannot be printed. The problem is that a field longer than 255 bytes cannot be used in a formula, as a sort criteria ...</p>\n"
},
{
"answer_id": 223789,
"author": "smbarbour",
"author_id": 29115,
"author_profile": "https://Stackoverflow.com/users/29115",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a live example of setting the parameters that we use:</p>\n\n<pre><code>For Each CRXParamDef In CrystalReport.ParameterFields\n Select Case CRXParamDef.ParameterFieldName\n Case \"@start\"\n CRXParamDef.AddCurrentValue CDate(\"1/18/2002 12:00:00AM\")\n Case \"@end\"\n CRXParamDef.AddCurrentValue Now\n End Select\nNext\n</code></pre>\n\n<p>This is actually a sample written in VBScript for printing Crystal 8.5 reports, but the syntax is the same for VB6</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18853/"
]
| I recently inherited an old visual basic 6/ crystal reports project which connects to a sql server database. The error message I get (Error# -2147191803 A String is required here) when I attempt to run the project seems to be narrowed down to the .Printout command in the following code:
```
'Login to database
Set Tables = Report.Database.Tables
Set Table = Tables.Item(1)
Table.SetLogOnInfo ConnName, DBName, user, pass
DomainName = CStr(selected)
'Set parameter Fields
'Declare parameter holders
Set ParamDefs = Report.ParameterFields
'Store parameter objects
For Each ParamDef In ParamDefs
With ParamDef
MsgBox("DomainName : " + DomainName)
Select Case .ParameterFieldName
Case "Company Name"
.SetCurrentValue DomainName
End Select
Select Case .Name
Case "{?Company Name}"
.SetCurrentValue DomainName
End Select
'Flag to see what is assigned to Current value
MsgBox("paramdef: " + ParamDef.Value)
End With
Next
Report.EnableParameterPrompting = False
Screen.MousePointer = vbHourglass
'CRViewer1.ReportSource = Report
'CRViewer1.ViewReport
test = 1
**Report.PrintOut**
test = test + 3
currenttime = Str(Now)
currenttime = Replace(currenttime, "/", "-")
currenttime = Replace(currenttime, ":", "-")
DomainName = Replace(DomainName, ".", "")
startName = mPath + "\crysta~1.pdf"
endName = mPath + "\" + DomainName + "\" + DomainName + " " + currenttime + ".pdf"
rc = MsgBox("Wait for PDF job to finish", vbInformation, "H/W Report")
Name startName As endName
Screen.MousePointer = vbDefault
End If
```
During the run, the form shows up, the ParamDef variable sets the "company name" and when it gets to the **Report.PrintOut** line which prompts to print, it throws the error. I'm guessing the crystal report isn't receiving the "Company Name" to properly run the crystal report. Does any one know how to diagnose this...either on the vb6 or crystal reports side to determine what I'm missing here?
**UPDATE:**
* inserted CStr(selected) to force DomainName to be a string
* inserted msgboxes into the for loop above and below the .setcurrentvalue line
* inserted Case "{?Company Name}" statement to see if that helps setting the value
* tried .AddCurrentValue and .SetCurrentValue functions as suggested by other forum websites
* ruled out that it was my development environement..loaded it on another machine with the exact same vb6 crystal reports 8.5 running on winxp prof sp2 and the same errors come up.
and when I run the MsgBox(ParamDef.Value) and it also turns up blank with the same missing string error. I also can't find any documentation on the craxdrt.ParameterFieldDefinition class to see what other hidden functions are available. When I see the list of methods and property variables, it doesn't list SetCurrentValue as one of the functions.
Any ideas on this? | What is the value of your selected variable?
Table.SetLogOnInfo ConnName, DBName, user, pass
**DomainName = selected**
'Set parameter Fields
If it is not a string, then that might be the problem. Crystal expects a string variable and when it doesn't receive what it expects, it throws errors. |
103,280 | <p>If by some miracle a segfault occurs in our program, I want to catch the SIGSEGV and let the user (possibly a GUI client) know with a single return code that a serious problem has occurred. At the same time I would like to display information on the command line to show which signal was caught.</p>
<p>Today our signal handler looks as follows:</p>
<pre><code>void catchSignal (int reason) {
std :: cerr << "Caught a signal: " << reason << std::endl;
exit (1);
}
</code></pre>
<p>I can hear the screams of horror with the above, as I have read from this <a href="http://groups.google.com/group/gnu.gcc.help/browse_thread/thread/6184795b39508519/f775c1f48284b212?lnk=gst&q=deadlock#" rel="nofollow noreferrer">thread</a> that it is evil to call a non-reentrant function from a signal handler.</p>
<p>Is there a portable way to handle the signal and provide information to users?</p>
<p><strong>EDIT:</strong> Or at least portable within the POSIX framework?</p>
| [
{
"answer_id": 103553,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 0,
"selected": false,
"text": "<p>Write a launcher program to run your program and report abnormal exit code to the user.</p>\n"
},
{
"answer_id": 103926,
"author": "Richard Corden",
"author_id": 11698,
"author_profile": "https://Stackoverflow.com/users/11698",
"pm_score": 5,
"selected": true,
"text": "<p>This <a href=\"http://docs.oracle.com/cd/E19963-01/html/821-1601/gen-61908.html#gen-95948\" rel=\"nofollow noreferrer\">table</a> lists all of the functions that POSIX guarantees to be async-signal-safe and so can be called from a signal handler.</p>\n\n<p>By using the 'write' command from this table, the following relatively \"ugly\" solution hopefully will do the trick:</p>\n\n<pre><code>#include <csignal>\n\n#ifdef _WINDOWS_\n#define _exit _Exit\n#else\n#include <unistd.h>\n#endif\n\n#define PRINT_SIGNAL(X) case X: \\\n write (STDERR_FILENO, #X \")\\n\" , sizeof(#X \")\\n\")-1); \\\n break;\n\nvoid catchSignal (int reason) {\n char s[] = \"Caught signal: (\";\n write (STDERR_FILENO, s, sizeof(s) - 1);\n switch (reason)\n {\n // These are the handlers that we catch\n PRINT_SIGNAL(SIGUSR1);\n PRINT_SIGNAL(SIGHUP);\n PRINT_SIGNAL(SIGINT);\n PRINT_SIGNAL(SIGQUIT);\n PRINT_SIGNAL(SIGABRT);\n PRINT_SIGNAL(SIGILL);\n PRINT_SIGNAL(SIGFPE);\n PRINT_SIGNAL(SIGBUS);\n PRINT_SIGNAL(SIGSEGV);\n PRINT_SIGNAL(SIGTERM);\n }\n\n _Exit (1); // 'exit' is not async-signal-safe\n}\n</code></pre>\n\n<p><strong>EDIT:</strong> Building on windows.</p>\n\n<p>After trying to build this one windows, it appears that 'STDERR_FILENO' is not defined. From the documentation however its value appears to be '2'.</p>\n\n<pre><code>#include <io.h>\n#define STDIO_FILENO 2\n</code></pre>\n\n<p><strong>EDIT:</strong> 'exit' should not be called from the signal handler either!</p>\n\n<p>As pointed out by <a href=\"https://stackoverflow.com/questions/103280/portable-way-to-catch-signals-and-report-problem-to-the-user#114413\">fizzer</a>, calling _Exit in the above is a sledge hammer approach for signals such as HUP and TERM. Ideally, when these signals are caught a flag with \"volatile sig_atomic_t\" type can be used to notify the main program that it should exit.</p>\n\n<p>The following I found useful in my searches.</p>\n\n<ol>\n<li><a href=\"http://users.actcom.co.il/~choo/lupg/tutorials/signals/signals-programming.html\" rel=\"nofollow noreferrer\">Introduction To Unix Signals Programming</a> </li>\n<li><a href=\"http://docs.oracle.com/cd/E19963-01/html/821-1601/gen-61908.html\" rel=\"nofollow noreferrer\">Extending Traditional Signals</a></li>\n</ol>\n"
},
{
"answer_id": 104849,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 1,
"selected": false,
"text": "<p>FWIW, 2 is standard error on Windows also, but you're going to need some conditional compilation because their write() is called _write(). You'll also want </p>\n\n<pre><code>#ifdef SIGUSR1 /* or whatever */\n</code></pre>\n\n<p>etc around all references to signals not guaranteed to be defined by the C standard.</p>\n\n<p>Also, as noted above, you don't want to handle SIGUSR1, SIGHUP, SIGINT, SIGQUIT and SIGTERM like this.</p>\n"
},
{
"answer_id": 114413,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 1,
"selected": false,
"text": "<p>Richard, still not enough karma to comment, so a new answer I'm afraid. These are asynchronous signals; you have no idea when they are delivered, so possibly you will be in library code which needs to complete to stay consistent. Signal handlers for these signals are therefore required to return. If you call exit(), the library will do some work post-main(), including calling functions registered with atexit() and cleaning up the standard streams. This processing may fail if, say, your signal arrived in a standard library I/O function. Therefore in C90 you are not allowed to call exit(). I see now C99 relaxes the requirement by providing a new function _Exit() in stdlib.h. _Exit() may safely be called from a handler for an asynchronous signal. _Exit() will not call atexit() functions and may omit cleaning up the standard streams at the implementation's discretion.</p>\n\n<p>To bk1e (commenter a few posts up)\n<em>The fact that SIGSEGV is synchronous is why you can't use functions that are not designed to be reentrant. What if the function that crashed was holding a lock, and the function called by the signal handler tries to acquire the same lock?</em> </p>\n\n<p>This is a possibility, but it's not 'the fact that SIGSEGV is synchronous' which is the problem. Calling non-reentrant functions from the handler is much worse with asynchronous signals for two reasons:</p>\n\n<ul>\n<li>asynchronous signal handlers are\n(generally) hoping to return and\nresume normal program execution. A\nhandler for a synchronous signal is\n(generally) going to terminate\nanyway, so you've not lost much if\nyou crash.</li>\n<li>in a perverse sense, you have absolute control over when a synchronous signal is delivered - it happens as you execute your defective code, and at no other time. You have no control at all over when an async signal is delivered. Unless the OP's own I/O code is ifself the cause of the defect - e.g. outputting a bad char* - his error message has a reasonable chance of succeeding.</li>\n</ul>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11698/"
]
| If by some miracle a segfault occurs in our program, I want to catch the SIGSEGV and let the user (possibly a GUI client) know with a single return code that a serious problem has occurred. At the same time I would like to display information on the command line to show which signal was caught.
Today our signal handler looks as follows:
```
void catchSignal (int reason) {
std :: cerr << "Caught a signal: " << reason << std::endl;
exit (1);
}
```
I can hear the screams of horror with the above, as I have read from this [thread](http://groups.google.com/group/gnu.gcc.help/browse_thread/thread/6184795b39508519/f775c1f48284b212?lnk=gst&q=deadlock#) that it is evil to call a non-reentrant function from a signal handler.
Is there a portable way to handle the signal and provide information to users?
**EDIT:** Or at least portable within the POSIX framework? | This [table](http://docs.oracle.com/cd/E19963-01/html/821-1601/gen-61908.html#gen-95948) lists all of the functions that POSIX guarantees to be async-signal-safe and so can be called from a signal handler.
By using the 'write' command from this table, the following relatively "ugly" solution hopefully will do the trick:
```
#include <csignal>
#ifdef _WINDOWS_
#define _exit _Exit
#else
#include <unistd.h>
#endif
#define PRINT_SIGNAL(X) case X: \
write (STDERR_FILENO, #X ")\n" , sizeof(#X ")\n")-1); \
break;
void catchSignal (int reason) {
char s[] = "Caught signal: (";
write (STDERR_FILENO, s, sizeof(s) - 1);
switch (reason)
{
// These are the handlers that we catch
PRINT_SIGNAL(SIGUSR1);
PRINT_SIGNAL(SIGHUP);
PRINT_SIGNAL(SIGINT);
PRINT_SIGNAL(SIGQUIT);
PRINT_SIGNAL(SIGABRT);
PRINT_SIGNAL(SIGILL);
PRINT_SIGNAL(SIGFPE);
PRINT_SIGNAL(SIGBUS);
PRINT_SIGNAL(SIGSEGV);
PRINT_SIGNAL(SIGTERM);
}
_Exit (1); // 'exit' is not async-signal-safe
}
```
**EDIT:** Building on windows.
After trying to build this one windows, it appears that 'STDERR\_FILENO' is not defined. From the documentation however its value appears to be '2'.
```
#include <io.h>
#define STDIO_FILENO 2
```
**EDIT:** 'exit' should not be called from the signal handler either!
As pointed out by [fizzer](https://stackoverflow.com/questions/103280/portable-way-to-catch-signals-and-report-problem-to-the-user#114413), calling \_Exit in the above is a sledge hammer approach for signals such as HUP and TERM. Ideally, when these signals are caught a flag with "volatile sig\_atomic\_t" type can be used to notify the main program that it should exit.
The following I found useful in my searches.
1. [Introduction To Unix Signals Programming](http://users.actcom.co.il/~choo/lupg/tutorials/signals/signals-programming.html)
2. [Extending Traditional Signals](http://docs.oracle.com/cd/E19963-01/html/821-1601/gen-61908.html) |
103,281 | <p>At the beginning of each PHP page I open up the connection to MySQL, use it throughout the page and close it at the end of the page. However, I often redirect in the middle of the page to another page and so in those cases the connection does not be closed. I understand that this is not bad for performance of the web server since PHP automatically closes all MySQL connections at the end of each page anyway. Are there any other issues here to keep in mind, or is it really true that you don't have to worry about closing your database connections in PHP?</p>
<pre><code>$mysqli = new mysqli("localhost", "root", "", "test");
...do stuff, perhaps redirect to another page...
$mysqli->close();
</code></pre>
| [
{
"answer_id": 103293,
"author": "David McLaughlin",
"author_id": 3404,
"author_profile": "https://Stackoverflow.com/users/3404",
"pm_score": 5,
"selected": true,
"text": "<p>From: <a href=\"http://us3.php.net/manual/en/mysqli.close.php\" rel=\"noreferrer\">http://us3.php.net/manual/en/mysqli.close.php</a></p>\n\n<blockquote>\n <p>\"Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resources to PHP and MySQL faster.\"</p>\n</blockquote>\n"
},
{
"answer_id": 103310,
"author": "steffenj",
"author_id": 15328,
"author_profile": "https://Stackoverflow.com/users/15328",
"pm_score": 1,
"selected": false,
"text": "<p>There might be a limit of how many connections can be open at once, so if you have many user you might run out of SQL connections. In effect, users will see SQL errors instead of nice web pages.</p>\n\n<p>It's better to open a connection to read data, then close it, then display data and once the user clicks \"submit\" you open another connection and then submit all changes.</p>\n"
},
{
"answer_id": 103313,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Just because you redirect doesn't mean the script stops executing. A redirect is just a header being sent. If you don't exit() right after, the rest of your script will continue running. When the script does finish running, it will close off all open connections (or release them back to the pool if you're using persistent connections). Don't worry about it.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103281",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
]
| At the beginning of each PHP page I open up the connection to MySQL, use it throughout the page and close it at the end of the page. However, I often redirect in the middle of the page to another page and so in those cases the connection does not be closed. I understand that this is not bad for performance of the web server since PHP automatically closes all MySQL connections at the end of each page anyway. Are there any other issues here to keep in mind, or is it really true that you don't have to worry about closing your database connections in PHP?
```
$mysqli = new mysqli("localhost", "root", "", "test");
...do stuff, perhaps redirect to another page...
$mysqli->close();
``` | From: <http://us3.php.net/manual/en/mysqli.close.php>
>
> "Open connections (and similar resources) are automatically destroyed at the end of script execution. However, you should still close or free all connections, result sets and statement handles as soon as they are no longer required. This will help return resources to PHP and MySQL faster."
>
>
> |
103,298 | <p>From managed C++, I am calling an unmanaged C++ method which returns a double. How can I convert this double into a managed string?</p>
| [
{
"answer_id": 103350,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 2,
"selected": false,
"text": "<p>C++ is definitely not my strongest skillset. Misread the question, but this should convert to a std::string, not exactly what you are looking for though, but leaving it since it was the original post....</p>\n\n<pre><code>double d = 123.45;\nstd::ostringstream oss;\noss << d;\nstd::string s = oss.str();\n</code></pre>\n\n<p>This should convert to a managed string however..</p>\n\n<pre><code>double d = 123.45\nString^ s = System::Convert::ToString(d);\n</code></pre>\n"
},
{
"answer_id": 103381,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 4,
"selected": true,
"text": "<p>I assume something like</p>\n\n<pre><code>(gcnew System::Double(d))->ToString()\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18170/"
]
| From managed C++, I am calling an unmanaged C++ method which returns a double. How can I convert this double into a managed string? | I assume something like
```
(gcnew System::Double(d))->ToString()
``` |
103,312 | <p>How can I test for the <code>EOF</code> flag in R? </p>
<p>For example:</p>
<pre><code>f <- file(fname, "rb")
while (???) {
a <- readBin(f, "int", n=1)
}
</code></pre>
| [
{
"answer_id": 103396,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 3,
"selected": false,
"text": "<p>The <a href=\"http://wiki.r-project.org/rwiki/doku.php?id=rdoc:base:readlines\" rel=\"noreferrer\">readLines</a> function will return a zero-length value when it reaches the EOF.</p>\n"
},
{
"answer_id": 1204916,
"author": "ars",
"author_id": 2611,
"author_profile": "https://Stackoverflow.com/users/2611",
"pm_score": 3,
"selected": false,
"text": "<p>Try checking the length of data returned by readBin:</p>\n\n<pre><code>while (length(a <- readBin(f, 'int', n=1)) > 0) {\n # do something\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| How can I test for the `EOF` flag in R?
For example:
```
f <- file(fname, "rb")
while (???) {
a <- readBin(f, "int", n=1)
}
``` | The [readLines](http://wiki.r-project.org/rwiki/doku.php?id=rdoc:base:readlines) function will return a zero-length value when it reaches the EOF. |
103,316 | <p>In bash, environmental variables will tab-expand correctly when placed after an echo command, for example:</p>
<pre><code>echo $HOME
</code></pre>
<p>But after cd or cat, bash places a \ before the $ sign, like so:</p>
<pre><code>cd \$HOME
</code></pre>
<p>If I use a variable as the second argument to a command, it won't expand at all:</p>
<pre><code>cp somefile $HOM
</code></pre>
<p>What mysterious option do I have in my .bashrc or .inputrc file that is causing me such distress?</p>
| [
{
"answer_id": 103463,
"author": "Brent ",
"author_id": 3764,
"author_profile": "https://Stackoverflow.com/users/3764",
"pm_score": 2,
"selected": false,
"text": "<p>For the second instance, you can press ESC before tab to solve it.</p>\n\n<p>I don't know the solution to your problem, but you could look in <strong>/etc/bash_completion</strong> or the files under <strong>/etc/bash_completion.d</strong> to determine what commands use autocompletion and how.</p>\n\n<pre><code>help complete\n</code></pre>\n\n<p>Might also be helpful.</p>\n"
},
{
"answer_id": 103921,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.gnu.org/software/bash/manual/bashref.html\" rel=\"nofollow noreferrer\">The Bash Reference Manual</a> has more information than you might want on expansion errata.</p>\n\n<p><a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Programmable-Completion-Builtins\" rel=\"nofollow noreferrer\">Section 8.7</a> looks like it would be the place to start. It give information on the 'complete' function, among other things.</p>\n"
},
{
"answer_id": 110181,
"author": "bd808",
"author_id": 8171,
"author_profile": "https://Stackoverflow.com/users/8171",
"pm_score": 3,
"selected": true,
"text": "<p>Try <strong><em>complete -r cd</em></strong> to remove the special programmatic completion function that many Linux distributions install for the <code>cd</code> command. The function adds searching a list of of directories specified in the CDPATH variable to tab completions for <code>cd</code>, but at the expense of breaking the default completion behavior.</p>\n\n<p>See <a href=\"http://www.gnu.org/software/bash/manual/bashref.html#Programmable-Completion\" rel=\"nofollow noreferrer\">http://www.gnu.org/software/bash/manual/bashref.html#Programmable-Completion</a> for more gory details.</p>\n"
},
{
"answer_id": 6848382,
"author": "kynan",
"author_id": 396967,
"author_profile": "https://Stackoverflow.com/users/396967",
"pm_score": 3,
"selected": false,
"text": "<p>What you're describing is a \"feature\" <a href=\"http://lists.gnu.org/archive/html/bug-bash/2011-02/msg00274.html\" rel=\"noreferrer\">introduced in bash 4.2</a>. So you don't have any mysterious option causing you distress, but just \"intended\" behaviour.</p>\n\n<p>I find this very annoying since I preferred it the way it used to be and haven't found any configuration options yet to get the earlier behaviour back. Playing with <code>complete</code> options as suggested by other answers didn't get me anywhere.</p>\n"
},
{
"answer_id": 12031608,
"author": "Yevgen Yampolskiy",
"author_id": 1321867,
"author_profile": "https://Stackoverflow.com/users/1321867",
"pm_score": 0,
"selected": false,
"text": "<p>I'm answering 4-year-old question! Fantastic!</p>\n\n<p>This is a bash bug/feature which was unintentionally introduced in v4.2, and was unnoticed for a long period of time. This was pointed out by geirha in <a href=\"https://askubuntu.com/questions/41891/bash-auto-complete-for-environment-variables\">this tread</a>. Confirmed as unintended feature <a href=\"http://lists.gnu.org/archive/html/bug-bash/2011-02/msg00296.html\" rel=\"nofollow noreferrer\">here</a> </p>\n\n<p>I came across this problem when running Ubuntu at home. At work I have bash-3.00, so I've spent some time browsing around to see what's going on. I wonder if I can 'downgrade'....</p>\n"
},
{
"answer_id": 42326792,
"author": "RaamEE",
"author_id": 317460,
"author_profile": "https://Stackoverflow.com/users/317460",
"pm_score": 1,
"selected": false,
"text": "<p>Check the answer for \n<a href=\"https://superuser.com/questions/434139/urxvt-tab-expand-environment-variables\">https://superuser.com/questions/434139/urxvt-tab-expand-environment-variables</a> by Dmitry Alexandrov:</p>\n\n<blockquote>\n <p>This is about direxpand option. <strong><code>$ shopt -s direxpand</code></strong> and <code>$FOO_PATH/</code> will be expanded by TAB.</p>\n</blockquote>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103316",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14102/"
]
| In bash, environmental variables will tab-expand correctly when placed after an echo command, for example:
```
echo $HOME
```
But after cd or cat, bash places a \ before the $ sign, like so:
```
cd \$HOME
```
If I use a variable as the second argument to a command, it won't expand at all:
```
cp somefile $HOM
```
What mysterious option do I have in my .bashrc or .inputrc file that is causing me such distress? | Try ***complete -r cd*** to remove the special programmatic completion function that many Linux distributions install for the `cd` command. The function adds searching a list of of directories specified in the CDPATH variable to tab completions for `cd`, but at the expense of breaking the default completion behavior.
See <http://www.gnu.org/software/bash/manual/bashref.html#Programmable-Completion> for more gory details. |
103,325 | <p>Given this XML, what XPath returns all elements whose <code>prop</code> attribute contains <code>Foo</code> (the first three nodes):</p>
<pre><code><bla>
<a prop="Foo1"/>
<a prop="Foo2"/>
<a prop="3Foo"/>
<a prop="Bar"/>
</bla>
</code></pre>
| [
{
"answer_id": 103364,
"author": "toddk",
"author_id": 17640,
"author_profile": "https://Stackoverflow.com/users/17640",
"pm_score": 3,
"selected": false,
"text": "<p>Have you tried something like:</p>\n\n<p>//a[contains(@prop, \"Foo\")]</p>\n\n<p>I've never used the contains function before but suspect that it should work as advertised...</p>\n"
},
{
"answer_id": 103371,
"author": "David Hill",
"author_id": 1181217,
"author_profile": "https://Stackoverflow.com/users/1181217",
"pm_score": 2,
"selected": false,
"text": "<p>/bla/a[contains(@prop, \"foo\")]</p>\n"
},
{
"answer_id": 103377,
"author": "digiguru",
"author_id": 5055,
"author_profile": "https://Stackoverflow.com/users/5055",
"pm_score": 1,
"selected": false,
"text": "<p>For the code above...\n//*[contains(@prop,'foo')] </p>\n"
},
{
"answer_id": 103383,
"author": "Dani Duran",
"author_id": 19010,
"author_profile": "https://Stackoverflow.com/users/19010",
"pm_score": 2,
"selected": false,
"text": "<p>try this:</p>\n\n<p>//a[contains(@prop,'foo')]</p>\n\n<p>that should work for any \"a\" tags in the document</p>\n"
},
{
"answer_id": 103417,
"author": "evilhomer",
"author_id": 2806,
"author_profile": "https://Stackoverflow.com/users/2806",
"pm_score": 10,
"selected": true,
"text": "<pre><code>//a[contains(@prop,'Foo')]\n</code></pre>\n\n<p>Works if I use this XML to get results back.</p>\n\n<pre><code><bla>\n <a prop=\"Foo1\">a</a>\n <a prop=\"Foo2\">b</a>\n <a prop=\"3Foo\">c</a>\n <a prop=\"Bar\">a</a>\n</bla>\n</code></pre>\n\n<p>Edit: \nAnother thing to note is that while the XPath above will return the correct answer for that particular xml, if you want to guarantee you only get the \"a\" elements in element \"bla\", you should as others have mentioned also use</p>\n\n<pre><code>/bla/a[contains(@prop,'Foo')]\n</code></pre>\n\n<p>This will search you all \"a\" elements in your entire xml document, regardless of being nested in a \"blah\" element</p>\n\n<pre><code>//a[contains(@prop,'Foo')] \n</code></pre>\n\n<p>I added this for the sake of thoroughness and in the spirit of stackoverflow. :)</p>\n"
},
{
"answer_id": 103432,
"author": "Metro Smurf",
"author_id": 9664,
"author_profile": "https://Stackoverflow.com/users/9664",
"pm_score": 3,
"selected": false,
"text": "<p>John C is the closest, but XPath is case sensitive, so the correct XPath would be:</p>\n\n<pre><code>/bla/a[contains(@prop, 'Foo')]\n</code></pre>\n"
},
{
"answer_id": 103464,
"author": "1729",
"author_id": 4319,
"author_profile": "https://Stackoverflow.com/users/4319",
"pm_score": 4,
"selected": false,
"text": "<pre><code>descendant-or-self::*[contains(@prop,'Foo')]\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>/bla/a[contains(@prop,'Foo')]\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code>/bla/a[position() <= 3]\n</code></pre>\n\n<p>Dissected:</p>\n\n<pre><code>descendant-or-self::\n</code></pre>\n\n<p>The Axis - search through every node underneath and the node itself. It is often better to say this than //. I have encountered some implementations where // means anywhere (decendant or self of the root node). The other use the default axis.</p>\n\n<pre><code>* or /bla/a\n</code></pre>\n\n<p>The Tag - a wildcard match, and /bla/a is an absolute path.</p>\n\n<pre><code>[contains(@prop,'Foo')] or [position() <= 3]\n</code></pre>\n\n<p>The condition within [ ]. @prop is shorthand for attribute::prop, as attribute is another search axis. Alternatively you can select the first 3 by using the position() function.</p>\n"
},
{
"answer_id": 2336985,
"author": "Alex Beynenson",
"author_id": 1138,
"author_profile": "https://Stackoverflow.com/users/1138",
"pm_score": 5,
"selected": false,
"text": "<p>This XPath will give you all nodes that have attributes containing 'Foo' regardless of node name or attribute name:</p>\n\n<pre><code>//attribute::*[contains(., 'Foo')]/..\n</code></pre>\n\n<p>Of course, if you're more interested in the contents of the attribute themselves, and not necessarily their parent node, just drop the /..</p>\n\n<pre><code>//attribute::*[contains(., 'Foo')]\n</code></pre>\n"
},
{
"answer_id": 15413875,
"author": "SomeDudeSomewhere",
"author_id": 332032,
"author_profile": "https://Stackoverflow.com/users/332032",
"pm_score": 3,
"selected": false,
"text": "<p>If you also need to match the content of the link itself, use text():</p>\n\n<p><code>//a[contains(@href,\"/some_link\")][text()=\"Click here\"]</code></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
]
| Given this XML, what XPath returns all elements whose `prop` attribute contains `Foo` (the first three nodes):
```
<bla>
<a prop="Foo1"/>
<a prop="Foo2"/>
<a prop="3Foo"/>
<a prop="Bar"/>
</bla>
``` | ```
//a[contains(@prop,'Foo')]
```
Works if I use this XML to get results back.
```
<bla>
<a prop="Foo1">a</a>
<a prop="Foo2">b</a>
<a prop="3Foo">c</a>
<a prop="Bar">a</a>
</bla>
```
Edit:
Another thing to note is that while the XPath above will return the correct answer for that particular xml, if you want to guarantee you only get the "a" elements in element "bla", you should as others have mentioned also use
```
/bla/a[contains(@prop,'Foo')]
```
This will search you all "a" elements in your entire xml document, regardless of being nested in a "blah" element
```
//a[contains(@prop,'Foo')]
```
I added this for the sake of thoroughness and in the spirit of stackoverflow. :) |
103,382 | <p>I'm using managed c++ to implement a method that returns a string. I declare the method in my header file using the following signature:</p>
<pre><code>String^ GetWindowText()
</code></pre>
<p>However, when I'm using this method from C#, the signature is:</p>
<pre><code>string GetWindowTextW();
</code></pre>
<p>How do I get rid of the extra "W" at the end of the method's name?</p>
| [
{
"answer_id": 103398,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 3,
"selected": true,
"text": "<p>To get around the preprocessor hackery of the Windows header files, declare it like this:</p>\n\n<pre><code>#undef GetWindowText\nString^ GetWindowText()\n</code></pre>\n\n<p>Note that, if you actually use the Win32 or MFC <code>GetWindowText()</code> routines in your code, you'll need to either redefine the macro or call them as <code>GetWindowTextW()</code>.</p>\n"
},
{
"answer_id": 103412,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "<p>GetWindowText is a win32 api call that is aliased via a macro to GetWindowTextW in your C++ project.</p>\n\n<p>Try adding #undef GetWindowText to you C++ project.</p>\n"
},
{
"answer_id": 103525,
"author": "Panic",
"author_id": 18216,
"author_profile": "https://Stackoverflow.com/users/18216",
"pm_score": 0,
"selected": false,
"text": "<p>Not Managed c++ but C++/CLI for the .net platform. A set of Microsoft extensions to C++ for use with their .Net system.</p>\n\n<p>Bjarne Stroustrup's FAQ <a href=\"http://www.research.att.com/~bs/bs_faq.html#CppCLI\" rel=\"nofollow noreferrer\">http://www.research.att.com/~bs/bs_faq.html#CppCLI</a></p>\n\n<p>C++/CLI is not C++, don't tag it as such. Txs</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103382",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15157/"
]
| I'm using managed c++ to implement a method that returns a string. I declare the method in my header file using the following signature:
```
String^ GetWindowText()
```
However, when I'm using this method from C#, the signature is:
```
string GetWindowTextW();
```
How do I get rid of the extra "W" at the end of the method's name? | To get around the preprocessor hackery of the Windows header files, declare it like this:
```
#undef GetWindowText
String^ GetWindowText()
```
Note that, if you actually use the Win32 or MFC `GetWindowText()` routines in your code, you'll need to either redefine the macro or call them as `GetWindowTextW()`. |
103,389 | <p>Does anyone know why in Oracle 11g when you do a Count(1) with more than one natural join it does a cartesian join and throws the count way off?</p>
<p>Such as </p>
<pre><code>SELECT Count(1) FROM record NATURAL join address NATURAL join person WHERE status=1
AND code = 1 AND state = 'TN'
</code></pre>
<p>This pulls back like 3 million rows when</p>
<pre><code>SELECT * FROM record NATURAL join address NATURAL join person WHERE status=1
AND code = 1 AND state = 'TN'
</code></pre>
<p>pulls back like 36000 rows, which is the correct amount.</p>
<p>Am I just missing something?</p>
<p>Here are the tables I'm using to get this result.</p>
<pre><code>CREATE TABLE addresses (
address_id NUMBER(10,0) NOT NULL,
address_1 VARCHAR2(60) NULL,
address_2 VARCHAR2(60) NULL,
city VARCHAR2(35) NULL,
state CHAR(2) NULL,
zip VARCHAR2(5) NULL,
zip_4 VARCHAR2(4) NULL,
county VARCHAR2(35) NULL,
phone VARCHAR2(11) NULL,
fax VARCHAR2(11) NULL,
origin_network NUMBER(3,0) NOT NULL,
owner_network NUMBER(3,0) NOT NULL,
corrected_address_id NUMBER(10,0) NULL,
"HASH" VARCHAR2(200) NULL
);
CREATE TABLE rates (
rate_id NUMBER(10,0) NOT NULL,
eob VARCHAR2(30) NOT NULL,
network_code NUMBER(3,0) NOT NULL,
product_code VARCHAR2(2) NOT NULL,
rate_type NUMBER(1,0) NOT NULL
);
CREATE TABLE records (
pk_unique_id NUMBER(10,0) NOT NULL,
rate_id NUMBER(10,0) NOT NULL,
address_id NUMBER(10,0) NOT NULL,
effective_date DATE NOT NULL,
term_date DATE NULL,
last_update DATE NULL,
status CHAR(1) NOT NULL,
network_unique_id VARCHAR2(20) NULL,
rate_id_2 NUMBER(10,0) NULL,
contracted_by VARCHAR2(50) NULL,
contract_version VARCHAR2(5) NULL,
bill_address_id NUMBER(10,0) NULL
);
</code></pre>
<p>I should mention this wasn't a problem in Oracle 9i, but when we switched to 11g it became a problem.</p>
| [
{
"answer_id": 103467,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 2,
"selected": false,
"text": "<p>If it happens exactly as you say then it <strong>must</strong> be an optimiser bug, you should report it to Oracle.</p>\n"
},
{
"answer_id": 103491,
"author": "bastos.sergio",
"author_id": 12772,
"author_profile": "https://Stackoverflow.com/users/12772",
"pm_score": 1,
"selected": false,
"text": "<p>you should try a count(*)</p>\n\n<p>There is a difference between the two.<br>\ncount(1) signifies count rows where 1 is not null<br>\ncount(*) signifies count the rows</p>\n"
},
{
"answer_id": 103783,
"author": "bastos.sergio",
"author_id": 12772,
"author_profile": "https://Stackoverflow.com/users/12772",
"pm_score": 1,
"selected": false,
"text": "<p>Just noticed you used 2 natural joins...\nFrom the documentation you can only use a natural join on 2 tables\n<a href=\"http://www.orafaq.com/wiki/Natural_join\" rel=\"nofollow noreferrer\">Natural_Join</a></p>\n"
},
{
"answer_id": 103934,
"author": "Eddie Awad",
"author_id": 17273,
"author_profile": "https://Stackoverflow.com/users/17273",
"pm_score": 4,
"selected": true,
"text": "<p>My advice would be to NOT use NATURAL JOIN. Explicitly define your join conditions to avoid confusion and \"hidden bugs\". Here is the <a href=\"http://68.142.116.68/docs/cd/B28359_01/server.111/b28286/statements_10002.htm#sthref9907\" rel=\"noreferrer\">official NATURAL JOIN Oracle documentation</a> and <a href=\"http://awads.net/wp/2006/03/20/back-to-basics-inner-joins/#comment-2837\" rel=\"noreferrer\">more discussion</a> about this subject. </p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12969/"
]
| Does anyone know why in Oracle 11g when you do a Count(1) with more than one natural join it does a cartesian join and throws the count way off?
Such as
```
SELECT Count(1) FROM record NATURAL join address NATURAL join person WHERE status=1
AND code = 1 AND state = 'TN'
```
This pulls back like 3 million rows when
```
SELECT * FROM record NATURAL join address NATURAL join person WHERE status=1
AND code = 1 AND state = 'TN'
```
pulls back like 36000 rows, which is the correct amount.
Am I just missing something?
Here are the tables I'm using to get this result.
```
CREATE TABLE addresses (
address_id NUMBER(10,0) NOT NULL,
address_1 VARCHAR2(60) NULL,
address_2 VARCHAR2(60) NULL,
city VARCHAR2(35) NULL,
state CHAR(2) NULL,
zip VARCHAR2(5) NULL,
zip_4 VARCHAR2(4) NULL,
county VARCHAR2(35) NULL,
phone VARCHAR2(11) NULL,
fax VARCHAR2(11) NULL,
origin_network NUMBER(3,0) NOT NULL,
owner_network NUMBER(3,0) NOT NULL,
corrected_address_id NUMBER(10,0) NULL,
"HASH" VARCHAR2(200) NULL
);
CREATE TABLE rates (
rate_id NUMBER(10,0) NOT NULL,
eob VARCHAR2(30) NOT NULL,
network_code NUMBER(3,0) NOT NULL,
product_code VARCHAR2(2) NOT NULL,
rate_type NUMBER(1,0) NOT NULL
);
CREATE TABLE records (
pk_unique_id NUMBER(10,0) NOT NULL,
rate_id NUMBER(10,0) NOT NULL,
address_id NUMBER(10,0) NOT NULL,
effective_date DATE NOT NULL,
term_date DATE NULL,
last_update DATE NULL,
status CHAR(1) NOT NULL,
network_unique_id VARCHAR2(20) NULL,
rate_id_2 NUMBER(10,0) NULL,
contracted_by VARCHAR2(50) NULL,
contract_version VARCHAR2(5) NULL,
bill_address_id NUMBER(10,0) NULL
);
```
I should mention this wasn't a problem in Oracle 9i, but when we switched to 11g it became a problem. | My advice would be to NOT use NATURAL JOIN. Explicitly define your join conditions to avoid confusion and "hidden bugs". Here is the [official NATURAL JOIN Oracle documentation](http://68.142.116.68/docs/cd/B28359_01/server.111/b28286/statements_10002.htm#sthref9907) and [more discussion](http://awads.net/wp/2006/03/20/back-to-basics-inner-joins/#comment-2837) about this subject. |
103,407 | <p>When attempting to call functions in <code>math.h</code>, I'm getting link errors like the following </p>
<pre><code>undefined reference to sqrt
</code></pre>
<p>But I'm doing a <code>#include <math.h></code><br>
I'm using gcc and compiling as follows:</p>
<pre><code>gcc -Wall -D_GNU_SOURCE blah.c -o blah
</code></pre>
<p>Why can't the linker find the definition for <code>sqrt</code>?</p>
| [
{
"answer_id": 103411,
"author": "FreeMemory",
"author_id": 2132,
"author_profile": "https://Stackoverflow.com/users/2132",
"pm_score": 2,
"selected": false,
"text": "<p>You need to link the math library explicitly. Add <code>-lm</code> to the flags you're passing to gcc so that the linker knows to link <code>libm.a</code></p>\n"
},
{
"answer_id": 103431,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 4,
"selected": true,
"text": "<p>Add -lm to the command when you call gcc:<br>\ngcc -Wall -D_GNU_SOURCE blah.c -o blah -lm</p>\n\n<p>This will tell the linker to link with the math library. Including math.h will tell the compiler that the math functions like sqrt() exist, but they are defined in a separate library, which the linker needs to pack with your executable.</p>\n\n<p>As FreeMemory pointed out the library is called libm.a . On Unix-like systems, the rule for naming libraries is lib[blah].a . Then if you want to link them to your executable you use -l[blah] .</p>\n"
},
{
"answer_id": 45885013,
"author": "Billy Raseman",
"author_id": 6451035,
"author_profile": "https://Stackoverflow.com/users/6451035",
"pm_score": 2,
"selected": false,
"text": "<p>Append <code>-lm</code> to the end of the gcc command to link the math library: </p>\n\n<pre><code>gcc -Wall -D_GNU_SOURCE blah.c -o blah -lm\n</code></pre>\n\n<p>For things to be linked properly, the order of the compiler flags matters! Specifically, the <code>-lm</code> should be placed <a href=\"https://stackoverflow.com/questions/16344445/undefined-reference-to-pow-even-with-math-h-and-the-library-link-lm\">at the end of the line</a>.</p>\n\n<p>If you're wondering why the <code>math.h</code> library needs to be included at all when compiling in C, check out this explanation <a href=\"https://stackoverflow.com/questions/1033898/why-do-you-have-to-link-the-math-library-in-c\">here</a>. </p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103407",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2132/"
]
| When attempting to call functions in `math.h`, I'm getting link errors like the following
```
undefined reference to sqrt
```
But I'm doing a `#include <math.h>`
I'm using gcc and compiling as follows:
```
gcc -Wall -D_GNU_SOURCE blah.c -o blah
```
Why can't the linker find the definition for `sqrt`? | Add -lm to the command when you call gcc:
gcc -Wall -D\_GNU\_SOURCE blah.c -o blah -lm
This will tell the linker to link with the math library. Including math.h will tell the compiler that the math functions like sqrt() exist, but they are defined in a separate library, which the linker needs to pack with your executable.
As FreeMemory pointed out the library is called libm.a . On Unix-like systems, the rule for naming libraries is lib[blah].a . Then if you want to link them to your executable you use -l[blah] . |
103,460 | <p>I need to get the name of the machine my .NET app is running on. What is the best way to do this?</p>
| [
{
"answer_id": 103468,
"author": "Billy Jo",
"author_id": 3447,
"author_profile": "https://Stackoverflow.com/users/3447",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.environment.machinename.aspx\" rel=\"nofollow noreferrer\"><code>System.Environment.MachineName</code></a></p>\n"
},
{
"answer_id": 103478,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 1,
"selected": false,
"text": "<p><s>Try <a href=\"http://msdn.microsoft.com/en-us/library/system.environment.machinename.aspx\" rel=\"nofollow noreferrer\">Environment.MachineName</a>.</s> Ray actually has the <strong>best</strong> <a href=\"https://stackoverflow.com/questions/103460/whats-the-best-way-to-determine-the-name-of-your-machine-in-a-net-app#104154\">answer</a>, although you will need to use some interop code.</p>\n"
},
{
"answer_id": 104154,
"author": "Ray Hayes",
"author_id": 7093,
"author_profile": "https://Stackoverflow.com/users/7093",
"pm_score": 4,
"selected": true,
"text": "<p>Whilst others have already said that the <a href=\"http://msdn.microsoft.com/en-us/library/system.environment.machinename.aspx\" rel=\"noreferrer\">System.Environment.MachineName</a> returns you the name of the machine, beware...</p>\n\n<p>That property is only returning the NetBIOS name (and only if your application has EnvironmentPermissionAccess.Read permissions). It is possible for your machine name to exceed the length defined in:</p>\n\n<pre><code>MAX_COMPUTERNAME_LENGTH \n</code></pre>\n\n<p>In these cases, System.Environment.MachineName will not return you the correct name! </p>\n\n<p>Also note, there are several names your machine could go by and in Win32 there is a method <a href=\"http://msdn.microsoft.com/en-us/library/ms724301(VS.85).aspx\" rel=\"noreferrer\">GetComputerNameEx</a> that is capable of getting the name matching each of these different name types:</p>\n\n<ul>\n<li>ComputerNameDnsDomain</li>\n<li>ComputerNameDnsFullyQualified</li>\n<li>ComputerNameDnsHostname</li>\n<li>ComputerNameNetBIOS</li>\n<li>ComputerNamePhysicalDnsDomain</li>\n<li>ComputerNamePhysicalDnsFullyQualified</li>\n<li>ComputerNamePhysicalDnsHostname</li>\n<li>ComputerNamePhysicalNetBIOS</li>\n</ul>\n\n<p>If you require this information, you're likely to need to go to Win32 through p/invoke, such as:</p>\n\n<pre><code>class Class1\n{\n enum COMPUTER_NAME_FORMAT\n {\n ComputerNameNetBIOS,\n ComputerNameDnsHostname,\n ComputerNameDnsDomain,\n ComputerNameDnsFullyQualified,\n ComputerNamePhysicalNetBIOS,\n ComputerNamePhysicalDnsHostname,\n ComputerNamePhysicalDnsDomain,\n ComputerNamePhysicalDnsFullyQualified\n }\n\n [DllImport(\"kernel32.dll\", SetLastError=true, CharSet=CharSet.Auto)]\n static extern bool GetComputerNameEx(COMPUTER_NAME_FORMAT NameType,\n [Out] StringBuilder lpBuffer, ref uint lpnSize);\n\n [STAThread]\n static void Main(string[] args)\n {\n bool success;\n StringBuilder name = new StringBuilder(260);\n uint size = 260;\n success = GetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNameDnsDomain,\n name, ref size);\n Console.WriteLine(name.ToString());\n }\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103460",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14101/"
]
| I need to get the name of the machine my .NET app is running on. What is the best way to do this? | Whilst others have already said that the [System.Environment.MachineName](http://msdn.microsoft.com/en-us/library/system.environment.machinename.aspx) returns you the name of the machine, beware...
That property is only returning the NetBIOS name (and only if your application has EnvironmentPermissionAccess.Read permissions). It is possible for your machine name to exceed the length defined in:
```
MAX_COMPUTERNAME_LENGTH
```
In these cases, System.Environment.MachineName will not return you the correct name!
Also note, there are several names your machine could go by and in Win32 there is a method [GetComputerNameEx](http://msdn.microsoft.com/en-us/library/ms724301(VS.85).aspx) that is capable of getting the name matching each of these different name types:
* ComputerNameDnsDomain
* ComputerNameDnsFullyQualified
* ComputerNameDnsHostname
* ComputerNameNetBIOS
* ComputerNamePhysicalDnsDomain
* ComputerNamePhysicalDnsFullyQualified
* ComputerNamePhysicalDnsHostname
* ComputerNamePhysicalNetBIOS
If you require this information, you're likely to need to go to Win32 through p/invoke, such as:
```
class Class1
{
enum COMPUTER_NAME_FORMAT
{
ComputerNameNetBIOS,
ComputerNameDnsHostname,
ComputerNameDnsDomain,
ComputerNameDnsFullyQualified,
ComputerNamePhysicalNetBIOS,
ComputerNamePhysicalDnsHostname,
ComputerNamePhysicalDnsDomain,
ComputerNamePhysicalDnsFullyQualified
}
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern bool GetComputerNameEx(COMPUTER_NAME_FORMAT NameType,
[Out] StringBuilder lpBuffer, ref uint lpnSize);
[STAThread]
static void Main(string[] args)
{
bool success;
StringBuilder name = new StringBuilder(260);
uint size = 260;
success = GetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNameDnsDomain,
name, ref size);
Console.WriteLine(name.ToString());
}
}
``` |
103,489 | <p>Below is the code I use to build an HTML table on the fly (using JSON data received from the server).</p>
<p>I display an animated pleasewait (.gif) graphic while the data is loading. However, the graphic freezes while the JavaScript function is building the table. At first, I was just happy to make this happen (display the table), I guess now I need to work on efficiency. At the very least I need to stop the animated graphic from freezing. I can go to a static "Loading" display, but I would rather make this method work.</p>
<p>Suggestions for my pleasewait display? And efficiency? Possibly a better way to build the table? Or maybe not a table, but some other "table" like display</p>
<pre><code>var t = eval( "(" + request + ")" ) ;
var myTable = '' ;
myTable += '<table id="myTable" cellspacing=0 cellpadding=2 border=1>' ;
myTable += "<thead>" ;
myTable += "<tr>";
for (var i = 0; i < t.hdrs.length; i++) {
myTable += "<th>" + header + "</th>";
}
myTable += "</tr>" ;
myTable += "</thead>" ;
myTable += "<tbody>" ;
for (var i = 0; i < t.data.length; i++) {
myTable += '<tr>';
for (var j = 0; j < t.hdrs.length; j++) {
myTable += '<td>';
if (t.data[i][t.hdrs[j]] == "") {
myTable += "&nbsp;" ;
}
else {
myTable += t.data[i][t.hdrs[j]] ;
}
myTable += "</td>";
}
myTable += "</tr>";
}
myTable += "</tbody>" ;
myTable += "</table>" ;
$("#result").append(myTable) ;
$("#PleaseWaitGraphic").addClass("hide");
$(".rslt").removeClass("hide") ;
</code></pre>
| [
{
"answer_id": 103527,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 2,
"selected": false,
"text": "<p>What you are doing is building a string, and then parsing it all at once upon insertion. What about creating an actual table element (i.e. <code>$(\"<table>\")</code>), and then adding each row to it in turn? By the time you actually insert it into the page, the DOM nodes will all have been constructed, so it shouldn't be as big a hit.</p>\n"
},
{
"answer_id": 103690,
"author": "neouser99",
"author_id": 10669,
"author_profile": "https://Stackoverflow.com/users/10669",
"pm_score": 0,
"selected": false,
"text": "<p>For starters, check out <a href=\"http://flydom.socianet.com/\" rel=\"nofollow noreferrer\">flydom</a> and it's variants, they will help termendously. Could you possibly give more context? If this is not in the onload and just pasted in the page, just wrapping the whole thing in $(function () { /* code */ }) will probably clean up everything you are having problems with. Inline JS is executed immediately, which means that loop for the table. onload is an event and essentially 'detached'.</p>\n"
},
{
"answer_id": 104053,
"author": "Lasar",
"author_id": 9438,
"author_profile": "https://Stackoverflow.com/users/9438",
"pm_score": -1,
"selected": false,
"text": "<p>You could insert the table into the DOM bit by bit. Honestly I'm not entirely sure if this will help with your problem, but it's worth a try. I'd do it roughly like this (untested code, could be refine some more):</p>\n\n<pre><code>$(\"#result\").append('<table id=\"myTable\" cellspacing=0 cellpadding=2 border=1></table>');\n$('#myTable').append('<thead><tr></tr></thead>');\n$('#myTable').append('<tbody></tbody>');\n\nfor (var i = 0; i < t.hdrs.length; i++) { \n $('#myTable thead tr').append('<th>'+header+'</th>');\n}\n\nfor (var i = 0; i < t.data.length; i++) { \n myTr = '<tr>';\n for (var j = 0; j < t.hdrs.length; j++) { \n myTr += '<td>';\n if (t.data[i][t.hdrs[j]] == \"\") { \n myTr += \"&nbsp;\" ; \n }\n else { \n myTr += t.data[i][t.hdrs[j]] ; \n }\n myTr += \"</td>\";\n }\n myTr += \"</tr>\";\n $('#myTable tbody').append(myTr);\n}\n\n$(\"#PleaseWaitGraphic\").addClass(\"hide\");\n$(\".rslt\").removeClass(\"hide\") ;\n</code></pre>\n"
},
{
"answer_id": 104139,
"author": "Chase Seibert",
"author_id": 7679,
"author_profile": "https://Stackoverflow.com/users/7679",
"pm_score": 0,
"selected": false,
"text": "<p>My experience has been that there are two discrete delays. One is concatenating all those strings together. The other is when the browser actually tries to render the string. Typically, it's IE that has the most trouble with UI freezes, in part because it's a lot slower at running javascript. This should get better in IE8.</p>\n\n<p>What I would suggest in your case is breaking the operation into steps. Say for a 100 row table, you produce a valid 10 row table first. Then you output that to screen and use a setTimeout to return control to the browser so the UI stops blocking. When the setTimeout comes back, you do the next 10 rows, etc.</p>\n\n<p>Creating the table using DOM is certainly \"cleaner\", as others have said. However, there is a steep price to pay in terms of performance. See the excellent <a href=\"http://www.quirksmode.org/dom/innerhtml.html\" rel=\"nofollow noreferrer\">quirksmode</a> article on this subject, which has some benchmarks you can run yourself.</p>\n\n<p>Long story short, innerHTML is much, much faster than DOM, even on modern JS engines.</p>\n"
},
{
"answer_id": 104159,
"author": "Guichard",
"author_id": 13628,
"author_profile": "https://Stackoverflow.com/users/13628",
"pm_score": 4,
"selected": false,
"text": "<p>I've been using <a href=\"http://jtemplates.tpython.com/\" rel=\"noreferrer\">JTemplates</a> to accomplish what you are describing. Dave Ward has an example on his blog <a href=\"http://encosia.com/2008/06/26/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/\" rel=\"noreferrer\">here</a>. The main benefit of JTemplates is that your html isn't woven into your javascript. You write a template and call two functions to have jTemplate build the html from your template and your json.</p>\n"
},
{
"answer_id": 106624,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 6,
"selected": true,
"text": "<p>You basically want to set up your loops so they yield to other threads every so often. Here is some example code from <a href=\"http://www.julienlecomte.net/blog/2007/10/28/\" rel=\"noreferrer\">this article</a> on the topic of running CPU intensive operations without freezing your UI:</p>\n\n<pre><code>function doSomething (progressFn [, additional arguments]) {\n // Initialize a few things here...\n (function () {\n // Do a little bit of work here...\n if (continuation condition) {\n // Inform the application of the progress\n progressFn(value, total);\n // Process next chunk\n setTimeout(arguments.callee, 0);\n }\n })();\n}\n</code></pre>\n\n<p>As far as simplifying the production of HTML in your script, if you're using jQuery, you might give my <a href=\"http://plugins.jquery.com/project/simple-templates\" rel=\"noreferrer\">Simple Templates</a> plug-in a try. It tidies up the process by cutting down drastically on the number of concatenations you have to do. It performs pretty well, too after I recently did some refactoring that resulted in a pretty big <a href=\"http://andrew.hedges.name/experiments/simple-templates-speed-test/\" rel=\"noreferrer\">speed increase</a>. Here's an example (without doing <em>all</em> of the work for you!):</p>\n\n<pre><code>var t = eval('(' + request + ')') ;\nvar templates = {\n tr : '<tr>#{row}</tr>',\n th : '<th>#{header}</th>',\n td : '<td>#{cell}</td>'\n};\nvar table = '<table><thead><tr>';\n$.each(t.hdrs, function (key, val) {\n table += $.tmpl(templates.th, {header: val});\n});\n...\n</code></pre>\n"
},
{
"answer_id": 107571,
"author": "bhollis",
"author_id": 11284,
"author_profile": "https://Stackoverflow.com/users/11284",
"pm_score": 2,
"selected": false,
"text": "<p>Using innerHTML can definitely be much faster than using jQuery's HTML-to-DOM-ifier, which uses innerHTML but does a lot of processing on the inputs.</p>\n\n<p>I'd suggest checking out <a href=\"http://github.com/raid-ox/chain.js/wikis\" rel=\"nofollow noreferrer\">chain.js</a> as a way to quickly build out tables and other repeating data structures from JavaScript objects. It's a really lightweight, smart databinding plugin for jQuery.</p>\n"
},
{
"answer_id": 345372,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Search the web for JavaScript and StringBuilder. Once you have a JavaScript string builder make sure you use the <code>.append</code> method for every concatenation. That is, you don't want to have any <code>+</code> concatenations. After that, search for JavaScript and replacehtml. Use this function instead of <code>innerHTML</code>.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
]
| Below is the code I use to build an HTML table on the fly (using JSON data received from the server).
I display an animated pleasewait (.gif) graphic while the data is loading. However, the graphic freezes while the JavaScript function is building the table. At first, I was just happy to make this happen (display the table), I guess now I need to work on efficiency. At the very least I need to stop the animated graphic from freezing. I can go to a static "Loading" display, but I would rather make this method work.
Suggestions for my pleasewait display? And efficiency? Possibly a better way to build the table? Or maybe not a table, but some other "table" like display
```
var t = eval( "(" + request + ")" ) ;
var myTable = '' ;
myTable += '<table id="myTable" cellspacing=0 cellpadding=2 border=1>' ;
myTable += "<thead>" ;
myTable += "<tr>";
for (var i = 0; i < t.hdrs.length; i++) {
myTable += "<th>" + header + "</th>";
}
myTable += "</tr>" ;
myTable += "</thead>" ;
myTable += "<tbody>" ;
for (var i = 0; i < t.data.length; i++) {
myTable += '<tr>';
for (var j = 0; j < t.hdrs.length; j++) {
myTable += '<td>';
if (t.data[i][t.hdrs[j]] == "") {
myTable += " " ;
}
else {
myTable += t.data[i][t.hdrs[j]] ;
}
myTable += "</td>";
}
myTable += "</tr>";
}
myTable += "</tbody>" ;
myTable += "</table>" ;
$("#result").append(myTable) ;
$("#PleaseWaitGraphic").addClass("hide");
$(".rslt").removeClass("hide") ;
``` | You basically want to set up your loops so they yield to other threads every so often. Here is some example code from [this article](http://www.julienlecomte.net/blog/2007/10/28/) on the topic of running CPU intensive operations without freezing your UI:
```
function doSomething (progressFn [, additional arguments]) {
// Initialize a few things here...
(function () {
// Do a little bit of work here...
if (continuation condition) {
// Inform the application of the progress
progressFn(value, total);
// Process next chunk
setTimeout(arguments.callee, 0);
}
})();
}
```
As far as simplifying the production of HTML in your script, if you're using jQuery, you might give my [Simple Templates](http://plugins.jquery.com/project/simple-templates) plug-in a try. It tidies up the process by cutting down drastically on the number of concatenations you have to do. It performs pretty well, too after I recently did some refactoring that resulted in a pretty big [speed increase](http://andrew.hedges.name/experiments/simple-templates-speed-test/). Here's an example (without doing *all* of the work for you!):
```
var t = eval('(' + request + ')') ;
var templates = {
tr : '<tr>#{row}</tr>',
th : '<th>#{header}</th>',
td : '<td>#{cell}</td>'
};
var table = '<table><thead><tr>';
$.each(t.hdrs, function (key, val) {
table += $.tmpl(templates.th, {header: val});
});
...
``` |
103,508 | <p>I'm using start.jar and stop.jar to stop and start my jetty instance.
I restart by calling stop.jar, then start.jar.
The problem is, if I don't sleep long enough between stop.jar and start.jar I start getting these random ClassNotFoundExceptions and the application doesn't work correctly.</p>
<p>Sleeping for a longer period of time between stop and start is my current option.</p>
<p>I also heard from someone that I should have something that manages my threads so that I end those before jetty finishes.
Is this correct? The question I have about this is that stop.jar returns immediately, so it doesn't seem to help me, unless there's something I'm missing.
Another option might be to poll the log file, but that's pretty ugly.</p>
<p>What's the best way of restarting jetty?</p>
<p>Gilbert: The Ant task is definitely not a bad way of doing it. However, it sleeps for a set amount of time, which is exactly what I'm trying to avoid.</p>
| [
{
"answer_id": 103550,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Did you try JFGI?\nSetting up Ant task that could do the work for you?</p>\n\n<p>This blog post details how to setup targets that can start and stop jetty for you. You could easily cobble together another target called 'jetty-restart' which depends on 'jetty-stop' and then calls 'jetty-start'.</p>\n\n<p><a href=\"http://ptrthomas.wordpress.com/2006/10/10/how-to-start-and-stop-jetty-from-ant/\" rel=\"nofollow noreferrer\">http://ptrthomas.wordpress.com/2006/10/10/how-to-start-and-stop-jetty-from-ant/</a></p>\n"
},
{
"answer_id": 159906,
"author": "Tim Howland",
"author_id": 4276,
"author_profile": "https://Stackoverflow.com/users/4276",
"pm_score": 1,
"selected": false,
"text": "<p>Can you write a shell script that does something like this after calling shutdown and before calling startup?</p>\n\n<pre>\n\nLISTEN_PORT = `netstat -vatn | grep LISTEN| grep 8080 | wc -l `\nwhile [$LISTEN_PORT -ne 0] ; do\n sleep 1\n LISTEN_PORT = `netstat -vatn | grep LISTEN| grep 8080 | wc -l `\ndone\n</pre> \n"
},
{
"answer_id": 476363,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>This thread looks old but posting anyway, may help someone. A cross-platform approach:</p>\n\n<p><a href=\"http://ptrthomas.wordpress.com/2009/01/24/how-to-start-and-stop-jetty-revisited/\" rel=\"nofollow noreferrer\">http://ptrthomas.wordpress.com/2009/01/24/how-to-start-and-stop-jetty-revisited/</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103508",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I'm using start.jar and stop.jar to stop and start my jetty instance.
I restart by calling stop.jar, then start.jar.
The problem is, if I don't sleep long enough between stop.jar and start.jar I start getting these random ClassNotFoundExceptions and the application doesn't work correctly.
Sleeping for a longer period of time between stop and start is my current option.
I also heard from someone that I should have something that manages my threads so that I end those before jetty finishes.
Is this correct? The question I have about this is that stop.jar returns immediately, so it doesn't seem to help me, unless there's something I'm missing.
Another option might be to poll the log file, but that's pretty ugly.
What's the best way of restarting jetty?
Gilbert: The Ant task is definitely not a bad way of doing it. However, it sleeps for a set amount of time, which is exactly what I'm trying to avoid. | Can you write a shell script that does something like this after calling shutdown and before calling startup?
```
LISTEN_PORT = `netstat -vatn | grep LISTEN| grep 8080 | wc -l `
while [$LISTEN_PORT -ne 0] ; do
sleep 1
LISTEN_PORT = `netstat -vatn | grep LISTEN| grep 8080 | wc -l `
done
``` |
103,512 | <p>I've heard that the <code>static_cast</code> function should be preferred to C-style or simple function-style casting. Is this true? Why?</p>
| [
{
"answer_id": 103529,
"author": "prakash",
"author_id": 123,
"author_profile": "https://Stackoverflow.com/users/123",
"pm_score": 3,
"selected": false,
"text": "<p>static_cast, aside from manipulating pointers to classes, can also be used to perform conversions explicitly defined in classes, as well as to perform standard conversions between fundamental types:</p>\n\n<pre><code>double d = 3.14159265;\nint i = static_cast<int>(d);\n</code></pre>\n"
},
{
"answer_id": 103612,
"author": "DrPizza",
"author_id": 2131,
"author_profile": "https://Stackoverflow.com/users/2131",
"pm_score": 5,
"selected": false,
"text": "<p><code>static_cast</code> means that you can't accidentally <code>const_cast</code> or <code>reinterpret_cast</code>, which is a good thing.</p>\n"
},
{
"answer_id": 103619,
"author": "Pitarou",
"author_id": 1260685,
"author_profile": "https://Stackoverflow.com/users/1260685",
"pm_score": 3,
"selected": false,
"text": "<p>It's about how much type-safety you want to impose.</p>\n\n<p>When you write <code>(bar) foo</code> (which is equivalent to <code>reinterpret_cast<bar> foo</code> if you haven't provided a type conversion operator) you are telling the compiler to ignore type safety, and just do as it's told.</p>\n\n<p>When you write <code>static_cast<bar> foo</code> you are asking the compiler to at least check that the type conversion makes sense and, for integral types, to insert some conversion code.</p>\n\n<hr>\n\n<p><strong>EDIT 2014-02-26</strong></p>\n\n<p>I wrote this answer more than 5 years ago, and I got it wrong. (See comments.) But it still gets upvotes!</p>\n"
},
{
"answer_id": 103696,
"author": "Karl",
"author_id": 17613,
"author_profile": "https://Stackoverflow.com/users/17613",
"pm_score": 7,
"selected": false,
"text": "<p>One pragmatic tip: you can search easily for the static_cast keyword in your source code if you plan to tidy up the project.</p>\n"
},
{
"answer_id": 103868,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 10,
"selected": true,
"text": "<p>The main reason is that classic C casts make no distinction between what we call <code>static_cast<>()</code>, <code>reinterpret_cast<>()</code>, <code>const_cast<>()</code>, and <code>dynamic_cast<>()</code>. These four things are completely different.</p>\n\n<p>A <code>static_cast<>()</code> is usually safe. There is a valid conversion in the language, or an appropriate constructor that makes it possible. The only time it's a bit risky is when you cast down to an inherited class; you must make sure that the object is actually the descendant that you claim it is, by means external to the language (like a flag in the object). A <code>dynamic_cast<>()</code> is safe as long as the result is checked (pointer) or a possible exception is taken into account (reference). </p>\n\n<p>A <code>reinterpret_cast<>()</code> (or a <code>const_cast<>()</code>) on the other hand is always dangerous. You tell the compiler: \"trust me: I know this doesn't look like a <code>foo</code> (this looks as if it isn't mutable), but it is\". </p>\n\n<p>The first problem is that it's almost impossible to tell which one will occur in a C-style cast without looking at large and disperse pieces of code and knowing all the rules.</p>\n\n<p>Let's assume these:</p>\n\n<pre><code>class CDerivedClass : public CMyBase {...};\nclass CMyOtherStuff {...} ;\n\nCMyBase *pSomething; // filled somewhere\n</code></pre>\n\n<p>Now, these two are compiled the same way:</p>\n\n<pre><code>CDerivedClass *pMyObject;\npMyObject = static_cast<CDerivedClass*>(pSomething); // Safe; as long as we checked\n\npMyObject = (CDerivedClass*)(pSomething); // Same as static_cast<>\n // Safe; as long as we checked\n // but harder to read\n</code></pre>\n\n<p>However, let's see this almost identical code:</p>\n\n<pre><code>CMyOtherStuff *pOther;\npOther = static_cast<CMyOtherStuff*>(pSomething); // Compiler error: Can't convert\n\npOther = (CMyOtherStuff*)(pSomething); // No compiler error.\n // Same as reinterpret_cast<>\n // and it's wrong!!!\n</code></pre>\n\n<p>As you can see, there is no easy way to distinguish between the two situations without knowing a lot about all the classes involved.</p>\n\n<p>The second problem is that the C-style casts are too hard to locate. In complex expressions it can be very hard to see C-style casts. It is virtually impossible to write an automated tool that needs to locate C-style casts (for example a search tool) without a full blown C++ compiler front-end. On the other hand, it's easy to search for \"static_cast<\" or \"reinterpret_cast<\".</p>\n\n<pre><code>pOther = reinterpret_cast<CMyOtherStuff*>(pSomething);\n // No compiler error.\n // but the presence of a reinterpret_cast<> is \n // like a Siren with Red Flashing Lights in your code.\n // The mere typing of it should cause you to feel VERY uncomfortable.\n</code></pre>\n\n<p>That means that, not only are C-style casts more dangerous, but it's a lot harder to find them all to make sure that they are correct.</p>\n"
},
{
"answer_id": 103871,
"author": "Dusty Campbell",
"author_id": 2174,
"author_profile": "https://Stackoverflow.com/users/2174",
"pm_score": 5,
"selected": false,
"text": "<p>The question is bigger than just using whether <code>static_cast<></code> or C-style casting because there are different things that happen when using C-style casts. The C++ casting operators are intended to make those different operations more explicit.</p>\n<p>On the surface <code>static_cast<></code> and C-style casts appear to be the same thing, for example when casting one value to another:</p>\n<pre><code>int i;\ndouble d = (double)i; //C-style cast\ndouble d2 = static_cast<double>( i ); //C++ cast\n</code></pre>\n<p>Both of those cast the integer value to a double. However when working with pointers things get more complicated. Some examples:</p>\n<pre><code>class A {};\nclass B : public A {};\n\nA* a = new B;\nB* b = (B*)a; //(1) what is this supposed to do?\n\nchar* c = (char*)new int( 5 ); //(2) that weird?\nchar* c1 = static_cast<char*>( new int( 5 ) ); //(3) compile time error\n</code></pre>\n<p>In this example (1) may be OK because the object pointed to by A is really an instance of B. But what if you don't know at that point in code what <code>a</code> actually points to?</p>\n<p>(2) may be perfectly legal (you only want to look at one byte of the integer), but it could also be a mistake in which case an error would be nice, like (3).</p>\n<p>The C++ casting operators are intended to expose these issues in the code by providing compile-time or run-time errors when possible.</p>\n<p>So, for strict "value casting" you can use <code>static_cast<></code>. If you want run-time polymorphic casting of pointers use <code>dynamic_cast<></code>. If you really want to forget about types, you can use <code>reintrepret_cast<></code>. And to just throw <code>const</code> out the window there is <code>const_cast<></code>.</p>\n<p>They just make the code more explicit so that it looks like you know what you were doing.</p>\n"
},
{
"answer_id": 103902,
"author": "Konrad",
"author_id": 18664,
"author_profile": "https://Stackoverflow.com/users/18664",
"pm_score": 3,
"selected": false,
"text": "<p>C Style casts are easy to miss in a block of code. C++ style casts are not only better practice; they offer a much greater degree of flexibility.</p>\n\n<p>reinterpret_cast allows integral to pointer type conversions, however can be unsafe if misused.</p>\n\n<p>static_cast offers good conversion for numeric types e.g. from as enums to ints or ints to floats or any data types you are confident of type. It does not perform any run time checks.</p>\n\n<p>dynamic_cast on the other hand will perform these checks flagging any ambiguous assignments or conversions. It only works on pointers and references and incurs an overhead.</p>\n\n<p>There are a couple of others but these are the main ones you will come across.</p>\n"
},
{
"answer_id": 103970,
"author": "JohnMcG",
"author_id": 1674,
"author_profile": "https://Stackoverflow.com/users/1674",
"pm_score": 3,
"selected": false,
"text": "<ol>\n<li>Allows casts to be found easily in\nyour code using grep or similar\ntools. </li>\n<li>Makes it explicit what kind\n of cast you are doing, and engaging\n the compiler's help in enforcing it.\n If you only want to cast away\n const-ness, then you can use\n const_cast, which will not allow you\n to do other types of conversions.</li>\n<li>Casts are inherently ugly -- you as\n a programmer are overruling how the\n compiler would ordinarily treat your\n code. You are saying to the\n compiler, \"I know better than you.\"\n That being the case, it makes sense\n that performing a cast should be a\n moderately painful thing to do, and\n that they should stick out in your\n code, since they are a likely source\n of problems.</li>\n</ol>\n\n<p>See <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321334876\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">Effective C++</a> Introduction</p>\n"
},
{
"answer_id": 26269263,
"author": "Hossein",
"author_id": 2736559,
"author_profile": "https://Stackoverflow.com/users/2736559",
"pm_score": 7,
"selected": false,
"text": "<blockquote>\n <p><strong>In short</strong>:</p>\n \n <ol>\n <li><code>static_cast<>()</code> gives you a compile time checking ability, C-Style\n cast doesn't.</li>\n <li><code>static_cast<>()</code> can be spotted easily\n anywhere inside a C++ source code; in contrast, C_Style cast is harder to spot.</li>\n <li>Intentions are conveyed much better using C++ casts.</li>\n </ol>\n \n <p><strong>More Explanation</strong>:</p>\n \n <p>The static cast performs conversions between <strong>compatible types</strong>. It\n is similar to the C-style cast, but is more restrictive. For example,\n the C-style cast would allow an integer pointer to point to a char.</p>\n\n<pre><code>char c = 10; // 1 byte\nint *p = (int*)&c; // 4 bytes\n</code></pre>\n \n <p>Since this results in a 4-byte pointer pointing to 1 byte of allocated\n memory, writing to this pointer will either cause a run-time error or\n will overwrite some adjacent memory.</p>\n\n<pre><code>*p = 5; // run-time error: stack corruption\n</code></pre>\n \n <p>In contrast to the C-style cast, the static cast will allow the\n compiler to check that the pointer and pointee data types are\n compatible, which allows the programmer to catch this incorrect\n pointer assignment during compilation.</p>\n\n<pre><code>int *q = static_cast<int*>(&c); // compile-time error\n</code></pre>\n</blockquote>\n\n<p>Read more on:<br>\n<a href=\"https://stackoverflow.com/a/18414126/2736559\">What is the difference between static_cast<> and C style casting </a><br>\nand<br>\n<a href=\"https://stackoverflow.com/questions/28002/regular-cast-vs-static-cast-vs-dynamic-cast/18414172#18414172\">Regular cast vs. static_cast vs. dynamic_cast </a> </p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11575/"
]
| I've heard that the `static_cast` function should be preferred to C-style or simple function-style casting. Is this true? Why? | The main reason is that classic C casts make no distinction between what we call `static_cast<>()`, `reinterpret_cast<>()`, `const_cast<>()`, and `dynamic_cast<>()`. These four things are completely different.
A `static_cast<>()` is usually safe. There is a valid conversion in the language, or an appropriate constructor that makes it possible. The only time it's a bit risky is when you cast down to an inherited class; you must make sure that the object is actually the descendant that you claim it is, by means external to the language (like a flag in the object). A `dynamic_cast<>()` is safe as long as the result is checked (pointer) or a possible exception is taken into account (reference).
A `reinterpret_cast<>()` (or a `const_cast<>()`) on the other hand is always dangerous. You tell the compiler: "trust me: I know this doesn't look like a `foo` (this looks as if it isn't mutable), but it is".
The first problem is that it's almost impossible to tell which one will occur in a C-style cast without looking at large and disperse pieces of code and knowing all the rules.
Let's assume these:
```
class CDerivedClass : public CMyBase {...};
class CMyOtherStuff {...} ;
CMyBase *pSomething; // filled somewhere
```
Now, these two are compiled the same way:
```
CDerivedClass *pMyObject;
pMyObject = static_cast<CDerivedClass*>(pSomething); // Safe; as long as we checked
pMyObject = (CDerivedClass*)(pSomething); // Same as static_cast<>
// Safe; as long as we checked
// but harder to read
```
However, let's see this almost identical code:
```
CMyOtherStuff *pOther;
pOther = static_cast<CMyOtherStuff*>(pSomething); // Compiler error: Can't convert
pOther = (CMyOtherStuff*)(pSomething); // No compiler error.
// Same as reinterpret_cast<>
// and it's wrong!!!
```
As you can see, there is no easy way to distinguish between the two situations without knowing a lot about all the classes involved.
The second problem is that the C-style casts are too hard to locate. In complex expressions it can be very hard to see C-style casts. It is virtually impossible to write an automated tool that needs to locate C-style casts (for example a search tool) without a full blown C++ compiler front-end. On the other hand, it's easy to search for "static\_cast<" or "reinterpret\_cast<".
```
pOther = reinterpret_cast<CMyOtherStuff*>(pSomething);
// No compiler error.
// but the presence of a reinterpret_cast<> is
// like a Siren with Red Flashing Lights in your code.
// The mere typing of it should cause you to feel VERY uncomfortable.
```
That means that, not only are C-style casts more dangerous, but it's a lot harder to find them all to make sure that they are correct. |
103,516 | <p>Using c#, VS2005, and .NET 2.0. (XP 32 bit) This is a Winforms app that gets called by a VBA addin (.xla) via Interop libraries. This app has been around for a while and works fine when the assembly is compiled and executed anywhere other than my dev machine. On dev it crashes hard (in debugger and just running the object) with "Unhandled exception at 0x... in EXCEL.EXE: 0x...violation reading location 0x...</p>
<p>But here's the weird part:</p>
<p>The first method in my interface works fine. All the other methods crash as above. Here is an approximation of the code:</p>
<pre><code>[Guid("123Fooetc...")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IBar
{
[DispId(1)]
void ThisOneWorksFine(Excel.Workbook ActiveWorkBook);
[DispId(2)]
string Crash1(Excel.Workbook ActiveWorkBook);
[DispId(3)]
int Crash2(Excel.Workbook activeWorkBook, Excel.Range target, string someStr);
}
[Guid("345Fooetc..")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("MyNameSpace.MyClass")]
public class MyClass : IBar
{
public void ThisOneWorksFine(Excel.Workbook ActiveWorkBook)
{...}
string Crash1(Excel.Workbook ActiveWorkBook);
{...}
int Crash2(Excel.Workbook activeWorkBook, Excel.Range target, string someStr);
{...}
}
</code></pre>
<p>It seems like some kind of environmental thing. Registry chundered? Could be code bugs, but it works fine elsewhere.</p>
| [
{
"answer_id": 103538,
"author": "Steve Cooper",
"author_id": 6722,
"author_profile": "https://Stackoverflow.com/users/6722",
"pm_score": 0,
"selected": false,
"text": "<p>Is your dev machine Win64? I've had problems with win64 builds of apps that go away if you set the build platform to x86.</p>\n"
},
{
"answer_id": 103882,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 3,
"selected": true,
"text": "<p>I've had problems in this scenario with Office 2003 in the past. Some things that have helped:</p>\n\n<ul>\n<li><p>Installing Office 2003 Service Pack 2 stopped some crashes that happened when closing Excel.</p></li>\n<li><p>Installing Office 2003 Service Pack 3 fixes a bug with using XP styles in a VSTO2005 application (not your case here)</p></li>\n<li><p>Running the Excel VBA CodeCleaner <a href=\"http://www.appspro.com/Utilities/CodeCleaner.htm\" rel=\"nofollow noreferrer\">http://www.appspro.com/Utilities/CodeCleaner.htm</a> periodically helps prevent random crashes.</p></li>\n<li><p>Accessing Excel objects from multiple threads would be dodgy, so I hope you aren't doing that.</p></li>\n</ul>\n\n<p>If you have the possibility you could also try opening a case with Microsoft PSS. They are pretty good if you are able to reproduce the problem. And in most cases, this kind of thing is a bug, so you won't be charged for it :)</p>\n"
},
{
"answer_id": 114917,
"author": "Robert S.",
"author_id": 7565,
"author_profile": "https://Stackoverflow.com/users/7565",
"pm_score": 0,
"selected": false,
"text": "<p>Is your dev machine running a different version of Office than the other machines? I know that the PIAs differ. So if you're developing on Office 2003 and testing on Office 2007 (or vice versa), for example, you will run into problems.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12281/"
]
| Using c#, VS2005, and .NET 2.0. (XP 32 bit) This is a Winforms app that gets called by a VBA addin (.xla) via Interop libraries. This app has been around for a while and works fine when the assembly is compiled and executed anywhere other than my dev machine. On dev it crashes hard (in debugger and just running the object) with "Unhandled exception at 0x... in EXCEL.EXE: 0x...violation reading location 0x...
But here's the weird part:
The first method in my interface works fine. All the other methods crash as above. Here is an approximation of the code:
```
[Guid("123Fooetc...")]
[InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
public interface IBar
{
[DispId(1)]
void ThisOneWorksFine(Excel.Workbook ActiveWorkBook);
[DispId(2)]
string Crash1(Excel.Workbook ActiveWorkBook);
[DispId(3)]
int Crash2(Excel.Workbook activeWorkBook, Excel.Range target, string someStr);
}
[Guid("345Fooetc..")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("MyNameSpace.MyClass")]
public class MyClass : IBar
{
public void ThisOneWorksFine(Excel.Workbook ActiveWorkBook)
{...}
string Crash1(Excel.Workbook ActiveWorkBook);
{...}
int Crash2(Excel.Workbook activeWorkBook, Excel.Range target, string someStr);
{...}
}
```
It seems like some kind of environmental thing. Registry chundered? Could be code bugs, but it works fine elsewhere. | I've had problems in this scenario with Office 2003 in the past. Some things that have helped:
* Installing Office 2003 Service Pack 2 stopped some crashes that happened when closing Excel.
* Installing Office 2003 Service Pack 3 fixes a bug with using XP styles in a VSTO2005 application (not your case here)
* Running the Excel VBA CodeCleaner <http://www.appspro.com/Utilities/CodeCleaner.htm> periodically helps prevent random crashes.
* Accessing Excel objects from multiple threads would be dodgy, so I hope you aren't doing that.
If you have the possibility you could also try opening a case with Microsoft PSS. They are pretty good if you are able to reproduce the problem. And in most cases, this kind of thing is a bug, so you won't be charged for it :) |
103,532 | <p>If you need to open a SqlConnection before issuing queries, can you simply handle all non-Open ConnectionStates in the same way? For example:</p>
<pre><code> if (connection.State != ConnectionState.Open)
{
connection.Open();
}
</code></pre>
<p>I read somewhere that for ConnectionState.Broken the connection needs to be closed before its re-opened. Does anyone have experience with this? Thanks-</p>
| [
{
"answer_id": 103832,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 3,
"selected": false,
"text": "<p>This isn't directly answering your question, but the best practice is to open and close a connection for every access to the database. ADO.NET connection pooling ensures that this performs well. It's particularly important to do this in server apps (e.g. ASP.NET), but I would do it even in a WinForms app that accesses the database directly.</p>\n\n<p>Example:</p>\n\n<pre><code>using(SqlConnection connection = new SqlConnection(...))\n{\n connection.Open();\n // ... do your stuff here\n\n} // Connection is disposed and closed here, even if an exception is thrown\n</code></pre>\n\n<p>In this way you never need to check the connection state when opening a connection.</p>\n"
},
{
"answer_id": 103901,
"author": "ddc0660",
"author_id": 16027,
"author_profile": "https://Stackoverflow.com/users/16027",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.data.connectionstate.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.data.connectionstate.aspx</a></p>\n\n<p>Broken connection state does need to be closed and reopened before eligible for continued use.</p>\n\n<p>Edit: Unfortunately closing a closed connection will balk as well. You'll need to test the ConnectionState before acting on an unknown connection. Perhaps a short switch statement could do the trick.</p>\n"
},
{
"answer_id": 12537293,
"author": "Rudy Hinojosa",
"author_id": 1689760,
"author_profile": "https://Stackoverflow.com/users/1689760",
"pm_score": 2,
"selected": false,
"text": "<p>You can handle it the same way. I was getting numerous connection state == broken while using IE9. There is something fundamentally wrong with IE9 in this regard since no other browser had this issue of broken connection states after 5 or 6 updates to the database tables. So I use object context. So basically just close it and re-open it.</p>\n<p>I have this code before all my reads and updates in the business logic layer:</p>\n<pre><code>if (context.Connection.State == System.Data.ConnectionState.Broken)\n{\n context.Connection.Close();\n context.Connection.Open();\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/815/"
]
| If you need to open a SqlConnection before issuing queries, can you simply handle all non-Open ConnectionStates in the same way? For example:
```
if (connection.State != ConnectionState.Open)
{
connection.Open();
}
```
I read somewhere that for ConnectionState.Broken the connection needs to be closed before its re-opened. Does anyone have experience with this? Thanks- | <http://msdn.microsoft.com/en-us/library/system.data.connectionstate.aspx>
Broken connection state does need to be closed and reopened before eligible for continued use.
Edit: Unfortunately closing a closed connection will balk as well. You'll need to test the ConnectionState before acting on an unknown connection. Perhaps a short switch statement could do the trick. |
103,560 | <p>I have an ASP.net application that works fine in the development environment but in the production environment throws the following exception when clicking a link that performs a postback. Any ideas?</p>
<blockquote>
<p>Invalid postback or callback argument.
Event validation is enabled using
in configuration or <%@ Page
EnableEventValidation="true" %> in a
page. For security purposes, this
feature verifies that arguments to
postback or callback events originate
from the server control that
originally rendered them. If the data
is valid and expected, use the
ClientScriptManager.RegisterForEventValidation
method in order to register the
postback or callback data for
validation.</p>
</blockquote>
<p><strong>Edit:</strong> This seems to only be happening when viewed with IE6 but not with IE7, any ideas?</p>
| [
{
"answer_id": 103599,
"author": "azamsharp",
"author_id": 3797,
"author_profile": "https://Stackoverflow.com/users/3797",
"pm_score": 0,
"selected": false,
"text": "<p>It seems that the data/controls on the page are changed when the postback occurs. What happens if you turn off the event validation in the page directive. </p>\n\n<pre><code><%@ Page ... EnableEventValidation = \"false\" />\n</code></pre>\n"
},
{
"answer_id": 103762,
"author": "Nikki9696",
"author_id": 456669,
"author_profile": "https://Stackoverflow.com/users/456669",
"pm_score": 1,
"selected": false,
"text": "<p>This can happen if you're posting what appears to be possibly malicious things; such as a textbox that has html in it, but is not encoded prior to postback. If you are allowing html or script to be submitted, you need to encode it so that the characters, such as <, are passed as & lt;.</p>\n"
},
{
"answer_id": 278893,
"author": "dnord",
"author_id": 3248,
"author_profile": "https://Stackoverflow.com/users/3248",
"pm_score": 0,
"selected": false,
"text": "<p>I only ever get this when I have nested <code><form></code> tags in my pages. IE6 will look at the nested form tags and try to post the values in <em>those</em> forms as well as the main ASP.NET form, causing the error. Other browsers don't post the nested forms (since it's invalid HTML) and don't get the error.</p>\n\n<p>You can certainly solve this by doing an <code>EnableEventValidation = \"false\"</code>, but that can mean problems for your posted values and viewstate. It's better to weed out the nested <code><form></code> tags first.</p>\n\n<p>There are other spots where this can come up, like HTML-esque values in form fields, but I think the error messages for those were more specific. On a generic postback that throws this, I'd just check the rendered page for extra <code><form></code> tags.</p>\n"
},
{
"answer_id": 26012819,
"author": "user1089766",
"author_id": 1089766,
"author_profile": "https://Stackoverflow.com/users/1089766",
"pm_score": 2,
"selected": false,
"text": "<p>Problem description:\n This is one the common issues that a lot of ASP.NET beginners face, post, and ask about. Typically, they post the error message as below and seek for resolution without sharing much about what they were trying to do.</p>\n\n<p>[ArgumentException: Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation=\"true\" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]</p>\n\n<p>Though, error stack trace itself suggests a quick resolution by setting eventvalidation off, it is not a recommended solution as it opens up a security hole. It is always good to know why it happened and how to solve/handle that root problem.</p>\n\n<p>Assessment:\n Event validation is done to validate if the origin of the event is the related rendered control (and not some cross site script or so). Since control registers its events during rendering, events can be validated during postback or callback (via arguments of __doPostBack). This reduces the risk of unauthorized or malicious postback requests and callbacks.</p>\n\n<p>Refer: MSDN: Page.EnableEventValidation Property</p>\n\n<p>Based on above, possible scenarios that I have faced or heard that raises the issue in discussion are:\n Case #1: If we have angular brackets in the request data, it looks like some script tag is being passed to server.</p>\n\n<p>Possible Solution:\n HTML encode the angular brackets with help of JavaScript before submitting the form, i.e., replace “<” with “<” and “>” with “>”</p>\n\n<pre><code>function HTMLEncodeAngularBrackets(someString)\n{\nvar modifiedString = someString.replace(\"<\",\"&lt;\");\nmodifiedString = modifiedString.replace(\">\",\"&gt;\");\nreturn modifiedString;\n}\n</code></pre>\n\n<p>Case #2: If we write client script that changes a control in the client at run time, we might have a dangling event. An example could be having embedded controls where an inner control registers for postback but is hidden at runtime because of an operation done on outer control. This I read about on MSDN blog written by Carlo, when looking for same issue because of multiple form tags.</p>\n\n<p>Possible Solution:\n Manually register control for event validation within Render method of the page.</p>\n\n<pre><code>protected override void Render(HtmlTextWriter writer)\n{\nClientScript.RegisterForEventValidation(myButton.UniqueID.ToString());\nbase.Render(writer);\n}\n</code></pre>\n\n<p>As said, one of the other common scenario reported (which looks like falls in the this same category) is building a page where one form tag is embedded in another form tag that runs on server. Removing one of them corrects the flow and resolves the issue.</p>\n\n<p>Case #3: If we re-define/instantiate controls or commands at runtime on every postback, respective/related events might go for a toss. A simple example could be of re-binding a datagrid on every pageload (including postbacks). Since, on rebind all the controls in grid will have a new ID, during an event triggered by datagrid control, on postback the control ID’s are changed and thus the event might not connect to correct control raising the issue.</p>\n\n<p>Possible Solution:\n This can be simply resolved by making sure that controls are not re-created on every postback (rebind here). Using Page property IsPostback can easily handle it. If you want to create a control on every postback, then it is necessary to make sure that the ID’s are not changed.</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\nif(!Page.IsPostback)\n{\n// Create controls\n// Bind Grid\n}\n}\n</code></pre>\n\n<p>Conclusion:\n As said, an easy/direct solution can be adding enableEventValidation=”false” in the Page directive or Web.config file but is not recommended. Based on the implementation and cause, find the root cause and apply the resolution accordingly.</p>\n"
},
{
"answer_id": 43311149,
"author": "TroyQ",
"author_id": 6106844,
"author_profile": "https://Stackoverflow.com/users/6106844",
"pm_score": 0,
"selected": false,
"text": "<p>I had something similar happen where I had a ListBox that worked fine when I entered text manually, but when I entered data based off of a SQL query, the last item in the list would throw this exception. I searched all the Q&A and nothing matched my issue. </p>\n\n<p>In my case, the issue was that there was an unprintable character (\\r) in the SQL data. I am guessing that the server created a hash code based on the existence of the unprintable character, but it was removed from the string that actually showed up in the ListBox so the 2nd hash didn't match the 1st. Cleaning up the string and removing the unprintable characters before putting it into the ListBox fixed my issue.</p>\n\n<p>This is probably a super edge-case but I wanted to add this just to be complete (and hopefully help someone else not spend 2 days going crazy).</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3111/"
]
| I have an ASP.net application that works fine in the development environment but in the production environment throws the following exception when clicking a link that performs a postback. Any ideas?
>
> Invalid postback or callback argument.
> Event validation is enabled using
>
> in configuration or <%@ Page
> EnableEventValidation="true" %> in a
> page. For security purposes, this
> feature verifies that arguments to
> postback or callback events originate
> from the server control that
> originally rendered them. If the data
> is valid and expected, use the
> ClientScriptManager.RegisterForEventValidation
> method in order to register the
> postback or callback data for
> validation.
>
>
>
**Edit:** This seems to only be happening when viewed with IE6 but not with IE7, any ideas? | Problem description:
This is one the common issues that a lot of ASP.NET beginners face, post, and ask about. Typically, they post the error message as below and seek for resolution without sharing much about what they were trying to do.
[ArgumentException: Invalid postback or callback argument. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]
Though, error stack trace itself suggests a quick resolution by setting eventvalidation off, it is not a recommended solution as it opens up a security hole. It is always good to know why it happened and how to solve/handle that root problem.
Assessment:
Event validation is done to validate if the origin of the event is the related rendered control (and not some cross site script or so). Since control registers its events during rendering, events can be validated during postback or callback (via arguments of \_\_doPostBack). This reduces the risk of unauthorized or malicious postback requests and callbacks.
Refer: MSDN: Page.EnableEventValidation Property
Based on above, possible scenarios that I have faced or heard that raises the issue in discussion are:
Case #1: If we have angular brackets in the request data, it looks like some script tag is being passed to server.
Possible Solution:
HTML encode the angular brackets with help of JavaScript before submitting the form, i.e., replace “<” with “<” and “>” with “>”
```
function HTMLEncodeAngularBrackets(someString)
{
var modifiedString = someString.replace("<","<");
modifiedString = modifiedString.replace(">",">");
return modifiedString;
}
```
Case #2: If we write client script that changes a control in the client at run time, we might have a dangling event. An example could be having embedded controls where an inner control registers for postback but is hidden at runtime because of an operation done on outer control. This I read about on MSDN blog written by Carlo, when looking for same issue because of multiple form tags.
Possible Solution:
Manually register control for event validation within Render method of the page.
```
protected override void Render(HtmlTextWriter writer)
{
ClientScript.RegisterForEventValidation(myButton.UniqueID.ToString());
base.Render(writer);
}
```
As said, one of the other common scenario reported (which looks like falls in the this same category) is building a page where one form tag is embedded in another form tag that runs on server. Removing one of them corrects the flow and resolves the issue.
Case #3: If we re-define/instantiate controls or commands at runtime on every postback, respective/related events might go for a toss. A simple example could be of re-binding a datagrid on every pageload (including postbacks). Since, on rebind all the controls in grid will have a new ID, during an event triggered by datagrid control, on postback the control ID’s are changed and thus the event might not connect to correct control raising the issue.
Possible Solution:
This can be simply resolved by making sure that controls are not re-created on every postback (rebind here). Using Page property IsPostback can easily handle it. If you want to create a control on every postback, then it is necessary to make sure that the ID’s are not changed.
```
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostback)
{
// Create controls
// Bind Grid
}
}
```
Conclusion:
As said, an easy/direct solution can be adding enableEventValidation=”false” in the Page directive or Web.config file but is not recommended. Based on the implementation and cause, find the root cause and apply the resolution accordingly. |
103,561 | <p>I am taking on a maintenance team and would like to introduce tools like FxCop and StyleCop to help improve the code and introduce the developers to better programming techniques and standards. Since we are maintaining code and not making significant enhancements, we will probably only deal with a couple of methods/routines at a time when making changes. </p>
<p>Is it possible to target FxCop/StyleCop to specific areas of code within Visual Studio to avoid getting overwhelmed with all of the issues that would get raised when analyzing a whole class or project? If it is possible, how do you go about it?</p>
<p>Thanks,
Matt</p>
| [
{
"answer_id": 104311,
"author": "ripper234",
"author_id": 11236,
"author_profile": "https://Stackoverflow.com/users/11236",
"pm_score": -1,
"selected": false,
"text": "<p>I would guess that it can't (seems a too-specific need).</p>\n"
},
{
"answer_id": 168262,
"author": "alexandrul",
"author_id": 19756,
"author_profile": "https://Stackoverflow.com/users/19756",
"pm_score": 3,
"selected": true,
"text": "<p>I am using FxCopCmd.exe (FxCop 1.36) as an external tool with various command line parameters, including this one:</p>\n\n<pre><code>/types:<type list> [Short form: /t:<type list>]\nAnalyze only these types and members.\n</code></pre>\n"
},
{
"answer_id": 168304,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 1,
"selected": false,
"text": "<p>FxCop can target specific types using either the command line or the GUI. StyleCop does not provide such a mechanism.</p>\n\n<p>However, for both of them you can target specific rules instead types which may work better to reduce the amount of \"noise\" to more manageable chunks.</p>\n"
},
{
"answer_id": 196066,
"author": "Dominic Cronin",
"author_id": 9967,
"author_profile": "https://Stackoverflow.com/users/9967",
"pm_score": -1,
"selected": false,
"text": "<p>Creating new rules for FXCop is possible, but \"advanced\". Configuring FXCop to only use certain rules from those available is trivial. </p>\n"
},
{
"answer_id": 1043546,
"author": "Col",
"author_id": 12653,
"author_profile": "https://Stackoverflow.com/users/12653",
"pm_score": 1,
"selected": false,
"text": "<p>Try the approach in this article</p>\n\n<p><a href=\"http://blogs.msdn.com/sourceanalysis/archive/2008/11/11/introducing-stylecop-on-legacy-projects.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/sourceanalysis/archive/2008/11/11/introducing-stylecop-on-legacy-projects.aspx</a></p>\n\n<p>You can remove individual files from StyleCop's beady eye by adding properties to include or exclude each file in the .csproj</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3262/"
]
| I am taking on a maintenance team and would like to introduce tools like FxCop and StyleCop to help improve the code and introduce the developers to better programming techniques and standards. Since we are maintaining code and not making significant enhancements, we will probably only deal with a couple of methods/routines at a time when making changes.
Is it possible to target FxCop/StyleCop to specific areas of code within Visual Studio to avoid getting overwhelmed with all of the issues that would get raised when analyzing a whole class or project? If it is possible, how do you go about it?
Thanks,
Matt | I am using FxCopCmd.exe (FxCop 1.36) as an external tool with various command line parameters, including this one:
```
/types:<type list> [Short form: /t:<type list>]
Analyze only these types and members.
``` |
103,575 | <p>I am trying to validate the WPF form against an object. The validation fires when I type something in the textbox lose focus come back to the textbox and then erase whatever I have written. But if I just load the WPF application and tab off the textbox without writing and erasing anything from the textbox, then it is not fired. </p>
<p>Here is the Customer.cs class: </p>
<pre><code>public class Customer : IDataErrorInfo
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string columnName]
{
get
{
string result = null;
if (columnName.Equals("FirstName"))
{
if (String.IsNullOrEmpty(FirstName))
{
result = "FirstName cannot be null or empty";
}
}
else if (columnName.Equals("LastName"))
{
if (String.IsNullOrEmpty(LastName))
{
result = "LastName cannot be null or empty";
}
}
return result;
}
}
}
</code></pre>
<p>And here is the WPF code: </p>
<pre><code><TextBlock Grid.Row="1" Margin="10" Grid.Column="0">LastName</TextBlock>
<TextBox Style="{StaticResource textBoxStyle}" Name="txtLastName" Margin="10"
VerticalAlignment="Top" Grid.Row="1" Grid.Column="1">
<Binding Source="{StaticResource CustomerKey}" Path="LastName"
ValidatesOnExceptions="True" ValidatesOnDataErrors="True"
UpdateSourceTrigger="LostFocus"/>
</TextBox>
</code></pre>
| [
{
"answer_id": 103641,
"author": "cranley",
"author_id": 10308,
"author_profile": "https://Stackoverflow.com/users/10308",
"pm_score": 4,
"selected": false,
"text": "<p>Unfortunately this is by design. WPF validation only fires if the value in the control has changed. </p>\n\n<p>Unbelievable, but true. So far, WPF validation is the big proverbial pain - it's terrible. </p>\n\n<p>One of the things you can do, however, is get the binding expression from the control's property and manually invoke the validations. It sucks, but it works. </p>\n"
},
{
"answer_id": 717211,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I've gone through the same problem and found an ultra simple way to resolve this : in the Loaded event of your window, simply put txtLastName.Text = String.Empty. That's it!! Since the property of your object has changed (been set to an empty string), the validation's firing !</p>\n"
},
{
"answer_id": 914289,
"author": "w4g3n3r",
"author_id": 36745,
"author_profile": "https://Stackoverflow.com/users/36745",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.controls.validationrule.validatesontargetupdated.aspx\" rel=\"noreferrer\">ValidatesOnTargetUpdated</a> property of ValidationRule. It will validate when the data is first loaded. This is good if you're trying to catch empty or null fields. </p>\n\n<p>You'd update your binding element like this:</p>\n\n<pre><code><Binding \n Source=\"{StaticResource CustomerKey}\" \n Path=\"LastName\" \n ValidatesOnExceptions=\"True\" \n ValidatesOnDataErrors=\"True\" \n UpdateSourceTrigger=\"LostFocus\">\n <Binding.ValidationRules>\n <DataErrorValidationRule\n ValidatesOnTargetUpdated=\"True\" />\n </Binding.ValidationRules>\n</Binding>\n</code></pre>\n"
},
{
"answer_id": 1347399,
"author": "Bermo",
"author_id": 5110,
"author_profile": "https://Stackoverflow.com/users/5110",
"pm_score": 5,
"selected": true,
"text": "<p>If you're not adverse to putting a bit of logic in your code behind, you can handle the actual <em>LostFocus</em> event with something like this:</p>\n\n<p><strong>.xaml</strong></p>\n\n<pre><code><TextBox LostFocus=\"TextBox_LostFocus\" ....\n</code></pre>\n\n<hr>\n\n<p><strong>.xaml.cs</strong></p>\n\n<pre><code>private void TextBox_LostFocus(object sender, RoutedEventArgs e)\n{\n ((Control)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource();\n}\n</code></pre>\n"
},
{
"answer_id": 5672473,
"author": "AbstractDissonance",
"author_id": 576287,
"author_profile": "https://Stackoverflow.com/users/576287",
"pm_score": 0,
"selected": false,
"text": "<p>The follow code loops over all the controls and validates them. Not necessarily the preferred way but seems to work. It only does TextBlocks and TextBoxes but you can easily change it.</p>\n\n<pre><code>public static class PreValidation\n{\n\n public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject\n {\n if (depObj != null)\n {\n for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)\n {\n DependencyObject child = VisualTreeHelper.GetChild(depObj, i);\n if (child != null && child is T)\n {\n yield return (T)child;\n }\n\n foreach (T childOfChild in FindVisualChildren<T>(child))\n {\n yield return childOfChild;\n }\n }\n }\n }\n\n\n public static void Validate(DependencyObject depObj)\n {\n foreach(var c in FindVisualChildren<FrameworkElement>(depObj))\n {\n DependencyProperty p = null;\n\n if (c is TextBlock)\n p = TextBlock.TextProperty;\n else if (c is TextBox)\n p = TextBox.TextProperty;\n\n if (p != null && c.GetBindingExpression(p) != null) c.GetBindingExpression(p).UpdateSource();\n }\n\n }\n}\n</code></pre>\n\n<p>Just call Validate on your window or control and it should pre-validate them for you.</p>\n"
},
{
"answer_id": 8528810,
"author": "theDoke",
"author_id": 1089031,
"author_profile": "https://Stackoverflow.com/users/1089031",
"pm_score": 1,
"selected": false,
"text": "<p>I found out the best way for me to handle this was on the LostFocus event of the text box I do something like this</p>\n\n<pre><code> private void dbaseNameTextBox_LostFocus(object sender, RoutedEventArgs e)\n {\n if (string.IsNullOrWhiteSpace(dbaseNameTextBox.Text))\n {\n dbaseNameTextBox.Text = string.Empty;\n }\n }\n</code></pre>\n\n<p>Then it sees an error</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103575",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3797/"
]
| I am trying to validate the WPF form against an object. The validation fires when I type something in the textbox lose focus come back to the textbox and then erase whatever I have written. But if I just load the WPF application and tab off the textbox without writing and erasing anything from the textbox, then it is not fired.
Here is the Customer.cs class:
```
public class Customer : IDataErrorInfo
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string columnName]
{
get
{
string result = null;
if (columnName.Equals("FirstName"))
{
if (String.IsNullOrEmpty(FirstName))
{
result = "FirstName cannot be null or empty";
}
}
else if (columnName.Equals("LastName"))
{
if (String.IsNullOrEmpty(LastName))
{
result = "LastName cannot be null or empty";
}
}
return result;
}
}
}
```
And here is the WPF code:
```
<TextBlock Grid.Row="1" Margin="10" Grid.Column="0">LastName</TextBlock>
<TextBox Style="{StaticResource textBoxStyle}" Name="txtLastName" Margin="10"
VerticalAlignment="Top" Grid.Row="1" Grid.Column="1">
<Binding Source="{StaticResource CustomerKey}" Path="LastName"
ValidatesOnExceptions="True" ValidatesOnDataErrors="True"
UpdateSourceTrigger="LostFocus"/>
</TextBox>
``` | If you're not adverse to putting a bit of logic in your code behind, you can handle the actual *LostFocus* event with something like this:
**.xaml**
```
<TextBox LostFocus="TextBox_LostFocus" ....
```
---
**.xaml.cs**
```
private void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
((Control)sender).GetBindingExpression(TextBox.TextProperty).UpdateSource();
}
``` |
103,576 | <p>I'm trying a very basic XPath on <a href="http://pastebin.com/f14a20a30" rel="noreferrer">this xml</a> (same as below), and it doesn't find anything.
I'm trying both .NET and <a href="http://www.xmlme.com/XpathTool.aspx" rel="noreferrer">this website</a>, and XPaths such as <code>//PropertyGroup</code>, <code>/PropertyGroup</code> and <code>//MSBuildCommunityTasksPath</code> are simply not working for me (they compiled but return zero results).</p>
<p>Source XML:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- $Id: FxCop.proj 114 2006-03-14 06:32:46Z pwelter34 $ -->
<PropertyGroup>
<MSBuildCommunityTasksPath>$(MSBuildProjectDirectory)\MSBuild.Community.Tasks\bin\Debug</MSBuildCommunityTasksPath>
</PropertyGroup>
<Import
Project="$(MSBuildProjectDirectory)\MSBuild.Community.Tasks\MSBuild.Community.Tasks.Targets" />
<Target Name="DoFxCop">
<FxCop TargetAssemblies="$(MSBuildCommunityTasksPath)\MSBuild.Community.Tasks.dll"
RuleLibraries="@(FxCopRuleAssemblies)"
AnalysisReportFileName="Test.html"
DependencyDirectories="$(MSBuildCommunityTasksPath)"
FailOnError="True"
ApplyOutXsl="True"
OutputXslFileName="C:\Program Files\Microsoft FxCop 1.32\Xml\FxCopReport.xsl" />
</Target>
</Project>
</code></pre>
| [
{
"answer_id": 103626,
"author": "Pseudo Masochist",
"author_id": 8529,
"author_profile": "https://Stackoverflow.com/users/8529",
"pm_score": 1,
"selected": false,
"text": "<p>Your issue is with the namespace (xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\"). You're receiving zero nodes because you aren't qualifying it with the namespace. If you remove the xmlns attribute, your \"//PropertyGroup\" XPath will work. How you query with namespace usually involves aliasing a default xmlns to an identifier (since one is not specified on the attribute), and selecting like \"//myXMLNStoken:PropertyGroup\".</p>\n"
},
{
"answer_id": 103905,
"author": "Jesse Millikan",
"author_id": 7526,
"author_profile": "https://Stackoverflow.com/users/7526",
"pm_score": 2,
"selected": false,
"text": "<p>The tags in the document end up in the \"default\" namespace created by the xmlns attribute with no prefix. Unfortunately, XPath alone can not query elements in the default namespace. I'm actually not sure of the semantic details, but you have to explicitly attach a prefix to that namespace using whatever tool is hosting XPath.</p>\n\n<p>There may be a shorter way to do this in .NET, but the only way I've seen is via a NameSpaceManager. After you explicitly add a namespace, you can query using the namespace manager as if all the tags in the namespaced element have that prefix (I chose 'msbuild'):</p>\n\n<pre><code>using System;\nusing System.Xml;\n\npublic class XPathNamespace {\n public static void Main(string[] args) {\n XmlDocument xmlDocument = new XmlDocument();\n xmlDocument.LoadXml(\n @\"<?xml version=\"\"1.0\"\" encoding=\"\"utf-8\"\"?>\n<Project xmlns=\"\"http://schemas.microsoft.com/developer/msbuild/2003\"\">\n <!-- $Id: FxCop.proj 114 2006-03-14 06:32:46Z pwelter34 $ -->\n\n <PropertyGroup>\n <MSBuildCommunityTasksPath>$(MSBuildProjectDirectory)\\MSBuild.Community.Tasks\\bin\\Debug</MSBuildCommunityTasksPath>\n </PropertyGroup>\n\n <Import Project=\"\"$(MSBuildProjectDirectory)\\MSBuild.Community.Tasks\\MSBuild.Community.Tasks.Targets\"\"/>\n\n <Target Name=\"\"DoFxCop\"\">\n\n <FxCop \n TargetAssemblies=\"\"$(MSBuildCommunityTasksPath)\\MSBuild.Community.Tasks.dll\"\"\n RuleLibraries=\"\"@(FxCopRuleAssemblies)\"\" \n AnalysisReportFileName=\"\"Test.html\"\"\n DependencyDirectories=\"\"$(MSBuildCommunityTasksPath)\"\"\n FailOnError=\"\"True\"\"\n ApplyOutXsl=\"\"True\"\"\n OutputXslFileName=\"\"C:\\Program Files\\Microsoft FxCop 1.32\\Xml\\FxCopReport.xsl\"\"\n />\n </Target>\n\n</Project>\");\n\n XmlNamespaceManager namespaceManager = new\n XmlNamespaceManager(xmlDocument.NameTable);\n namespaceManager.AddNamespace(\"msbuild\", \"http://schemas.microsoft.com/developer/msbuild/2003\");\n foreach (XmlNode n in xmlDocument.SelectNodes(\"//msbuild:MSBuildCommunityTasksPath\", namespaceManager)) {\n Console.WriteLine(n.InnerText);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 104404,
"author": "b w",
"author_id": 4126,
"author_profile": "https://Stackoverflow.com/users/4126",
"pm_score": 5,
"selected": true,
"text": "<p>You can add namespaces in your code and all that, but you can effectively wildcard the namespace. Try the following XPath idiom.</p>\n\n<pre><code>//*[local-name()='PropertyGroup']\n//*[local-name()='MSBuildCommunityTasksPath']\n</code></pre>\n\n<p>name() usually works as well, as in:</p>\n\n<pre><code>//*[name()='PropertyGroup']\n//*[name()='MSBuildCommunityTasksPath']\n</code></pre>\n\n<p>EDIT: <strong>Namespaces are great</strong> and i'm not suggesting they're not important, but wildcarding them comes in handy when cobbling together prototype code, one-off desktop tools, experimenting with XSLT, and so forth. Balance your need for convenience against acceptable risk for the task at hand. FYI, if need be, you can also strip or reassign namespaces.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11236/"
]
| I'm trying a very basic XPath on [this xml](http://pastebin.com/f14a20a30) (same as below), and it doesn't find anything.
I'm trying both .NET and [this website](http://www.xmlme.com/XpathTool.aspx), and XPaths such as `//PropertyGroup`, `/PropertyGroup` and `//MSBuildCommunityTasksPath` are simply not working for me (they compiled but return zero results).
Source XML:
```
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<!-- $Id: FxCop.proj 114 2006-03-14 06:32:46Z pwelter34 $ -->
<PropertyGroup>
<MSBuildCommunityTasksPath>$(MSBuildProjectDirectory)\MSBuild.Community.Tasks\bin\Debug</MSBuildCommunityTasksPath>
</PropertyGroup>
<Import
Project="$(MSBuildProjectDirectory)\MSBuild.Community.Tasks\MSBuild.Community.Tasks.Targets" />
<Target Name="DoFxCop">
<FxCop TargetAssemblies="$(MSBuildCommunityTasksPath)\MSBuild.Community.Tasks.dll"
RuleLibraries="@(FxCopRuleAssemblies)"
AnalysisReportFileName="Test.html"
DependencyDirectories="$(MSBuildCommunityTasksPath)"
FailOnError="True"
ApplyOutXsl="True"
OutputXslFileName="C:\Program Files\Microsoft FxCop 1.32\Xml\FxCopReport.xsl" />
</Target>
</Project>
``` | You can add namespaces in your code and all that, but you can effectively wildcard the namespace. Try the following XPath idiom.
```
//*[local-name()='PropertyGroup']
//*[local-name()='MSBuildCommunityTasksPath']
```
name() usually works as well, as in:
```
//*[name()='PropertyGroup']
//*[name()='MSBuildCommunityTasksPath']
```
EDIT: **Namespaces are great** and i'm not suggesting they're not important, but wildcarding them comes in handy when cobbling together prototype code, one-off desktop tools, experimenting with XSLT, and so forth. Balance your need for convenience against acceptable risk for the task at hand. FYI, if need be, you can also strip or reassign namespaces. |
103,583 | <p>This is written in PHP, but it's really language agnostic.</p>
<pre><code>try
{
try
{
$issue = new DM_Issue($core->db->escape_string($_GET['issue']));
}
catch(DM_Exception $e)
{
throw new Error_Page($tpl, ERR_NOT_FOUND, $e->getMessage());
}
}
catch(Error_Page $e)
{
die($e);
}
</code></pre>
<p>Is nested try, catch blocks a good practice to follow? It seems a little bulky just for an error page - however my Issue Datamanager throws an Exception if an error occurs and I consider that to be a good way of error detecting.</p>
<p>The Error_Page exception is simply an error page compiler.</p>
<p>I might just be pedantic, but do you think this is a good way to report errors and if so can you suggest a better way to write this?</p>
<p>Thanks</p>
| [
{
"answer_id": 103625,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 2,
"selected": false,
"text": "<p>I think you'd be better off not nesting. If you expect multiple exception types, have multiple catches.</p>\n\n<pre><code>try{\n Something();\n}\ncatch( SpecificException se )\n{blah();}\ncatch( AnotherException ae )\n{blah();}\n</code></pre>\n"
},
{
"answer_id": 103631,
"author": "sgibbons",
"author_id": 2327,
"author_profile": "https://Stackoverflow.com/users/2327",
"pm_score": 0,
"selected": false,
"text": "<p>Depending on your needs this could be fine, but I am generally pretty hesitant to catch an exception, wrap the message in a new exception, and rethrow it because you loose the stack trace (and potentially other) information from the original exception in the wrapping exception. If you're <strong>sure</strong> that you don't need that information when examining the wrapping exception then it's probably alright.</p>\n"
},
{
"answer_id": 103637,
"author": "Jeremy Privett",
"author_id": 560,
"author_profile": "https://Stackoverflow.com/users/560",
"pm_score": 4,
"selected": true,
"text": "<p>You're using Exceptions for page logic, and I personally think that's not a good thing. Exceptions should be used to signal when bad or unexpected things happen, not to control the output of an error page. If you want to generate an error page based on Exceptions, consider using <a href=\"http://www.php.net/set_exception_handler\" rel=\"nofollow noreferrer\">set_exception_handler</a>. Any uncaught exceptions are run through whatever callback method you specify. Keep in mind that this doesn't stop the \"fatalness\" of an Exception. After an exception is passed through your callback, execution will stop like normal after any uncaught exception.</p>\n"
},
{
"answer_id": 103645,
"author": "Anheledir",
"author_id": 5703,
"author_profile": "https://Stackoverflow.com/users/5703",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure about PHP but in e.g. C# you can have more then one catch-Block so there is no need for nested try/catch-combinations.</p>\n\n<p>Generally I believe that errorhandling with try/catch/finally is always common-sense, also for showing \"only\" a error-page. It's a clean way to handle errors and avoid strange behavior on crashing.</p>\n"
},
{
"answer_id": 103692,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 2,
"selected": false,
"text": "<p>The ideal is for exceptions to be caught at the level which can handle them. Not before (waste of time), and not after (you lose context).</p>\n\n<p>So, if $tpl and ERR_NOT_FOUND are information which is only \"known\" close to the new DM_Issue call, for example because there are other places where you create a DM_Issue and would want ERR_SOMETHING_ELSE, or because the value of $tpl varies, then you're catching the first exception at the right place.</p>\n\n<p>How to get from that place to dying is another question. An alternative would be to die right there. But if you do that then there's no opportunity for intervening code to do anything (such as clearing something up in some way or modifying the error page) after the error but before exit. It's also good to have explicit control flow. So I think you're good.</p>\n\n<p>I'm assuming that your example isn't a complete application - if it is then it's probably needlessly verbose, and you could just die in the DM_Exception catch clause. But for a real app I approve of the principle of not just dying in the middle of nowhere.</p>\n"
},
{
"answer_id": 103859,
"author": "Aeon",
"author_id": 13289,
"author_profile": "https://Stackoverflow.com/users/13289",
"pm_score": 0,
"selected": false,
"text": "<p>I wouldn't throw an exception on issue not found - it's a valid state of an application, and you don't need a stack trace just to display a 404. </p>\n\n<p>What you need to catch is unexpected failures, like sql errors - that's when exception handling comes in handy. I would change your code to look more like this:</p>\n\n<pre><code>try {\n $issue = DM_Issue::fetch($core->db->escape_string($_GET['issue']));\n}\ncatch (SQLException $e) {\n log_error('SQL Error: DM_Issue::fetch()', $e->get_message());\n}\ncatch (Exception $e) {\n log_error('Exception: DM_Issue::fetch()', $e->get_message());\n}\n\nif(!$issue) {\n display_error_page($tpl, ERR_NOT_FOUND);\n}\nelse\n{\n // ... do stuff with $issue object.\n}\n</code></pre>\n"
},
{
"answer_id": 106530,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Exceptions should be used only if there is a potentially site-breaking event - such as a database query not executing properly or something is misconfigured. A good example is that a cache or log directory is not writable by the Apache process.</p>\n\n<p>The idea here is that exceptions are for you, the developer, to halt code that can break the entire site so you can fix them before deployment. They are also sanity checks to make sure that if the environment changes (i.e. somebody alters the permissions of the cache folder or change the database scheme) the site is halted before it can damage anything.</p>\n\n<p>So, no; nested catch handlers are not a good idea. In my pages, my index.php file wraps its code in a try...cache block - and if something bad happens it checks to see if its in production or not; and either emails me and display a generic error page, or shows the error right on the screen.</p>\n\n<p>Remember: PHP is not C#. C# is (with the exception (hehe, no pun intended :p) of ASP.net) for applications that contain state - whereas PHP is a stateless scripting language.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103583",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2025/"
]
| This is written in PHP, but it's really language agnostic.
```
try
{
try
{
$issue = new DM_Issue($core->db->escape_string($_GET['issue']));
}
catch(DM_Exception $e)
{
throw new Error_Page($tpl, ERR_NOT_FOUND, $e->getMessage());
}
}
catch(Error_Page $e)
{
die($e);
}
```
Is nested try, catch blocks a good practice to follow? It seems a little bulky just for an error page - however my Issue Datamanager throws an Exception if an error occurs and I consider that to be a good way of error detecting.
The Error\_Page exception is simply an error page compiler.
I might just be pedantic, but do you think this is a good way to report errors and if so can you suggest a better way to write this?
Thanks | You're using Exceptions for page logic, and I personally think that's not a good thing. Exceptions should be used to signal when bad or unexpected things happen, not to control the output of an error page. If you want to generate an error page based on Exceptions, consider using [set\_exception\_handler](http://www.php.net/set_exception_handler). Any uncaught exceptions are run through whatever callback method you specify. Keep in mind that this doesn't stop the "fatalness" of an Exception. After an exception is passed through your callback, execution will stop like normal after any uncaught exception. |
103,593 | <p>I have:</p>
<pre><code><?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
</code></pre>
<p>but it overwrites the beginning of the file. How do I make it insert?</p>
| [
{
"answer_id": 103609,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 6,
"selected": true,
"text": "<p>I'm not entirely sure of your question - do you want to write data and not have it over-write the beginning of an existing file, or write new data to the start of an existing file, keeping the existing content after it?</p>\n\n<p><strong>To insert text without over-writing the beginning of the file</strong>, you'll have to open it for appending (<a href=\"http://ie.php.net/fopen\" rel=\"noreferrer\"><code>a+</code> rather than <code>r+</code></a>)</p>\n\n<pre><code>$file=fopen(date(\"Y-m-d\").\".txt\",\"a+\") or exit(\"Unable to open file!\");\n\nif ($_POST[\"lastname\"] <> \"\")\n{\n fwrite($file,$_POST[\"lastname\"].\"\\n\");\n}\n\nfclose($file);\n</code></pre>\n\n<p><strong>If you're trying to write to the start of the file</strong>, you'll have to read in the file contents (see <a href=\"http://www.google.ie/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fwww.php.net%2Ffile_get_contents&ei=39jTSKOWEoyk1wbQ-vC6Dg&usg=AFQjCNHwFDwvy4v0p90sNfmfSB_jg7gR7Q&sig2=KyOdq6fGxuj8701pDDdXqA\" rel=\"noreferrer\"><code>file_get_contents</code></a>) first, then write your new string followed by file contents to the output file.</p>\n\n<pre><code>$old_content = file_get_contents($file);\nfwrite($file, $new_content.\"\\n\".$old_content);\n</code></pre>\n\n<p>The above approach will work with small files, but you may run into memory limits trying to read a large file in using <code>file_get_conents</code>. In this case, consider using <a href=\"http://ie.php.net/rewind\" rel=\"noreferrer\"><code>rewind($file)</code></a>, which sets the file position indicator for handle to the beginning of the file stream. \nNote when using <code>rewind()</code>, not to open the file with the <code>a</code> (or <code>a+</code>) options, as:</p>\n\n<blockquote>\n <p>If you have opened the file in append (\"a\" or \"a+\") mode, any data you write to the file will always be appended, regardless of the file position. </p>\n</blockquote>\n"
},
{
"answer_id": 103617,
"author": "SeanDowney",
"author_id": 5261,
"author_profile": "https://Stackoverflow.com/users/5261",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to put your text at the beginning of the file, you'd have to read the file contents first like:</p>\n\n<pre><code><?php\n\n$file=fopen(date(\"Y-m-d\").\".txt\",\"r+\") or exit(\"Unable to open file!\");\n\nif ($_POST[\"lastname\"] <> \"\")\n{ \n $existingText = file_get_contents($file);\n fwrite($file, $existingText . $_POST[\"lastname\"].\"\\n\");\n}\n\nfclose($file);\n\n?>\n</code></pre>\n"
},
{
"answer_id": 103675,
"author": "Eduardo Campañó",
"author_id": 12091,
"author_profile": "https://Stackoverflow.com/users/12091",
"pm_score": 0,
"selected": false,
"text": "<p>You get the same opening the file for appending</p>\n\n<pre><code><?php\n$file=fopen(date(\"Y-m-d\").\".txt\",\"a+\") or exit(\"Unable to open file!\");\nif ($_POST[\"lastname\"] <> \"\")\n{\n fwrite($file,$_POST[\"lastname\"].\"\\n\");\n}\nfclose($file);\n?>\n</code></pre>\n"
},
{
"answer_id": 26093658,
"author": "oskarth",
"author_id": 1062912,
"author_profile": "https://Stackoverflow.com/users/1062912",
"pm_score": 1,
"selected": false,
"text": "<p>A working example for inserting in the middle of a file stream without overwriting, and without having to load the whole thing into a variable/memory:</p>\n\n<pre><code>function finsert($handle, $string, $bufferSize = 16384) {\n $insertionPoint = ftell($handle);\n\n // Create a temp file to stream into\n $tempPath = tempnam(sys_get_temp_dir(), \"file-chainer\");\n $lastPartHandle = fopen($tempPath, \"w+\");\n\n // Read in everything from the insertion point and forward\n while (!feof($handle)) {\n fwrite($lastPartHandle, fread($handle, $bufferSize), $bufferSize);\n }\n\n // Rewind to the insertion point\n fseek($handle, $insertionPoint);\n\n // Rewind the temporary stream\n rewind($lastPartHandle);\n\n // Write back everything starting with the string to insert\n fwrite($handle, $string);\n while (!feof($lastPartHandle)) {\n fwrite($handle, fread($lastPartHandle, $bufferSize), $bufferSize);\n }\n\n // Close the last part handle and delete it\n fclose($lastPartHandle);\n unlink($tempPath);\n\n // Re-set pointer\n fseek($handle, $insertionPoint + strlen($string));\n}\n\n$handle = fopen(\"file.txt\", \"w+\");\nfwrite($handle, \"foobar\");\nrewind($handle);\nfinsert($handle, \"baz\");\n\n// File stream is now: bazfoobar\n</code></pre>\n\n<p><a href=\"https://github.com/prewk/file-chainer/\" rel=\"nofollow\">Composer lib for it can be found here</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103593",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have:
```
<?php
$file=fopen(date("Y-m-d").".txt","r+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
?>
```
but it overwrites the beginning of the file. How do I make it insert? | I'm not entirely sure of your question - do you want to write data and not have it over-write the beginning of an existing file, or write new data to the start of an existing file, keeping the existing content after it?
**To insert text without over-writing the beginning of the file**, you'll have to open it for appending ([`a+` rather than `r+`](http://ie.php.net/fopen))
```
$file=fopen(date("Y-m-d").".txt","a+") or exit("Unable to open file!");
if ($_POST["lastname"] <> "")
{
fwrite($file,$_POST["lastname"]."\n");
}
fclose($file);
```
**If you're trying to write to the start of the file**, you'll have to read in the file contents (see [`file_get_contents`](http://www.google.ie/url?sa=t&source=web&ct=res&cd=1&url=http%3A%2F%2Fwww.php.net%2Ffile_get_contents&ei=39jTSKOWEoyk1wbQ-vC6Dg&usg=AFQjCNHwFDwvy4v0p90sNfmfSB_jg7gR7Q&sig2=KyOdq6fGxuj8701pDDdXqA)) first, then write your new string followed by file contents to the output file.
```
$old_content = file_get_contents($file);
fwrite($file, $new_content."\n".$old_content);
```
The above approach will work with small files, but you may run into memory limits trying to read a large file in using `file_get_conents`. In this case, consider using [`rewind($file)`](http://ie.php.net/rewind), which sets the file position indicator for handle to the beginning of the file stream.
Note when using `rewind()`, not to open the file with the `a` (or `a+`) options, as:
>
> If you have opened the file in append ("a" or "a+") mode, any data you write to the file will always be appended, regardless of the file position.
>
>
> |
103,598 | <p>Why was the <code>arguments.callee.caller</code> property deprecated in JavaScript?</p>
<p>It was added and then deprecated in JavaScript, but it was omitted altogether by ECMAScript. Some browser (Mozilla, IE) have always supported it and don't have any plans on the map to remove support. Others (Safari, Opera) have adopted support for it, but support on older browsers is unreliable.</p>
<p>Is there a good reason to put this valuable functionality in limbo?</p>
<p>(Or alternately, is there a better way to grab a handle on the calling function?)</p>
| [
{
"answer_id": 103961,
"author": "Zach",
"author_id": 9128,
"author_profile": "https://Stackoverflow.com/users/9128",
"pm_score": 5,
"selected": false,
"text": "<p>It is better to use <strong>named functions</strong> than arguments.callee:</p>\n\n<pre><code> function foo () {\n ... foo() ...\n }\n</code></pre>\n\n<p>is better than</p>\n\n<pre><code> function () {\n ... arguments.callee() ...\n }\n</code></pre>\n\n<p>The named function will have access to its caller through the <strong><a href=\"http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/caller\" rel=\"noreferrer\">caller</a></strong> property:</p>\n\n<pre><code> function foo () {\n alert(foo.caller);\n }\n</code></pre>\n\n<p>which is better than</p>\n\n<pre><code> function foo () {\n alert(arguments.callee.caller);\n }\n</code></pre>\n\n<p>The deprecation is due to current ECMAScript <a href=\"http://wiki.ecmascript.org/doku.php?id=es3.1:design_principles\" rel=\"noreferrer\">design principles</a>.</p>\n"
},
{
"answer_id": 235760,
"author": "olliej",
"author_id": 784,
"author_profile": "https://Stackoverflow.com/users/784",
"pm_score": 9,
"selected": true,
"text": "<p>Early versions of JavaScript did not allow named function expressions, and because of that we could not make a recursive function expression:</p>\n\n<pre><code> // This snippet will work:\n function factorial(n) {\n return (!(n>1))? 1 : factorial(n-1)*n;\n }\n [1,2,3,4,5].map(factorial);\n\n\n // But this snippet will not:\n [1,2,3,4,5].map(function(n) {\n return (!(n>1))? 1 : /* what goes here? */ (n-1)*n;\n });\n</code></pre>\n\n<p>To get around this, <code>arguments.callee</code> was added so we could do:</p>\n\n<pre><code> [1,2,3,4,5].map(function(n) {\n return (!(n>1))? 1 : arguments.callee(n-1)*n;\n });\n</code></pre>\n\n<p>However this was actually a really bad solution as this (in conjunction with other arguments, callee, and caller issues) make inlining and tail recursion impossible in the general case (you can achieve it in select cases through tracing etc, but even the best code is sub optimal due to checks that would not otherwise be necessary). The other major issue is that the recursive call will get a different <code>this</code> value, for example:</p>\n\n<pre><code>var global = this;\nvar sillyFunction = function (recursed) {\n if (!recursed)\n return arguments.callee(true);\n if (this !== global)\n alert(\"This is: \" + this);\n else\n alert(\"This is the global\");\n}\nsillyFunction();\n</code></pre>\n\n<p>Anyhow, EcmaScript 3 resolved these issues by allowing named function expressions, e.g.:</p>\n\n<pre><code> [1,2,3,4,5].map(function factorial(n) {\n return (!(n>1))? 1 : factorial(n-1)*n;\n });\n</code></pre>\n\n<p>This has numerous benefits:</p>\n\n<ul>\n<li><p>The function can be called like any other from inside your code.</p></li>\n<li><p>It does not pollute the namespace.</p></li>\n<li><p>The value of <code>this</code> does not change.</p></li>\n<li><p>It's more performant (accessing the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments\" rel=\"noreferrer\">arguments object</a> is expensive).</p></li>\n</ul>\n\n<h3>Whoops,</h3>\n\n<p>Just realised that in addition to everything else the question was about <code>arguments.callee.caller</code>, or more specifically <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller\" rel=\"noreferrer\"><code>Function.caller</code></a>.</p>\n\n<p>At any point in time you can find the deepest caller of any function on the stack, and as I said above, looking at the call stack has one single major effect: It makes a large number of optimizations impossible, or much much more difficult.</p>\n\n<p>Eg. if we can't guarantee that a function <code>f</code> will not call an unknown function, then it is not possible to inline <code>f</code>. Basically it means that any call site that may have been trivially inlinable accumulates a large number of guards, take:</p>\n\n<pre><code> function f(a, b, c, d, e) { return a ? b * c : d * e; }\n</code></pre>\n\n<p>If the js interpreter cannot guarantee that all the provided arguments are numbers at the point that the call is made, it needs to either insert checks for all the arguments before the inlined code, or it cannot inline the function.</p>\n\n<p>Now in this particular case a smart interpreter should be able to rearrange the checks to be more optimal and not check any values that would not be used. However in many cases that's just not possible and therefore it becomes impossible to inline.</p>\n"
},
{
"answer_id": 1335595,
"author": "James Wheare",
"author_id": 115076,
"author_profile": "https://Stackoverflow.com/users/115076",
"pm_score": 7,
"selected": false,
"text": "<p><code>arguments.call<b>ee</b>.call<b>er</b></code> is <b>not</b> deprecated, though it does make use of the <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Function/caller\" rel=\"noreferrer\"><code>Function.call<b>er</b></code></a> property. (<a href=\"https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Functions_and_function_scope/arguments/callee\" rel=\"noreferrer\"><code>arguments.call<b>ee</b></code></a> will just give you a reference to the current function)</p>\n\n<ul>\n<li><code>Function.call<b>er</b></code>, though non-standard according to ECMA3, is implemented across <b>all current major browsers</b>.</li>\n<li><a href=\"https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Functions_and_function_scope/arguments/caller\" rel=\"noreferrer\"><code>arguments.call<b>er</b></code></a> <b>is</b> deprecated in favour of <code>Function.call<b>er</b></code>, and isn't implemented in some current major browsers (e.g. Firefox 3).</li>\n</ul>\n\n<p>So the situation is less than ideal, but if you want to access the calling function in Javascript across all major browsers, you can use the <code>Function.call<b>er</b></code> property, either accessed directly on a named function reference, or from within an anonymous function via the <code>arguments.call<b>ee</b></code> property.</p>\n"
},
{
"answer_id": 28084391,
"author": "FERcsI",
"author_id": 2531161,
"author_profile": "https://Stackoverflow.com/users/2531161",
"pm_score": 0,
"selected": false,
"text": "<p>Just an extension. The value of \"this\" changes during recursion. In the following (modified) example, factorial gets the {foo:true} object.</p>\n\n<pre><code>[1,2,3,4,5].map(function factorial(n) {\n console.log(this);\n return (!(n>1))? 1 : factorial(n-1)*n;\n}, {foo:true} );\n</code></pre>\n\n<p>factorial called first time gets the object, but this is not true for recursive calls.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103598",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15992/"
]
| Why was the `arguments.callee.caller` property deprecated in JavaScript?
It was added and then deprecated in JavaScript, but it was omitted altogether by ECMAScript. Some browser (Mozilla, IE) have always supported it and don't have any plans on the map to remove support. Others (Safari, Opera) have adopted support for it, but support on older browsers is unreliable.
Is there a good reason to put this valuable functionality in limbo?
(Or alternately, is there a better way to grab a handle on the calling function?) | Early versions of JavaScript did not allow named function expressions, and because of that we could not make a recursive function expression:
```
// This snippet will work:
function factorial(n) {
return (!(n>1))? 1 : factorial(n-1)*n;
}
[1,2,3,4,5].map(factorial);
// But this snippet will not:
[1,2,3,4,5].map(function(n) {
return (!(n>1))? 1 : /* what goes here? */ (n-1)*n;
});
```
To get around this, `arguments.callee` was added so we could do:
```
[1,2,3,4,5].map(function(n) {
return (!(n>1))? 1 : arguments.callee(n-1)*n;
});
```
However this was actually a really bad solution as this (in conjunction with other arguments, callee, and caller issues) make inlining and tail recursion impossible in the general case (you can achieve it in select cases through tracing etc, but even the best code is sub optimal due to checks that would not otherwise be necessary). The other major issue is that the recursive call will get a different `this` value, for example:
```
var global = this;
var sillyFunction = function (recursed) {
if (!recursed)
return arguments.callee(true);
if (this !== global)
alert("This is: " + this);
else
alert("This is the global");
}
sillyFunction();
```
Anyhow, EcmaScript 3 resolved these issues by allowing named function expressions, e.g.:
```
[1,2,3,4,5].map(function factorial(n) {
return (!(n>1))? 1 : factorial(n-1)*n;
});
```
This has numerous benefits:
* The function can be called like any other from inside your code.
* It does not pollute the namespace.
* The value of `this` does not change.
* It's more performant (accessing the [arguments object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments) is expensive).
### Whoops,
Just realised that in addition to everything else the question was about `arguments.callee.caller`, or more specifically [`Function.caller`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/caller).
At any point in time you can find the deepest caller of any function on the stack, and as I said above, looking at the call stack has one single major effect: It makes a large number of optimizations impossible, or much much more difficult.
Eg. if we can't guarantee that a function `f` will not call an unknown function, then it is not possible to inline `f`. Basically it means that any call site that may have been trivially inlinable accumulates a large number of guards, take:
```
function f(a, b, c, d, e) { return a ? b * c : d * e; }
```
If the js interpreter cannot guarantee that all the provided arguments are numbers at the point that the call is made, it needs to either insert checks for all the arguments before the inlined code, or it cannot inline the function.
Now in this particular case a smart interpreter should be able to rearrange the checks to be more optimal and not check any values that would not be used. However in many cases that's just not possible and therefore it becomes impossible to inline. |
103,616 | <p>I have an Apex class (controller) originally developed under Developer Edition and need to upload it to production which is Enterprise Edition.</p>
<p>The upload fails with following message</p>
<pre><code>classes/RenewalController.cls(RenewalController):An error occurred on your page.
package.xml(RenewalController):An object 'RenewalController' of type ApexClass
was named in manifest but was not found in zipped directory
</code></pre>
<p>The same message when I try to use Force.com IDE: <em>Save error: An error occurred on your page.</em></p>
<p>This class is working under Developer Edition but not with Enterprise.</p>
<p>What can be the problem?</p>
| [
{
"answer_id": 177263,
"author": "Dima Malenko",
"author_id": 2586,
"author_profile": "https://Stackoverflow.com/users/2586",
"pm_score": 2,
"selected": true,
"text": "<p>Controller class may reference other custom SalesForce objects like pages. If controller is uploaded before these objects <em>Save error: An error occurred on your page.</em> is reported.</p>\n\n<p>Correct order of uploading of custom components should be used.</p>\n"
},
{
"answer_id": 195252,
"author": "Ryan Guest",
"author_id": 1811,
"author_profile": "https://Stackoverflow.com/users/1811",
"pm_score": 2,
"selected": false,
"text": "<p>Dmytro, you are correct. Visualforce pages, apex classes, and components must be uploaded in the correct order. Generally the pattern I use is upload the controllers, components, and then visualforce pages.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103616",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2586/"
]
| I have an Apex class (controller) originally developed under Developer Edition and need to upload it to production which is Enterprise Edition.
The upload fails with following message
```
classes/RenewalController.cls(RenewalController):An error occurred on your page.
package.xml(RenewalController):An object 'RenewalController' of type ApexClass
was named in manifest but was not found in zipped directory
```
The same message when I try to use Force.com IDE: *Save error: An error occurred on your page.*
This class is working under Developer Edition but not with Enterprise.
What can be the problem? | Controller class may reference other custom SalesForce objects like pages. If controller is uploaded before these objects *Save error: An error occurred on your page.* is reported.
Correct order of uploading of custom components should be used. |
103,622 | <p>We have a java program that requires a large amount of heap space - we start it with (among other command line arguments) the argument -Xmx1500m, which specifies a maximum heap space of 1500 MB. When starting this program on a Windows XP box that has been freshly rebooted, it will start and run without issues. But if the program has run several times, the computer has been up for a while, etc., when it tries to start I get this error:</p>
<pre>
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.
</pre>
<p>I suspect that Windows itself is suffering from memory fragmentation, but I don't know how to confirm this suspicion. At the time that this happens, Task manager and sysinternals procexp report 2000MB free memory. I have looked at <a href="https://stackoverflow.com/questions/60871/how-to-solve-memory-fragmentation">this question related to internal fragmentation</a></p>
<p>So the first question is, How do I confirm my suspicion?
The second question is, if my suspicions are correct, does anyone know of any tools to solve this problem? I've looked around quite a bit, but I haven't found anything that helps, other than periodic reboots of the machine. </p>
<p>ps - changing operating systems is also not currently a viable option. </p>
| [
{
"answer_id": 103830,
"author": "kulakli",
"author_id": 11131,
"author_profile": "https://Stackoverflow.com/users/11131",
"pm_score": 0,
"selected": false,
"text": "<p>Using Minimem (<a href=\"http://minimem.kerkia.net/\" rel=\"nofollow noreferrer\">http://minimem.kerkia.net/</a>) for that application might fix your problem. However, I'm not sure this is the answer you are looking for. I hope it helps.</p>\n"
},
{
"answer_id": 103835,
"author": "Okami",
"author_id": 11450,
"author_profile": "https://Stackoverflow.com/users/11450",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe you should consider to start the program and reserving the memory and not\nend the VM after each run. Look for different GC options and release your objects.</p>\n"
},
{
"answer_id": 103912,
"author": "Torlack",
"author_id": 5243,
"author_profile": "https://Stackoverflow.com/users/5243",
"pm_score": 2,
"selected": false,
"text": "<p>Unless you are running out of page file space, this issue isn't that the computer is running out of memory. The whole point of virtual memory is to allow the processes to use more virtual memory than is physically available.</p>\n\n<p>Not knowing how the JVM handles the heap, it is a bit hard to say exactly what the problem is, but one of the common issues is that there isn't enough contiguous free address space available in your process to allow the heap to be extended. Why this would be a problem after the machine has been running a while is a bit confusing.</p>\n\n<p>I've been working on a similar problem at work. I have found that running the program using WinDBG and using the \"!address\" and \"!address -summary\" commands have been invaluable in tracking down why a processes' virtual address space has become fragmented. You can also try running the program after reboot and using the \"!address\" command to take a picture of the address space and then do the same when the program no longer runs. This might clue you in on the problem. Maybe something simple as an extra DLL getting loading might cause the problem.</p>\n"
},
{
"answer_id": 103960,
"author": "John Gardner",
"author_id": 13687,
"author_profile": "https://Stackoverflow.com/users/13687",
"pm_score": 3,
"selected": true,
"text": "<p>Agree with Torlack, a lot of this is because other DLLs are getting loaded and go into certain spots, breaking up the amount of memory you can get for the VM in one big chunk.</p>\n\n<p>You can do some work on WinXP if you have more than 3G of memory to get some of the windows stuff moved around, look up PAE here:\n<a href=\"http://www.microsoft.com/whdc/system/platform/server/PAE/PAEdrv.mspx\" rel=\"nofollow noreferrer\">http://www.microsoft.com/whdc/system/platform/server/PAE/PAEdrv.mspx</a></p>\n\n<p>Your best bet, if you really need more than 1.2G of memory for your java app, is to look at 64 bit windows or linux or OSX. If you're using any kind of native libraries with your app you'll have to recompile them for 64 bit, but its going to be a lot easier than trying to rebase dlls and stuff to maximize the memory you can get on 32 bit windows.</p>\n\n<p>Another option would be to split your program up into multiple VMs and have them communicate with eachother via RMI or messaging or something. That way each VM can have some subset of the memory you need. Without knowing what your app does, i'm not sure that this will help in any way, though...</p>\n"
},
{
"answer_id": 882927,
"author": "SteveDonie",
"author_id": 11051,
"author_profile": "https://Stackoverflow.com/users/11051",
"pm_score": 2,
"selected": false,
"text": "<p>I suspect that the problem is Windows memory fragmentation. There is another question here on StackOverflow called <a href=\"https://stackoverflow.com/questions/171205/java-maximum-memory-on-windows-xp\">Java Maximum Memory on Windows XP</a> that mentions using Process Explorer to look at where DLLs are mapped into memory, and then to address the problem by rebasing the DLLs so that load into memory in a more compact way.</p>\n"
},
{
"answer_id": 7724231,
"author": "jey burrows",
"author_id": 72460,
"author_profile": "https://Stackoverflow.com/users/72460",
"pm_score": 0,
"selected": false,
"text": "<p>Use vmmap from Microsoft's SysInternals tools to view the fragmentation of the virtual address space, and identify what's breaking up the space</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11051/"
]
| We have a java program that requires a large amount of heap space - we start it with (among other command line arguments) the argument -Xmx1500m, which specifies a maximum heap space of 1500 MB. When starting this program on a Windows XP box that has been freshly rebooted, it will start and run without issues. But if the program has run several times, the computer has been up for a while, etc., when it tries to start I get this error:
```
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.
```
I suspect that Windows itself is suffering from memory fragmentation, but I don't know how to confirm this suspicion. At the time that this happens, Task manager and sysinternals procexp report 2000MB free memory. I have looked at [this question related to internal fragmentation](https://stackoverflow.com/questions/60871/how-to-solve-memory-fragmentation)
So the first question is, How do I confirm my suspicion?
The second question is, if my suspicions are correct, does anyone know of any tools to solve this problem? I've looked around quite a bit, but I haven't found anything that helps, other than periodic reboots of the machine.
ps - changing operating systems is also not currently a viable option. | Agree with Torlack, a lot of this is because other DLLs are getting loaded and go into certain spots, breaking up the amount of memory you can get for the VM in one big chunk.
You can do some work on WinXP if you have more than 3G of memory to get some of the windows stuff moved around, look up PAE here:
<http://www.microsoft.com/whdc/system/platform/server/PAE/PAEdrv.mspx>
Your best bet, if you really need more than 1.2G of memory for your java app, is to look at 64 bit windows or linux or OSX. If you're using any kind of native libraries with your app you'll have to recompile them for 64 bit, but its going to be a lot easier than trying to rebase dlls and stuff to maximize the memory you can get on 32 bit windows.
Another option would be to split your program up into multiple VMs and have them communicate with eachother via RMI or messaging or something. That way each VM can have some subset of the memory you need. Without knowing what your app does, i'm not sure that this will help in any way, though... |
103,630 | <p>Is it possible to use an <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="noreferrer">ASP.NET</a> web.sitemap with a jQuery <a href="http://users.tpg.com.au/j_birch/plugins/superfish/" rel="noreferrer">Superfish</a> menu? </p>
<p>If not, are there any standards based browser agnostic plugins available that work with the web.sitemap file?</p>
| [
{
"answer_id": 103789,
"author": "Smallinov",
"author_id": 8897,
"author_profile": "https://Stackoverflow.com/users/8897",
"pm_score": 0,
"selected": false,
"text": "<p>The SiteMapDataSource control should be able to bind to any hierarchical data bound control. I'm not familiar with superfish but I know there are plenty of jQueryish controls out there to do this.</p>\n"
},
{
"answer_id": 171093,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 2,
"selected": false,
"text": "<p>It looks like you need to generate a UL for Superfish. You should be able to do this with ASP.Net from your site map. I think the site map control will do something like this. If not, it should be pretty trivial to call the site map directly from C# and generate the DOM programmatically. You could build a user control to do this, or do it in the master page.</p>\n\n<p>Check out <a href=\"http://msdn.microsoft.com/en-us/library/ms178424.aspx\" rel=\"nofollow noreferrer\">this MSDN article</a> on how to programmatically enumerate the nodes in your site map.</p>\n"
},
{
"answer_id": 171117,
"author": "410",
"author_id": 24522,
"author_profile": "https://Stackoverflow.com/users/24522",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, it is totally possible.</p>\n\n<p>I have used it with the ASP:Menu control and jQuery 1.2.6 with the Superfish plugin. Note, you will need the <a href=\"http://www.asp.net/CSSAdapters/Menu.aspx\" rel=\"nofollow noreferrer\">ASP.NET 2.0 CSS Friendly Control Adapters</a>. </p>\n\n<p>ASP.NET generates the ASP:Menu control as a table layout. The CSS Friendly Control Adapter will make ASP.NET generate the ASP:Menu control as a UL/LI layout inside a div.</p>\n\n<p>This will allow easy integration of the jQuery and Superfish plugin because the Superfish plugin relies on a UL/LI layout.</p>\n"
},
{
"answer_id": 647656,
"author": "Conceptdev",
"author_id": 25673,
"author_profile": "https://Stackoverflow.com/users/25673",
"pm_score": 6,
"selected": true,
"text": "<p>I found this question while looking for the same answer... everyone <em>says</em> it's possible but no-one gives the actual solution! I seem to have it working now so thought I'd post my findings...</p>\n\n<p>Things I needed:</p>\n\n<ul>\n<li><p><a href=\"http://users.tpg.com.au/j_birch/plugins/superfish/#download\" rel=\"noreferrer\">Superfish</a> which also includes a version of <a href=\"http://jquery.com/\" rel=\"noreferrer\">jQuery</a></p></li>\n<li><p><a href=\"http://cssfriendly.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=2159\" rel=\"noreferrer\">CSS Friendly Control Adaptors</a> download DLL and .browsers file (into /bin and /App_Browsers folders respectively)</p></li>\n<li><p><a href=\"http://msdn.microsoft.com/en-us/library/yy2ykkab.aspx\" rel=\"noreferrer\">ASP.NET SiteMap</a> (a .sitemap XML file and <code>siteMap</code> provider entry in web.config)</p></li>\n</ul>\n\n<p>My finished <code>Masterpage.master</code> has the following <code>head</code> tag:</p>\n\n<pre><code><head runat=\"server\">\n <script type=\"text/javascript\" src=\"/script/jquery-1.3.2.min.js\"></script>\n <script type=\"text/javascript\" src=\"/script/superfish.js\"></script>\n <link href=\"~/css/superfish.css\" type=\"text/css\" rel=\"stylesheet\" media=\"screen\" runat=\"server\" />\n <script type=\"text/javascript\">\n\n $(document).ready(function() {\n $('ul.AspNet-Menu').superfish();\n }); \n\n</script>\n</head>\n</code></pre>\n\n<p>Which is basically all the stuff needed for the jQuery Superfish menu to work. Inside the page (where the menu goes) looks like this (based on <a href=\"http://www.devx.com/asp/Article/31889\" rel=\"noreferrer\">these instructions</a>):</p>\n\n<pre><code><asp:SiteMapDataSource ID=\"SiteMapDataSource\" runat=\"server\"\n ShowStartingNode=\"false\" />\n<asp:Menu ID=\"Menu1\" runat=\"server\" \n DataSourceID=\"SiteMapDataSource\"\n Orientation=\"Horizontal\" CssClass=\"sf-menu\">\n</asp:Menu>\n</code></pre>\n\n<p>Based on the documentation, this seems like it SHOULD work - but it doesn't. The reason is that the <code>CssClass=\"sf-menu\"</code> gets overwritten when the Menu is rendered and the <code><ul></code> tag gets a <code>class=\"AspNet-Menu\"</code>. I thought the line <code>$('ul.AspNet-Menu').superfish();</code> would help, but it didn't. </p>\n\n<p><strong>ONE MORE THING</strong></p>\n\n<p>Although it is a hack (and please someone point me to the correct solution) I was able to get it working by opening the <code>superfish.css</code> file and <em>search and replacing</em> <strong>sf-menu</strong> with <strong>AspNet-Menu</strong>... and voila! the menu appeared. I thought there would be some configuration setting in the <code>asp:Menu</code> control where I could set the <code><ul></code> class but didn't find any hints via google.</p>\n"
},
{
"answer_id": 1432092,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Remember to add css classes for NonLink elements. Superfish css elements don't acccont for them. And if you're like me and have root menu's that are not links, then it renders horribly. Just add AspNet-Menu-NonLink elements to the superfish.css file and it should render fine.</p>\n"
},
{
"answer_id": 5720215,
"author": "Mr W",
"author_id": 77694,
"author_profile": "https://Stackoverflow.com/users/77694",
"pm_score": 0,
"selected": false,
"text": "<p>I created a neat little sample project you can use at <a href=\"http://simplesitemenu.codeplex.com/\" rel=\"nofollow\">http://simplesitemenu.codeplex.com/</a></p>\n\n<p>It is a composite control which generates a nested UL/LI listing from your sitemap.</p>\n\n<p>Enjoy!</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3742/"
]
| Is it possible to use an [ASP.NET](http://en.wikipedia.org/wiki/ASP.NET) web.sitemap with a jQuery [Superfish](http://users.tpg.com.au/j_birch/plugins/superfish/) menu?
If not, are there any standards based browser agnostic plugins available that work with the web.sitemap file? | I found this question while looking for the same answer... everyone *says* it's possible but no-one gives the actual solution! I seem to have it working now so thought I'd post my findings...
Things I needed:
* [Superfish](http://users.tpg.com.au/j_birch/plugins/superfish/#download) which also includes a version of [jQuery](http://jquery.com/)
* [CSS Friendly Control Adaptors](http://cssfriendly.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=2159) download DLL and .browsers file (into /bin and /App\_Browsers folders respectively)
* [ASP.NET SiteMap](http://msdn.microsoft.com/en-us/library/yy2ykkab.aspx) (a .sitemap XML file and `siteMap` provider entry in web.config)
My finished `Masterpage.master` has the following `head` tag:
```
<head runat="server">
<script type="text/javascript" src="/script/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="/script/superfish.js"></script>
<link href="~/css/superfish.css" type="text/css" rel="stylesheet" media="screen" runat="server" />
<script type="text/javascript">
$(document).ready(function() {
$('ul.AspNet-Menu').superfish();
});
</script>
</head>
```
Which is basically all the stuff needed for the jQuery Superfish menu to work. Inside the page (where the menu goes) looks like this (based on [these instructions](http://www.devx.com/asp/Article/31889)):
```
<asp:SiteMapDataSource ID="SiteMapDataSource" runat="server"
ShowStartingNode="false" />
<asp:Menu ID="Menu1" runat="server"
DataSourceID="SiteMapDataSource"
Orientation="Horizontal" CssClass="sf-menu">
</asp:Menu>
```
Based on the documentation, this seems like it SHOULD work - but it doesn't. The reason is that the `CssClass="sf-menu"` gets overwritten when the Menu is rendered and the `<ul>` tag gets a `class="AspNet-Menu"`. I thought the line `$('ul.AspNet-Menu').superfish();` would help, but it didn't.
**ONE MORE THING**
Although it is a hack (and please someone point me to the correct solution) I was able to get it working by opening the `superfish.css` file and *search and replacing* **sf-menu** with **AspNet-Menu**... and voila! the menu appeared. I thought there would be some configuration setting in the `asp:Menu` control where I could set the `<ul>` class but didn't find any hints via google. |
103,633 | <p><a href="http://en.wikibooks.org/wiki/Combinatorics/Subsets_of_a_set-The_Binomial_Coefficient" rel="nofollow noreferrer">Pascal's rule</a> on counting the subset's of a set works great, when the set contains unique entities.</p>
<p>Is there a modification to this rule for when the set contains duplicate items?</p>
<p>For instance, when I try to find the count of the combinations of the letters A,B,C,D, it's easy to see that it's 1 + 4 + 6 + 4 + 1 (from Pascal's Triangle) = 16, or 15 if I remove the "use none of the letters" entry.</p>
<p>Now, what if the set of letters is A,B,B,B,C,C,D? Computing by hand, I can determine that the sum of subsets is: 1 + 4 + 8 + 11 + 11 + 8 + 4 + 1 = 48, but this doesn't conform to the Triangle I know.</p>
<p>Question: How do you modify Pascal's Triangle to take into account duplicate entities in the set?</p>
| [
{
"answer_id": 103651,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 2,
"selected": false,
"text": "<p>A set only contains unique items. If there are duplicates, then it is no longer a set.</p>\n"
},
{
"answer_id": 103702,
"author": "Paul Reiners",
"author_id": 7648,
"author_profile": "https://Stackoverflow.com/users/7648",
"pm_score": 0,
"selected": false,
"text": "<p>Even though mathematical sets do contain unique items, you can run into the problem of duplicate items in 'sets' in the real world of programming. See <a href=\"http://groups.google.com/group/comp.lang.lisp/browse_thread/thread/49b04522abaf7f7b/7948ffb8a3acf0f5?lnk=gst&q=reiners+set#7948ffb8a3acf0f5\" rel=\"nofollow noreferrer\">this thread</a> on Lisp unions for an example.</p>\n"
},
{
"answer_id": 103724,
"author": "Pedro",
"author_id": 5488,
"author_profile": "https://Stackoverflow.com/users/5488",
"pm_score": 2,
"selected": false,
"text": "<p>You don't need to modify Pascal's Triangle at all. Study C(k,n) and you'll find out -- you basically need to divide the original results to account for the permutation of equivalent letters.</p>\n\n<p>E.g., A B1 B2 C1 D1 == A B2 B1 C1 D1, therefore you need to divide C(5,5) by C(2,2).</p>\n"
},
{
"answer_id": 103767,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 1,
"selected": false,
"text": "<p>Without duplicates (in a set as earlier posters have noted), each element is either in or out of the subset. So you have 2^n subsets. With duplicates, (in a \"multi-set\") you have to take into account the number the number of times each element is in the \"sub-multi-set\". If it m_1,m_2...m_n represent the number of times each element repeats, then the number of sub-bags is (1+m_1) * (1+m_2) * ... (1+m_n).</p>\n"
},
{
"answer_id": 104046,
"author": "Thomas Andrews",
"author_id": 7061,
"author_profile": "https://Stackoverflow.com/users/7061",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, if you don't want to consider sets, consider the idea of 'factors.' How many factors does:</p>\n\n<pre><code>p1^a1.p2^a2....pn^an\n</code></pre>\n\n<p>have if p1's are distinct primes. If the ai's are all 1, then the number is 2^n. In general, the answer is (a1+1)(a2+1)...(an+1) as David Nehme notes.</p>\n\n<p>Oh, and note that your answer by hand was wrong, it should be 48, or 47 if you don't want to count the empty set.</p>\n"
},
{
"answer_id": 104091,
"author": "user11318",
"author_id": 11318,
"author_profile": "https://Stackoverflow.com/users/11318",
"pm_score": 3,
"selected": true,
"text": "<p>It looks like you want to know how many sub-multi-sets have, say, 3 elements. The math for this gets very tricky, very quickly. The idea is that you want to add together all of the combinations of ways to get there. So you have C(3,4) = 4 ways of doing it with no duplicated elements. B can be repeated twice in C(1,3) = 3 ways. B can be repeated 3 times in 1 way. And C can be repeated twice in C(1,3) = 3 ways. For 11 total. (Your 10 you got by hand was wrong. Sorry.)</p>\n\n<p>In general trying to do that logic is too hard. The simpler way to keep track of it is to write out a polynomial whose coefficients have the terms you want which you multiply out. For Pascal's triangle this is easy, the polynomial is (1+x)^n. (You can use repeated squaring to calculate this more efficiently.) In your case if an element is repeated twice you would have a (1+x+x^2) factor. 3 times would be (1+x+x^2+x^3). So your specific problem would be solved as follows:</p>\n\n<pre><code>(1 + x) (1 + x + x^2 + x^3) (1 + x + x^2) (1 + x)\n = (1 + 2x + 2x^2 + 2x^3 + x^4)(1 + 2x + 2x^2 + x^3)\n = 1 + 2x + 2x^2 + x^3 +\n 2x + 4x^2 + 4x^3 + 2x^4 +\n 2x^2 + 4x^3 + 4x^4 + 2x^5 +\n 2x^3 + 4x^4 + 4x^5 + 2x^6 +\n x^4 + 2x^5 + 2x^6 + x^7\n = 1 + 4x + 8x^2 + 11x^3 + 11x^4 + 8x^5 + 4x^6 + x^7\n</code></pre>\n\n<p>If you want to produce those numbers in code, I would use the polynomial trick to organize your thinking and code. (You'd be working with arrays of coefficients.)</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13824/"
]
| [Pascal's rule](http://en.wikibooks.org/wiki/Combinatorics/Subsets_of_a_set-The_Binomial_Coefficient) on counting the subset's of a set works great, when the set contains unique entities.
Is there a modification to this rule for when the set contains duplicate items?
For instance, when I try to find the count of the combinations of the letters A,B,C,D, it's easy to see that it's 1 + 4 + 6 + 4 + 1 (from Pascal's Triangle) = 16, or 15 if I remove the "use none of the letters" entry.
Now, what if the set of letters is A,B,B,B,C,C,D? Computing by hand, I can determine that the sum of subsets is: 1 + 4 + 8 + 11 + 11 + 8 + 4 + 1 = 48, but this doesn't conform to the Triangle I know.
Question: How do you modify Pascal's Triangle to take into account duplicate entities in the set? | It looks like you want to know how many sub-multi-sets have, say, 3 elements. The math for this gets very tricky, very quickly. The idea is that you want to add together all of the combinations of ways to get there. So you have C(3,4) = 4 ways of doing it with no duplicated elements. B can be repeated twice in C(1,3) = 3 ways. B can be repeated 3 times in 1 way. And C can be repeated twice in C(1,3) = 3 ways. For 11 total. (Your 10 you got by hand was wrong. Sorry.)
In general trying to do that logic is too hard. The simpler way to keep track of it is to write out a polynomial whose coefficients have the terms you want which you multiply out. For Pascal's triangle this is easy, the polynomial is (1+x)^n. (You can use repeated squaring to calculate this more efficiently.) In your case if an element is repeated twice you would have a (1+x+x^2) factor. 3 times would be (1+x+x^2+x^3). So your specific problem would be solved as follows:
```
(1 + x) (1 + x + x^2 + x^3) (1 + x + x^2) (1 + x)
= (1 + 2x + 2x^2 + 2x^3 + x^4)(1 + 2x + 2x^2 + x^3)
= 1 + 2x + 2x^2 + x^3 +
2x + 4x^2 + 4x^3 + 2x^4 +
2x^2 + 4x^3 + 4x^4 + 2x^5 +
2x^3 + 4x^4 + 4x^5 + 2x^6 +
x^4 + 2x^5 + 2x^6 + x^7
= 1 + 4x + 8x^2 + 11x^3 + 11x^4 + 8x^5 + 4x^6 + x^7
```
If you want to produce those numbers in code, I would use the polynomial trick to organize your thinking and code. (You'd be working with arrays of coefficients.) |
103,654 | <p>In several modern programming languages (including C++, Java, and C#), the language allows <a href="http://en.wikipedia.org/wiki/Integer_overflow" rel="noreferrer">integer overflow</a> to occur at runtime without raising any kind of error condition.</p>
<p>For example, consider this (contrived) C# method, which does not account for the possibility of overflow/underflow. (For brevity, the method also doesn't handle the case where the specified list is a null reference.)</p>
<pre class="lang-c# prettyprint-override"><code>//Returns the sum of the values in the specified list.
private static int sumList(List<int> list)
{
int sum = 0;
foreach (int listItem in list)
{
sum += listItem;
}
return sum;
}
</code></pre>
<p>If this method is called as follows:</p>
<pre class="lang-c# prettyprint-override"><code>List<int> list = new List<int>();
list.Add(2000000000);
list.Add(2000000000);
int sum = sumList(list);
</code></pre>
<p>An overflow will occur in the <code>sumList()</code> method (because the <code>int</code> type in C# is a 32-bit signed integer, and the sum of the values in the list exceeds the value of the maximum 32-bit signed integer). The sum variable will have a value of -294967296 (not a value of 4000000000); this most likely is not what the (hypothetical) developer of the sumList method intended.</p>
<p>Obviously, there are various techniques that can be used by developers to avoid the possibility of integer overflow, such as using a type like Java's <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html" rel="noreferrer"><code>BigInteger</code></a>, or the <a href="http://msdn.microsoft.com/en-us/library/74b4xzyw.aspx" rel="noreferrer"><code>checked</code></a> keyword and <a href="http://msdn.microsoft.com/en-us/library/h25wtyxf.aspx" rel="noreferrer"><code>/checked</code></a> compiler switch in C#.</p>
<p>However, the question that I'm interested in is why these languages were designed to by default allow integer overflows to happen in the first place, instead of, for example, raising an exception when an operation is performed at runtime that would result in an overflow. It seems like such behavior would help avoid bugs in cases where a developer neglects to account for the possibility of overflow when writing code that performs an arithmetic operation that could result in overflow. (These languages could have included something like an "unchecked" keyword that could designate a block where integer overflow is permitted to occur without an exception being raised, in those cases where that behavior is explicitly intended by the developer; C# actually <a href="http://msdn.microsoft.com/en-us/library/a569z7k8.aspx" rel="noreferrer">does have this</a>.)</p>
<p>Does the answer simply boil down to performance -- the language designers didn't want their respective languages to default to having "slow" arithmetic integer operations where the runtime would need to do extra work to check whether an overflow occurred, on every applicable arithmetic operation -- and this performance consideration outweighed the value of avoiding "silent" failures in the case that an inadvertent overflow occurs?</p>
<p>Are there other reasons for this language design decision as well, other than performance considerations?</p>
| [
{
"answer_id": 103670,
"author": "David Hill",
"author_id": 1181217,
"author_profile": "https://Stackoverflow.com/users/1181217",
"pm_score": 5,
"selected": false,
"text": "<p>I think performance is a pretty good reason. If you consider every instruction in a typical program that increments an integer, and if instead of the simple op to add 1, it had to check every time if adding 1 would overflow the type, then the cost in extra cycles would be pretty severe.</p>\n"
},
{
"answer_id": 103673,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 3,
"selected": false,
"text": "<p>It is likely 99% performance. On x86 would have to check the overflow flag on every operation which would be a huge performance hit.</p>\n\n<p>The other 1% would cover those cases where people are doing fancy bit manipulations or being 'imprecise' in mixing signed and unsigned operations and want the overflow semantics.</p>\n"
},
{
"answer_id": 103680,
"author": "Dima",
"author_id": 13313,
"author_profile": "https://Stackoverflow.com/users/13313",
"pm_score": 3,
"selected": false,
"text": "<p>Because checking for overflow takes time. Each primitive mathematical operation, which normally translates into a single assembly instruction would have to include a check for overflow, resulting in multiple assembly instructions, potentially resulting in a program that is several times slower.</p>\n"
},
{
"answer_id": 103695,
"author": "devinmoore",
"author_id": 15950,
"author_profile": "https://Stackoverflow.com/users/15950",
"pm_score": -1,
"selected": false,
"text": "<p>My understanding of why errors would not be raised by default at runtime boils down to the legacy of desiring to create programming languages with ACID-like behavior. Specifically, the tenet that anything that you code it to do (or don't code), it will do (or not do). If you didn't code some error handler, then the machine will \"assume\" by virtue of no error handler, that you really want to do the ridiculous, crash-prone thing you're telling it to do.</p>\n\n<p>(ACID reference: <a href=\"http://en.wikipedia.org/wiki/ACID\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/ACID</a>)</p>\n"
},
{
"answer_id": 103701,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 2,
"selected": false,
"text": "<p>Backwards compatibility is a big one. With C, it was assumed that you were paying enough attention to the size of your datatypes that if an over/underflow occurred, that that was what you wanted. Then with C++, C# and Java, very little changed with how the \"built-in\" data types worked. </p>\n"
},
{
"answer_id": 103711,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 4,
"selected": false,
"text": "<p>You work under the assumption that integer overflow is always undesired behavior.</p>\n\n<p>Sometimes integer overflow is desired behavior. One example I've seen is representation of an absolute heading value as a fixed point number. Given an unsigned int, 0 is 0 or 360 degrees and the max 32 bit unsigned integer (0xffffffff) is the biggest value just below 360 degrees.</p>\n\n<pre class=\"lang-c++ prettyprint-override\"><code>int main()\n{\n uint32_t shipsHeadingInDegrees= 0;\n\n // Rotate by a bunch of degrees\n shipsHeadingInDegrees += 0x80000000; // 180 degrees\n shipsHeadingInDegrees += 0x80000000; // another 180 degrees, overflows \n shipsHeadingInDegrees += 0x80000000; // another 180 degrees\n\n // Ships heading now will be 180 degrees\n cout << \"Ships Heading Is\" << (double(shipsHeadingInDegrees) / double(0xffffffff)) * 360.0 << std::endl;\n\n}\n</code></pre>\n\n<p>There are probably other situations where overflow is acceptable, similar to this example.</p>\n"
},
{
"answer_id": 104191,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 3,
"selected": false,
"text": "<p>C/C++ never mandate trap behaviour. Even the obvious division by 0 is undefined behaviour in C++, not a specified kind of trap.</p>\n\n<p>The C language doesn't have any concept of trapping, unless you count signals.</p>\n\n<p>C++ has a design principle that it doesn't introduce overhead not present in C unless you ask for it. So Stroustrup would not have wanted to mandate that integers behave in a way which requires any explicit checking.</p>\n\n<p>Some early compilers, and lightweight implementations for restricted hardware, don't support exceptions at all, and exceptions can often be disabled with compiler options. Mandating exceptions for language built-ins would be problematic.</p>\n\n<p>Even if C++ had made integers checked, 99% of programmers in the early days would have turned if off for the performance boost...</p>\n"
},
{
"answer_id": 108776,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 6,
"selected": true,
"text": "<p>In C#, it was a question of performance. Specifically, out-of-box benchmarking.</p>\n\n<p>When C# was new, Microsoft was hoping a lot of C++ developers would switch to it. They knew that many C++ folks thought of C++ as being fast, especially faster than languages that \"wasted\" time on automatic memory management and the like. </p>\n\n<p>Both potential adopters and magazine reviewers are likely to get a copy of the new C#, install it, build a trivial app that no one would ever write in the real world, run it in a tight loop, and measure how long it took. Then they'd make a decision for their company or publish an article based on that result.</p>\n\n<p>The fact that their test showed C# to be slower than natively compiled C++ is the kind of thing that would turn people off C# quickly. The fact that your C# app is going to catch overflow/underflow automatically is the kind of thing that they might miss. So, it's off by default.</p>\n\n<p>I think it's obvious that 99% of the time we want /checked to be on. It's an unfortunate compromise.</p>\n"
},
{
"answer_id": 60730517,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 1,
"selected": false,
"text": "<p>If integer overflow is defined as immediately raising a signal, throwing an exception, or otherwise deflecting program execution, then any computations which might overflow will need to be performed in the specified sequence. Even on platforms where integer overflow checking wouldn't cost anything directly, the requirement that integer overflow be trapped at exactly the right point in a program's execution sequence would severely impede many useful optimizations.</p>\n\n<p>If a language were to specify that integer overflows would instead set a latching error flag, were to limit how actions on that flag within a function could affect its value within calling code, and were to provide that the flag need not be set in circumstances where an overflow could not result in erroneous output or behavior, then compilers could generate more efficient code than any kind of manual overflow-checking programmers could use. As a simple example, if one had a function in C that would multiply two numbers and return a result, setting an error flag in case of overflow, a compiler would be required to perform the multiplication whether or not the caller would ever use the result. In a language with looser rules like I described, however, a compiler that determined that nothing ever uses the result of the multiply could infer that overflow could not affect a program's output, and skip the multiply altogether.</p>\n\n<p>From a practical standpoint, most programs don't care about precisely when overflows occur, so much as they need to guarantee that they don't produce erroneous results as a consequence of overflow. Unfortunately, programming languages' integer-overflow-detection semantics have not caught up with what would be necessary to let compilers produce efficient code.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12484/"
]
| In several modern programming languages (including C++, Java, and C#), the language allows [integer overflow](http://en.wikipedia.org/wiki/Integer_overflow) to occur at runtime without raising any kind of error condition.
For example, consider this (contrived) C# method, which does not account for the possibility of overflow/underflow. (For brevity, the method also doesn't handle the case where the specified list is a null reference.)
```c#
//Returns the sum of the values in the specified list.
private static int sumList(List<int> list)
{
int sum = 0;
foreach (int listItem in list)
{
sum += listItem;
}
return sum;
}
```
If this method is called as follows:
```c#
List<int> list = new List<int>();
list.Add(2000000000);
list.Add(2000000000);
int sum = sumList(list);
```
An overflow will occur in the `sumList()` method (because the `int` type in C# is a 32-bit signed integer, and the sum of the values in the list exceeds the value of the maximum 32-bit signed integer). The sum variable will have a value of -294967296 (not a value of 4000000000); this most likely is not what the (hypothetical) developer of the sumList method intended.
Obviously, there are various techniques that can be used by developers to avoid the possibility of integer overflow, such as using a type like Java's [`BigInteger`](http://java.sun.com/j2se/1.5.0/docs/api/java/math/BigInteger.html), or the [`checked`](http://msdn.microsoft.com/en-us/library/74b4xzyw.aspx) keyword and [`/checked`](http://msdn.microsoft.com/en-us/library/h25wtyxf.aspx) compiler switch in C#.
However, the question that I'm interested in is why these languages were designed to by default allow integer overflows to happen in the first place, instead of, for example, raising an exception when an operation is performed at runtime that would result in an overflow. It seems like such behavior would help avoid bugs in cases where a developer neglects to account for the possibility of overflow when writing code that performs an arithmetic operation that could result in overflow. (These languages could have included something like an "unchecked" keyword that could designate a block where integer overflow is permitted to occur without an exception being raised, in those cases where that behavior is explicitly intended by the developer; C# actually [does have this](http://msdn.microsoft.com/en-us/library/a569z7k8.aspx).)
Does the answer simply boil down to performance -- the language designers didn't want their respective languages to default to having "slow" arithmetic integer operations where the runtime would need to do extra work to check whether an overflow occurred, on every applicable arithmetic operation -- and this performance consideration outweighed the value of avoiding "silent" failures in the case that an inadvertent overflow occurs?
Are there other reasons for this language design decision as well, other than performance considerations? | In C#, it was a question of performance. Specifically, out-of-box benchmarking.
When C# was new, Microsoft was hoping a lot of C++ developers would switch to it. They knew that many C++ folks thought of C++ as being fast, especially faster than languages that "wasted" time on automatic memory management and the like.
Both potential adopters and magazine reviewers are likely to get a copy of the new C#, install it, build a trivial app that no one would ever write in the real world, run it in a tight loop, and measure how long it took. Then they'd make a decision for their company or publish an article based on that result.
The fact that their test showed C# to be slower than natively compiled C++ is the kind of thing that would turn people off C# quickly. The fact that your C# app is going to catch overflow/underflow automatically is the kind of thing that they might miss. So, it's off by default.
I think it's obvious that 99% of the time we want /checked to be on. It's an unfortunate compromise. |
103,725 | <p>I'm working on a project that generates PDFs that can contain fairly complex math and science formulas. The text is rendered in Times New Roman, which has pretty good Unicode coverage, but not complete. We have a system in place to swap in a more Unicode complete font for code points that don't have a glyph in TNR (like most of the "stranger" math symbols,) but I can't seem to find a way to query the *.ttf file to see if a given glyph is present. So far, I've just hard-coded a lookup table of which code points are present, but I'd much prefer an automatic solution.</p>
<p>I'm using VB.Net in a web system under ASP.net, but solutions in any programming language/environment would be appreciated.</p>
<p>Edit: The win32 solution looks excellent, but the specific case I'm trying to solve is in an ASP.Net web system. Is there a way to do this without including the windows API DLLs into my web site?</p>
| [
{
"answer_id": 103795,
"author": "Stephen Deken",
"author_id": 7154,
"author_profile": "https://Stackoverflow.com/users/7154",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.freetype.org/\" rel=\"nofollow noreferrer\">FreeType</a> is a library that can read TrueType font files (among others) and can be used to query the font for a specific glyph. However, FreeType is designed for rendering, so using it might cause you to pull in more code than you need for this solution.</p>\n\n<p>Unfortunately, there's not really a clear solution even within the world of OpenType / TrueType fonts; the character-to-glyph mapping has about a dozen different definitions depending on the type of font and what platform it was originally designed for. You might try to look at the <a href=\"http://www.microsoft.com/typography/otspec/cmap.htm\" rel=\"nofollow noreferrer\">cmap table definition</a> in Microsoft's copy of the <a href=\"http://www.microsoft.com/typography/otspec/otff.htm\" rel=\"nofollow noreferrer\">OpenType spec</a>, but it's not exactly easy reading.</p>\n"
},
{
"answer_id": 103807,
"author": "Rylee Corradini",
"author_id": 7542,
"author_profile": "https://Stackoverflow.com/users/7542",
"pm_score": 0,
"selected": false,
"text": "<p>This Microsoft KB article may help:\n<a href=\"http://support.microsoft.com/kb/241020\" rel=\"nofollow noreferrer\">http://support.microsoft.com/kb/241020</a></p>\n\n<p>It's a bit dated (was originally written for Windows 95), but the general principle may still apply. The sample code is C++, but since it's just calling standard Windows APIs, it'll more than likely work in .NET languages as well with a little elbow grease.</p>\n\n<p>-Edit-\nIt seems that the old 95-era APIs have been obsoleted by a new API Microsoft calls \"<a href=\"http://msdn.microsoft.com/en-us/library/ms776488(VS.85).aspx\" rel=\"nofollow noreferrer\">Uniscribe</a>\", which should be able to do what you need it to.</p>\n"
},
{
"answer_id": 103858,
"author": "Scott Nichols",
"author_id": 4299,
"author_profile": "https://Stackoverflow.com/users/4299",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a pass at it using c# and the windows API.</p>\n\n<pre><code>[DllImport(\"gdi32.dll\")]\npublic static extern uint GetFontUnicodeRanges(IntPtr hdc, IntPtr lpgs);\n\n[DllImport(\"gdi32.dll\")]\npublic extern static IntPtr SelectObject(IntPtr hDC, IntPtr hObject);\n\npublic struct FontRange\n{\n public UInt16 Low;\n public UInt16 High;\n}\n\npublic List<FontRange> GetUnicodeRangesForFont(Font font)\n{\n Graphics g = Graphics.FromHwnd(IntPtr.Zero);\n IntPtr hdc = g.GetHdc();\n IntPtr hFont = font.ToHfont();\n IntPtr old = SelectObject(hdc, hFont);\n uint size = GetFontUnicodeRanges(hdc, IntPtr.Zero);\n IntPtr glyphSet = Marshal.AllocHGlobal((int)size);\n GetFontUnicodeRanges(hdc, glyphSet);\n List<FontRange> fontRanges = new List<FontRange>();\n int count = Marshal.ReadInt32(glyphSet, 12);\n for (int i = 0; i < count; i++)\n {\n FontRange range = new FontRange();\n range.Low = (UInt16)Marshal.ReadInt16(glyphSet, 16 + i * 4);\n range.High = (UInt16)(range.Low + Marshal.ReadInt16(glyphSet, 18 + i * 4) - 1);\n fontRanges.Add(range);\n }\n SelectObject(hdc, old);\n Marshal.FreeHGlobal(glyphSet);\n g.ReleaseHdc(hdc);\n g.Dispose();\n return fontRanges;\n}\n\npublic bool CheckIfCharInFont(char character, Font font)\n{\n UInt16 intval = Convert.ToUInt16(character);\n List<FontRange> ranges = GetUnicodeRangesForFont(font);\n bool isCharacterPresent = false;\n foreach (FontRange range in ranges)\n {\n if (intval >= range.Low && intval <= range.High)\n {\n isCharacterPresent = true;\n break;\n }\n }\n return isCharacterPresent;\n}\n</code></pre>\n\n<p>Then, given a char toCheck that you want to check and a Font theFont to test it against...</p>\n\n<pre><code>if (!CheckIfCharInFont(toCheck, theFont) {\n // not present\n}\n</code></pre>\n\n<p>Same code using VB.Net</p>\n\n<pre><code><DllImport(\"gdi32.dll\")> _\nPublic Shared Function GetFontUnicodeRanges(ByVal hds As IntPtr, ByVal lpgs As IntPtr) As UInteger\nEnd Function \n\n<DllImport(\"gdi32.dll\")> _\nPublic Shared Function SelectObject(ByVal hDc As IntPtr, ByVal hObject As IntPtr) As IntPtr\nEnd Function \n\nPublic Structure FontRange\n Public Low As UInt16\n Public High As UInt16\nEnd Structure \n\nPublic Function GetUnicodeRangesForFont(ByVal font As Font) As List(Of FontRange)\n Dim g As Graphics\n Dim hdc, hFont, old, glyphSet As IntPtr\n Dim size As UInteger\n Dim fontRanges As List(Of FontRange)\n Dim count As Integer\n\n g = Graphics.FromHwnd(IntPtr.Zero)\n hdc = g.GetHdc()\n hFont = font.ToHfont()\n old = SelectObject(hdc, hFont)\n size = GetFontUnicodeRanges(hdc, IntPtr.Zero)\n glyphSet = Marshal.AllocHGlobal(CInt(size))\n GetFontUnicodeRanges(hdc, glyphSet)\n fontRanges = New List(Of FontRange)\n count = Marshal.ReadInt32(glyphSet, 12)\n\n For i = 0 To count - 1\n Dim range As FontRange = New FontRange\n range.Low = Marshal.ReadInt16(glyphSet, 16 + (i * 4))\n range.High = range.Low + Marshal.ReadInt16(glyphSet, 18 + (i * 4)) - 1\n fontRanges.Add(range)\n Next\n\n SelectObject(hdc, old)\n Marshal.FreeHGlobal(glyphSet)\n g.ReleaseHdc(hdc)\n g.Dispose()\n\n Return fontRanges\nEnd Function \n\nPublic Function CheckIfCharInFont(ByVal character As Char, ByVal font As Font) As Boolean\n Dim intval As UInt16 = Convert.ToUInt16(character)\n Dim ranges As List(Of FontRange) = GetUnicodeRangesForFont(font)\n Dim isCharacterPresent As Boolean = False\n\n For Each range In ranges\n If intval >= range.Low And intval <= range.High Then\n isCharacterPresent = True\n Exit For\n End If\n Next range\n Return isCharacterPresent\nEnd Function \n</code></pre>\n"
},
{
"answer_id": 1278132,
"author": "FarmerDave",
"author_id": 156516,
"author_profile": "https://Stackoverflow.com/users/156516",
"pm_score": 0,
"selected": false,
"text": "<p>The code posted by Scott Nichols is great, except for one bug: if the glyph id is greater than Int16.MaxValue, it throws an OverflowException. To fix it, I added the following function:</p>\n\n<pre><code>Protected Function Unsign(ByVal Input As Int16) As UInt16\n If Input > -1 Then\n Return CType(Input, UInt16)\n Else\n Return UInt16.MaxValue - (Not Input)\n End If\nEnd Function\n</code></pre>\n\n<p>And then changed the main for loop in the function GetUnicodeRangesForFont to look like this:</p>\n\n<pre><code>For i As Integer = 0 To count - 1\n Dim range As FontRange = New FontRange\n range.Low = Unsign(Marshal.ReadInt16(glyphSet, 16 + (i * 4)))\n range.High = range.Low + Unsign(Marshal.ReadInt16(glyphSet, 18 + (i * 4)) - 1)\n fontRanges.Add(range)\nNext\n</code></pre>\n"
},
{
"answer_id": 11333802,
"author": "David Thielen",
"author_id": 509627,
"author_profile": "https://Stackoverflow.com/users/509627",
"pm_score": 2,
"selected": false,
"text": "<p>Scott's answer is good. Here is another approach that is probably faster if checking just a couple of strings per font (in our case 1 string per font). But probably slower if you are using one font to check a ton of text.</p>\n\n<pre><code> [DllImport(\"gdi32.dll\", EntryPoint = \"CreateDC\", CharSet = CharSet.Auto, SetLastError = true)]\n private static extern IntPtr CreateDC(string lpszDriver, string lpszDeviceName, string lpszOutput, IntPtr devMode);\n\n [DllImport(\"gdi32.dll\", ExactSpelling = true, SetLastError = true)]\n private static extern bool DeleteDC(IntPtr hdc);\n\n [DllImport(\"Gdi32.dll\")]\n private static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj);\n\n [DllImport(\"Gdi32.dll\", CharSet = CharSet.Unicode)]\n private static extern int GetGlyphIndices(IntPtr hdc, [MarshalAs(UnmanagedType.LPWStr)] string lpstr, int c,\n Int16[] pgi, int fl);\n\n /// <summary>\n /// Returns true if the passed in string can be displayed using the passed in fontname. It checks the font to \n /// see if it has glyphs for all the chars in the string.\n /// </summary>\n /// <param name=\"fontName\">The name of the font to check.</param>\n /// <param name=\"text\">The text to check for glyphs of.</param>\n /// <returns></returns>\n public static bool CanDisplayString(string fontName, string text)\n {\n try\n {\n IntPtr hdc = CreateDC(\"DISPLAY\", null, null, IntPtr.Zero);\n if (hdc != IntPtr.Zero)\n {\n using (Font font = new Font(new FontFamily(fontName), 12, FontStyle.Regular, GraphicsUnit.Point))\n {\n SelectObject(hdc, font.ToHfont());\n int count = text.Length;\n Int16[] rtcode = new Int16[count];\n GetGlyphIndices(hdc, text, count, rtcode, 0xffff);\n DeleteDC(hdc);\n\n foreach (Int16 code in rtcode)\n if (code == 0)\n return false;\n }\n }\n }\n catch (Exception)\n {\n // nada - return true\n Trap.trap();\n }\n return true;\n }\n</code></pre>\n"
},
{
"answer_id": 55349185,
"author": "brewmanz",
"author_id": 2821586,
"author_profile": "https://Stackoverflow.com/users/2821586",
"pm_score": 0,
"selected": false,
"text": "<p>I have done this with just a VB.Net Unit Test and no WIN32 API calls. It includes code to check specific characters U+2026 (ellipsis) & U+2409 (HTab), and also returns # of characters (and low and high values) that have glyphs. I was only interested in Monospace fonts, but easy enough to change ...</p>\n<pre><code> Dim fnt As System.Drawing.Font, size_M As Drawing.Size, size_i As Drawing.Size, size_HTab As Drawing.Size, isMonospace As Boolean\n Dim ifc = New Drawing.Text.InstalledFontCollection\n Dim bm As Drawing.Bitmap = New Drawing.Bitmap(640, 64), gr = Drawing.Graphics.FromImage(bm)\n Dim tf As Windows.Media.Typeface, gtf As Windows.Media.GlyphTypeface = Nothing, ok As Boolean, gtfName = ""\n\n For Each item In ifc.Families\n 'TestContext_WriteTimedLine($"N={item.Name}.")\n fnt = New Drawing.Font(item.Name, 24.0)\n Assert.IsNotNull(fnt)\n\n tf = New Windows.Media.Typeface(item.Name)\n Assert.IsNotNull(tf, $"item.Name={item.Name}")\n\n size_M = System.Windows.Forms.TextRenderer.MeasureText("M", fnt)\n size_i = System.Windows.Forms.TextRenderer.MeasureText("i", fnt)\n size_HTab = System.Windows.Forms.TextRenderer.MeasureText(ChrW(&H2409), fnt)\n isMonospace = size_M.Width = size_i.Width\n Assert.AreEqual(size_M.Height, size_i.Height, $"fnt={fnt.Name}")\n\n If isMonospace Then\n\n gtfName = "-"\n ok = tf.TryGetGlyphTypeface(gtf)\n If ok Then\n Assert.AreEqual(True, ok, $"item.Name={item.Name}")\n Assert.IsNotNull(gtf, $"item.Name={item.Name}")\n gtfName = $"{gtf.FamilyNames(Globalization.CultureInfo.CurrentUICulture)}"\n\n Assert.AreEqual(True, gtf.CharacterToGlyphMap().ContainsKey(AscW("M")), $"item.Name={item.Name}")\n Assert.AreEqual(True, gtf.CharacterToGlyphMap().ContainsKey(AscW("i")), $"item.Name={item.Name}")\n\n Dim t = 0, nMin = &HFFFF, nMax = 0\n For n = 0 To &HFFFF\n If gtf.CharacterToGlyphMap().ContainsKey(n) Then\n If n < nMin Then nMin = n\n If n > nMax Then nMax = n\n t += 1\n End If\n Next\n gtfName &= $",[x{nMin:X}-x{nMax:X}]#{t}"\n\n ok = gtf.CharacterToGlyphMap().ContainsKey(AscW(ChrW(&H2409)))\n If ok Then\n gtfName &= ",U+2409"\n End If\n ok = gtf.CharacterToGlyphMap().ContainsKey(AscW(ChrW(&H2026)))\n If ok Then\n gtfName &= ",U+2026"\n End If\n End If\n\n Debug.WriteLine($"{IIf(isMonospace, "*M*", "")} N={fnt.Name}, gtf={gtfName}.")\n gr.Clear(Drawing.Color.White)\n gr.DrawString($"Mi{ChrW(&H2409)} {fnt.Name}", fnt, New Drawing.SolidBrush(Drawing.Color.Black), 10, 10)\n bm.Save($"{fnt.Name}_MiHT.bmp")\n End If\n Next\n</code></pre>\n<p>The output was</p>\n<blockquote>\n<p><em>M</em> N=Consolas, gtf=Consolas,[x0-xFFFC]#2488,U+2026.</p>\n<p><em>M</em> N=Courier New, gtf=Courier New,[x20-xFFFC]#3177,U+2026.</p>\n<p><em>M</em> N=Lucida Console, gtf=Lucida Console,[x20-xFB02]#644,U+2026.</p>\n<p><em>M</em> N=Lucida Sans Typewriter, gtf=Lucida Sans Typewriter,[x20-xF002]#240,U+2026.</p>\n<p><em>M</em> N=MingLiU-ExtB, gtf=MingLiU-ExtB,[x0-x2122]#212.</p>\n<p><em>M</em> N=MingLiU_HKSCS-ExtB, gtf=MingLiU_HKSCS-ExtB,[x0-x2122]#212.</p>\n<p><em>M</em> N=MS Gothic, gtf=MS Gothic,[x0-xFFEE]#15760,U+2026.</p>\n<p><em>M</em> N=NSimSun, gtf=NSimSun,[x20-xFFE5]#28737,U+2026.</p>\n<p><em>M</em> N=OCR A Extended, gtf=OCR A Extended,[x20-xF003]#248,U+2026.</p>\n<p><em>M</em> N=SimSun, gtf=SimSun,[x20-xFFE5]#28737,U+2026.</p>\n<p><em>M</em> N=SimSun-ExtB, gtf=SimSun-ExtB,[x20-x7F]#96.</p>\n<p><em>M</em> N=Webdings, gtf=Webdings,[x20-xF0FF]#446.</p>\n</blockquote>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19074/"
]
| I'm working on a project that generates PDFs that can contain fairly complex math and science formulas. The text is rendered in Times New Roman, which has pretty good Unicode coverage, but not complete. We have a system in place to swap in a more Unicode complete font for code points that don't have a glyph in TNR (like most of the "stranger" math symbols,) but I can't seem to find a way to query the \*.ttf file to see if a given glyph is present. So far, I've just hard-coded a lookup table of which code points are present, but I'd much prefer an automatic solution.
I'm using VB.Net in a web system under ASP.net, but solutions in any programming language/environment would be appreciated.
Edit: The win32 solution looks excellent, but the specific case I'm trying to solve is in an ASP.Net web system. Is there a way to do this without including the windows API DLLs into my web site? | Here's a pass at it using c# and the windows API.
```
[DllImport("gdi32.dll")]
public static extern uint GetFontUnicodeRanges(IntPtr hdc, IntPtr lpgs);
[DllImport("gdi32.dll")]
public extern static IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
public struct FontRange
{
public UInt16 Low;
public UInt16 High;
}
public List<FontRange> GetUnicodeRangesForFont(Font font)
{
Graphics g = Graphics.FromHwnd(IntPtr.Zero);
IntPtr hdc = g.GetHdc();
IntPtr hFont = font.ToHfont();
IntPtr old = SelectObject(hdc, hFont);
uint size = GetFontUnicodeRanges(hdc, IntPtr.Zero);
IntPtr glyphSet = Marshal.AllocHGlobal((int)size);
GetFontUnicodeRanges(hdc, glyphSet);
List<FontRange> fontRanges = new List<FontRange>();
int count = Marshal.ReadInt32(glyphSet, 12);
for (int i = 0; i < count; i++)
{
FontRange range = new FontRange();
range.Low = (UInt16)Marshal.ReadInt16(glyphSet, 16 + i * 4);
range.High = (UInt16)(range.Low + Marshal.ReadInt16(glyphSet, 18 + i * 4) - 1);
fontRanges.Add(range);
}
SelectObject(hdc, old);
Marshal.FreeHGlobal(glyphSet);
g.ReleaseHdc(hdc);
g.Dispose();
return fontRanges;
}
public bool CheckIfCharInFont(char character, Font font)
{
UInt16 intval = Convert.ToUInt16(character);
List<FontRange> ranges = GetUnicodeRangesForFont(font);
bool isCharacterPresent = false;
foreach (FontRange range in ranges)
{
if (intval >= range.Low && intval <= range.High)
{
isCharacterPresent = true;
break;
}
}
return isCharacterPresent;
}
```
Then, given a char toCheck that you want to check and a Font theFont to test it against...
```
if (!CheckIfCharInFont(toCheck, theFont) {
// not present
}
```
Same code using VB.Net
```
<DllImport("gdi32.dll")> _
Public Shared Function GetFontUnicodeRanges(ByVal hds As IntPtr, ByVal lpgs As IntPtr) As UInteger
End Function
<DllImport("gdi32.dll")> _
Public Shared Function SelectObject(ByVal hDc As IntPtr, ByVal hObject As IntPtr) As IntPtr
End Function
Public Structure FontRange
Public Low As UInt16
Public High As UInt16
End Structure
Public Function GetUnicodeRangesForFont(ByVal font As Font) As List(Of FontRange)
Dim g As Graphics
Dim hdc, hFont, old, glyphSet As IntPtr
Dim size As UInteger
Dim fontRanges As List(Of FontRange)
Dim count As Integer
g = Graphics.FromHwnd(IntPtr.Zero)
hdc = g.GetHdc()
hFont = font.ToHfont()
old = SelectObject(hdc, hFont)
size = GetFontUnicodeRanges(hdc, IntPtr.Zero)
glyphSet = Marshal.AllocHGlobal(CInt(size))
GetFontUnicodeRanges(hdc, glyphSet)
fontRanges = New List(Of FontRange)
count = Marshal.ReadInt32(glyphSet, 12)
For i = 0 To count - 1
Dim range As FontRange = New FontRange
range.Low = Marshal.ReadInt16(glyphSet, 16 + (i * 4))
range.High = range.Low + Marshal.ReadInt16(glyphSet, 18 + (i * 4)) - 1
fontRanges.Add(range)
Next
SelectObject(hdc, old)
Marshal.FreeHGlobal(glyphSet)
g.ReleaseHdc(hdc)
g.Dispose()
Return fontRanges
End Function
Public Function CheckIfCharInFont(ByVal character As Char, ByVal font As Font) As Boolean
Dim intval As UInt16 = Convert.ToUInt16(character)
Dim ranges As List(Of FontRange) = GetUnicodeRangesForFont(font)
Dim isCharacterPresent As Boolean = False
For Each range In ranges
If intval >= range.Low And intval <= range.High Then
isCharacterPresent = True
Exit For
End If
Next range
Return isCharacterPresent
End Function
``` |
103,765 | <p>Here's the situation: I have a label's text set, immediately followed by a response.redirect() call as follows (this is just an example, but I believe it describes my situation accurately):</p>
<p>aspx:</p>
<pre><code><asp:Label runat="server" Text="default text" />
</code></pre>
<p>Code-behind (code called on an onclick event):</p>
<pre><code>Label.Text = "foo";
Response.Redirect("Default.aspx");
</code></pre>
<p>When the page renders, the label says "default text". What do I need to do differently? My understanding was that such changes would be done automatically behind the scenes, but apparently, not in this case. Thanks.</p>
<p>For a little extra background, the code-behind snippet is called inside a method that's invoked upon an onclick event. There is more to it, but I only included that which is of interest to this issue.</p>
| [
{
"answer_id": 103813,
"author": "Orion Adrian",
"author_id": 7756,
"author_profile": "https://Stackoverflow.com/users/7756",
"pm_score": 1,
"selected": false,
"text": "<p>ASP and ASP.Net are inherently stateless unless state is explicitly specified. Normally between PostBacks information like the value of a label is contained in the viewstate, but if you change pages that viewstate is lost because it is was being stored in a hidden field on the page.</p>\n\n<p>If you want to maintain the value of the label between calls you need to use one of the state mechanisms (e.g. Session, Preferences) or communication systems (Request (GET, POST)).</p>\n\n<p>Additionally you may be looking for Server.Transfer which will change who is processing the page behind the scenes. Response.Redirect is designed to ditch your current context in most cases.</p>\n"
},
{
"answer_id": 103816,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 2,
"selected": false,
"text": "<p>A <code>Response.Redirect</code> call will ask the user's browser to load the page specified in the URL you give it. Because this is a new request for your page the page utilises the text which is contained in your markup (as I assume that the label text is being set inside a button handler or similar).</p>\n\n<p>If you remove the <code>Response.Redirect</code> call your page should work as advertised.</p>\n"
},
{
"answer_id": 103826,
"author": "David Thibault",
"author_id": 5903,
"author_profile": "https://Stackoverflow.com/users/5903",
"pm_score": 2,
"selected": true,
"text": "<p>After a redirect you will loose any state information associated to your controls. If you simply want the page to refresh, remove the redirect. After the code has finished executing, the page will refresh and any state will be kept.</p>\n\n<p>Behind the scenes, this works because ASP.NET writes the state information to a hidden input field on the page. When you click a button, the form is posted and ASP.NET deciphers the viewstate. Your code runs, modifying the state, and after that the state is again written to the hidden field and the cycle continues, <strong>until you change the page without a POST</strong>. This can happen when clicking an hyperlink to another page, or via Response.Redirect(), which instructs the browser to follow the specified url.</p>\n"
},
{
"answer_id": 103865,
"author": "MrBoJangles",
"author_id": 13578,
"author_profile": "https://Stackoverflow.com/users/13578",
"pm_score": 0,
"selected": false,
"text": "<p>So, if I may answer my own question (according to the FAQ, that's encouraged), the short answer is, you don't persist view state through redirects. View state is for postbacks, not redirects.</p>\n\n<p>Bonus: <a href=\"http://msdn.microsoft.com/en-us/library/ms972976.aspx#viewstate_topic10\" rel=\"nofollow noreferrer\">Everything you ever wanted to know about View State in ASP.NET</a>, with pictures!</p>\n"
},
{
"answer_id": 104020,
"author": "Nikki9696",
"author_id": 456669,
"author_profile": "https://Stackoverflow.com/users/456669",
"pm_score": 1,
"selected": false,
"text": "<p>To persist state, use Server.Transfer instead of Response.Redirect.</p>\n"
},
{
"answer_id": 142437,
"author": "MrBoJangles",
"author_id": 13578,
"author_profile": "https://Stackoverflow.com/users/13578",
"pm_score": 0,
"selected": false,
"text": "<p>For what it's worth (and hopefully it's worth something), Chapter 6 of <a href=\"https://rads.stackoverflow.com/amzn/click/com/1590598938\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Pro ASP.NET 3.5 in C# 2008, Second Edition</a> is a terrific resource on the subject. The whole book has been great so far.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103765",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13578/"
]
| Here's the situation: I have a label's text set, immediately followed by a response.redirect() call as follows (this is just an example, but I believe it describes my situation accurately):
aspx:
```
<asp:Label runat="server" Text="default text" />
```
Code-behind (code called on an onclick event):
```
Label.Text = "foo";
Response.Redirect("Default.aspx");
```
When the page renders, the label says "default text". What do I need to do differently? My understanding was that such changes would be done automatically behind the scenes, but apparently, not in this case. Thanks.
For a little extra background, the code-behind snippet is called inside a method that's invoked upon an onclick event. There is more to it, but I only included that which is of interest to this issue. | After a redirect you will loose any state information associated to your controls. If you simply want the page to refresh, remove the redirect. After the code has finished executing, the page will refresh and any state will be kept.
Behind the scenes, this works because ASP.NET writes the state information to a hidden input field on the page. When you click a button, the form is posted and ASP.NET deciphers the viewstate. Your code runs, modifying the state, and after that the state is again written to the hidden field and the cycle continues, **until you change the page without a POST**. This can happen when clicking an hyperlink to another page, or via Response.Redirect(), which instructs the browser to follow the specified url. |
103,829 | <p>Given the following:</p>
<pre><code>declare @a table
(
pkid int,
value int
)
declare @b table
(
otherID int,
value int
)
insert into @a values (1, 1000)
insert into @a values (1, 1001)
insert into @a values (2, 1000)
insert into @a values (2, 1001)
insert into @a values (2, 1002)
insert into @b values (-1, 1000)
insert into @b values (-1, 1001)
insert into @b values (-1, 1002)
</code></pre>
<p>How do I query for all the values in @a that completely match up with @b? </p>
<p><code>{@a.pkid = 1, @b.otherID = -1}</code> would not be returned (only 2 of 3 values match)</p>
<p><code>{@a.pkid = 2, @b.otherID = -1}</code> would be returned (3 of 3 values match)</p>
<p>Refactoring tables can be an option.</p>
<p><strong>EDIT:</strong> I've had success with the answers from James and Tom H. </p>
<p>When I add another case in @b, they fall a little short.</p>
<pre><code>insert into @b values (-2, 1000)
</code></pre>
<p>Assuming this should return two additional rows (<code>{@a.pkid = 1, @b.otherID = -2}</code> and <code>{@a.pkid = 2, @b.otherID = -2}</code>, it doesn't work. However, for my project this is not an issue.</p>
| [
{
"answer_id": 103910,
"author": "Cruachan",
"author_id": 7315,
"author_profile": "https://Stackoverflow.com/users/7315",
"pm_score": 0,
"selected": false,
"text": "<p>Several ways of doing this, but a simple one is to create a union view as</p>\n\n<pre><code>create view qryMyUinion as\nselect * from table1 \nunion all\nselect * from table2\n</code></pre>\n\n<p>be careful to use union all, not a simple union as that will omit the duplicates</p>\n\n<p>then do this </p>\n\n<pre><code>select count( * ), [field list here] \nfrom qryMyUnion\ngroup by [field list here]\nhaving count( * ) > 1\n</code></pre>\n\n<p>the Union and Having statements tend to be the most overlooked part of standard SQL, but they can solve a lot of tricky issues that otherwise require procedural code</p>\n"
},
{
"answer_id": 104001,
"author": "James",
"author_id": 2719,
"author_profile": "https://Stackoverflow.com/users/2719",
"pm_score": 4,
"selected": true,
"text": "<p>Probably not the cheapest way to do it:</p>\n\n<pre><code>SELECT a.pkId,b.otherId FROM\n (SELECT a.pkId,CHECKSUM_AGG(DISTINCT a.value) as 'ValueHash' FROM @a a GROUP BY a.pkId) a\n INNER JOIN (SELECT b.otherId,CHECKSUM_AGG(DISTINCT b.value) as 'ValueHash' FROM @b b GROUP BY b.otherId) b\nON a.ValueHash = b.ValueHash\n</code></pre>\n\n<p>You can see, basically I'm creating a new result set for each representing one value for each Id's set of values in each table and joining only where they match.</p>\n"
},
{
"answer_id": 104007,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 0,
"selected": false,
"text": "<p>If you are trying to return only complete sets of records, you could try this. I would definitely recommend using meaningful aliases, though ...</p>\n\n<p>Cervo is right, we need an additional check to ensure that a is an exact match of b and not a superset of b. This is more of an unwieldy solution at this point, so this would only be reasonable in contexts where analytical functions in the other solutions do not work.</p>\n\n<pre><code>select \n a.pkid,\n a.value\nfrom\n @a a\nwhere\n a.pkid in\n (\n select\n pkid\n from\n (\n select \n c.pkid,\n c.otherid,\n count(*) matching_count\n from \n (\n select \n a.pkid,\n a.value,\n b.otherid\n from \n @a a inner join @b b \n on a.value = b.value\n ) c\n group by \n c.pkid,\n c.otherid\n ) d\n inner join\n (\n select \n b.otherid,\n count(*) b_record_count\n from\n @b b\n group by\n b.otherid\n ) e\n on d.otherid = e.otherid\n and d.matching_count = e.b_record_count\n inner join\n (\n select \n a.pkid match_pkid,\n count(*) a_record_count\n from\n @a a\n group by\n a.pkid\n ) f\n on d.pkid = f.match_pkid\n and d.matching_count = f.a_record_count\n )\n</code></pre>\n"
},
{
"answer_id": 104049,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 1,
"selected": false,
"text": "<p>Works for your example, and I think it will work for all cases, but I haven't tested it thoroughly:</p>\n\n<pre><code>SELECT\n SQ1.pkid\nFROM\n (\n SELECT\n a.pkid, COUNT(*) AS cnt\n FROM\n @a AS a\n GROUP BY\n a.pkid\n ) SQ1\nINNER JOIN\n (\n SELECT\n a1.pkid, b1.otherID, COUNT(*) AS cnt\n FROM\n @a AS a1\n INNER JOIN @b AS b1 ON b1.value = a1.value\n GROUP BY\n a1.pkid, b1.otherID\n ) SQ2 ON\n SQ2.pkid = SQ1.pkid AND\n SQ2.cnt = SQ1.cnt\nINNER JOIN\n (\n SELECT\n b2.otherID, COUNT(*) AS cnt\n FROM\n @b AS b2\n GROUP BY\n b2.otherID\n ) SQ3 ON\n SQ3.otherID = SQ2.otherID AND\n SQ3.cnt = SQ1.cnt\n</code></pre>\n"
},
{
"answer_id": 104064,
"author": "Dave Jackson",
"author_id": 12328,
"author_profile": "https://Stackoverflow.com/users/12328",
"pm_score": -1,
"selected": false,
"text": "<p>As CQ says, a simple inner join is all you need.</p>\n\n<pre><code>Select * -- all columns but only from #a\nfrom #a \ninner join #b \non #a.value = #b.value -- only return matching rows\nwhere #a.pkid = 2\n</code></pre>\n"
},
{
"answer_id": 104170,
"author": "Cervo",
"author_id": 16219,
"author_profile": "https://Stackoverflow.com/users/16219",
"pm_score": 1,
"selected": false,
"text": "<pre>\n-- Note, only works as long as no duplicate values are allowed in either table\nDECLARE @validcomparisons TABLE (\n pkid INT,\n otherid INT,\n num INT\n)\n\nINSERT INTO @validcomparisons (pkid, otherid, num)\nSELECT a.pkid, b.otherid, A.cnt\nFROM (select pkid, count(*) as cnt FROM @a group by pkid) a\nINNER JOIN (select otherid, count(*) as cnt from @b group by otherid) b \n ON b.cnt = a.cnt\n\nDECLARE @comparison TABLE (\n pkid INT,\n otherid INT,\n same INT)\n\ninsert into @comparison(pkid, otherid, same)\nSELECT a.pkid, b.otherid, count(*)\nFROM @a a\nINNER JOIN @b b\n ON a.value = b.value\nGROUP BY a.pkid, b.otherid\n\nSELECT COMP.PKID, COMP.OTHERID\nFROM @comparison comp\nINNER JOIN @validcomparisons val\n ON comp.pkid = val.pkid\n AND comp.otherid = val.otherid\n AND comp.same = val.num\n</pre>\n"
},
{
"answer_id": 104204,
"author": "boes",
"author_id": 17746,
"author_profile": "https://Stackoverflow.com/users/17746",
"pm_score": 2,
"selected": false,
"text": "<p>The following query gives you the requested results:</p>\n\n<pre><code>select A.pkid, B.otherId\n from @a A, @b B \n where A.value = B.value\n group by A.pkid, B.otherId\n having count(B.value) = (\n select count(*) from @b BB where B.otherId = BB.otherId)\n</code></pre>\n"
},
{
"answer_id": 104240,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>To iterate the point further:</p>\n\n<pre><code>select a.*\nfrom @a a \ninner join @b b on a.value = b.value\n</code></pre>\n\n<p>This will return all the values in @a that match @b</p>\n"
},
{
"answer_id": 104327,
"author": "user19143",
"author_id": 19143,
"author_profile": "https://Stackoverflow.com/users/19143",
"pm_score": 1,
"selected": false,
"text": "<p>I've added a few extra test cases. You can change your duplicate handling by changing the way you use distinct keywords in your aggregates. Basically, I'm getting a count of matches and comparing it to a count of required matches in each @a and @b.</p>\n\n<pre><code>declare @a table\n(\n pkid int,\n value int\n)\n\ndeclare @b table\n(\n otherID int,\n value int\n)\n\n\ninsert into @a values (1, 1000)\ninsert into @a values (1, 1001)\n\ninsert into @a values (2, 1000)\ninsert into @a values (2, 1001)\ninsert into @a values (2, 1002)\n\ninsert into @a values (3, 1000)\ninsert into @a values (3, 1001)\ninsert into @a values (3, 1001)\n\ninsert into @a values (4, 1000)\ninsert into @a values (4, 1000)\ninsert into @a values (4, 1001)\n\n\ninsert into @b values (-1, 1000)\ninsert into @b values (-1, 1001)\ninsert into @b values (-1, 1002)\n\ninsert into @b values (-2, 1001)\ninsert into @b values (-2, 1002)\n\ninsert into @b values (-3, 1000)\ninsert into @b values (-3, 1001)\ninsert into @b values (-3, 1001)\n\n\n\nSELECT Matches.pkid, Matches.otherId\nFROM\n(\n SELECT a.pkid, b.otherId, n = COUNT(*)\n FROM @a a\n INNER JOIN @b b\n ON a.Value = b.Value\n GROUP BY a.pkid, b.otherId\n) AS Matches\n\nINNER JOIN \n(\n SELECT\n pkid,\n n = COUNT(DISTINCT value)\n FROM @a\n GROUP BY pkid\n) AS ACount\nON Matches.pkid = ACount.pkid\n\nINNER JOIN\n(\n SELECT\n otherId,\n n = COUNT(DISTINCT value)\n FROM @b\n GROUP BY otherId\n) AS BCount\n ON Matches.otherId = BCount.otherId\n\nWHERE Matches.n = ACount.n AND Matches.n = BCount.n\n</code></pre>\n"
},
{
"answer_id": 105108,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>1) i assume that you don't have duplicate id</p>\n\n<p>2) get the key with the same number of value</p>\n\n<p>3) the row with the number of key value equal to the number of equal value is the target</p>\n\n<p>I hope it's what you searched for (you don't search performance don't you ?)</p>\n\n<pre><code>declare @a table( pkid int, value int)\ndeclare @b table( otherID int, value int)\n\ninsert into @a values (1, 1000)\ninsert into @a values (1, 1001)\ninsert into @a values (2, 1000)\ninsert into @a values (2, 1001)\ninsert into @a values (2, 1002)\ninsert into @a values (3, 1000) \ninsert into @a values (3, 1001)\ninsert into @a values (4, 1000)\ninsert into @a values (4, 1001)\ninsert into @b values (-1, 1000)\ninsert into @b values (-1, 1001)\ninsert into @b values (-1, 1002)\ninsert into @b values (-2, 1001)\ninsert into @b values (-2, 1002)\ninsert into @b values (-3, 1000)\ninsert into @b values (-3, 1001)\n\n select cntok.cntid1 as cntid1, cntok.cntid2 as cntid2\n from\n (select cnt.cnt, cnt.cntid1, cnt.cntid2 from\n (select acnt.cnt as cnt, acnt.cntid as cntid1, bcnt.cntid as cntid2 from\n (select count(pkid) as cnt, pkid as cntid from @a group by pkid)\n as acnt\n full join \n (select count(otherID) as cnt, otherID as cntid from @b group by otherID)\n as bcnt\n on acnt.cnt = bcnt.cnt)\n as cnt\n where cntid1 is not null and cntid2 is not null)\n as cntok \ninner join \n(select count(1) as cnt, cnta.cntid1 as cntid1, cnta.cntid2 as cntid2\nfrom\n (select cnt, cntid1, cntid2, a.value as value1 \n from\n (select cnt.cnt, cnt.cntid1, cnt.cntid2 from\n (select acnt.cnt as cnt, acnt.cntid as cntid1, bcnt.cntid as cntid2 from\n (select count(pkid) as cnt, pkid as cntid from @a group by pkid)\n as acnt\n full join \n (select count(otherID) as cnt, otherID as cntid from @b group by otherID)\n as bcnt\n on acnt.cnt = bcnt.cnt)\n as cnt\n where cntid1 is not null and cntid2 is not null)\n as cntok \n inner join @a as a on a.pkid = cntok.cntid1)\n as cnta\n inner join\n\n (select cnt, cntid1, cntid2, b.value as value2 \n from\n (select cnt.cnt, cnt.cntid1, cnt.cntid2 from\n (select acnt.cnt as cnt, acnt.cntid as cntid1, bcnt.cntid as cntid2 from\n (select count(pkid) as cnt, pkid as cntid from @a group by pkid)\n as acnt\n full join \n (select count(otherID) as cnt, otherID as cntid from @b group by otherID)\n as bcnt\n on acnt.cnt = bcnt.cnt)\n as cnt\n where cntid1 is not null and cntid2 is not null)\n as cntok \n inner join @b as b on b.otherid = cntok.cntid2)\n as cntb\n on cnta.cntid1 = cntb.cntid1 and cnta.cntid2 = cntb.cntid2 and cnta.value1 = cntb.value2\n group by cnta.cntid1, cnta.cntid2) \n as cntequals\n on cntok.cnt = cntequals.cnt and cntok.cntid1 = cntequals.cntid1 and cntok.cntid2 = cntequals.cntid2\n</code></pre>\n"
},
{
"answer_id": 105562,
"author": "user19164",
"author_id": 19164,
"author_profile": "https://Stackoverflow.com/users/19164",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>How do I query for all the values in @a that completely match up with @b? </p>\n</blockquote>\n\n<p>I'm afraid this definition is not quite perfectly clear. It seems from your additional example that you want all pairs of a.pkid, b.otherID for which every b.value for the given b.otherID is also an a.value for the given a.pkid.</p>\n\n<p>In other words, you want the pkids in @a that have <strong>at least</strong> all the values for otherIDs in b. Extra values in @a appear to be okay. Again, this is reasoning based on your additional example, and the assumption that (1, -2) and (2, -2) would be valid results. In both of those cases, the a.value values for the given pkid are <strong>more than</strong> the b.value values for the given otherID.</p>\n\n<p>So, with that in mind:</p>\n\n<pre><code> select\n matches.pkid\n ,matches.otherID\nfrom\n(\n select \n a.pkid\n ,b.otherID\n ,count(1) as cnt\n from @a a\n inner join @b b\n on b.value = a.value\n group by \n a.pkid\n ,b.otherID\n) as matches\ninner join\n(\n select\n otherID\n ,count(1) as cnt\n from @b\n group by otherID\n) as b_counts\non b_counts.otherID = matches.otherID\nwhere matches.cnt = b_counts.cnt\n</code></pre>\n"
},
{
"answer_id": 713969,
"author": "Quassnoi",
"author_id": 55159,
"author_profile": "https://Stackoverflow.com/users/55159",
"pm_score": 3,
"selected": false,
"text": "<p>This is more efficient (it uses <code>TOP 1</code> instead of <code>COUNT</code>), and works with <code>(-2, 1000)</code>:</p>\n\n<pre><code>SELECT *\nFROM (\n SELECT ab.pkid, ab.otherID,\n (\n SELECT TOP 1 COALESCE(ai.value, bi.value)\n FROM (\n SELECT *\n FROM @a aii\n WHERE aii.pkid = ab.pkid\n ) ai\n FULL OUTER JOIN\n (\n SELECT *\n FROM @b bii\n WHERE bii.otherID = ab.otherID\n ) bi\n ON ai.value = bi.value\n WHERE ai.pkid IS NULL OR bi.otherID IS NULL\n ) unmatch\n FROM\n (\n SELECT DISTINCT pkid, otherid\n FROM @a a , @b b\n ) ab\n ) q\nWHERE unmatch IS NOT NULL\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103829",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4068/"
]
| Given the following:
```
declare @a table
(
pkid int,
value int
)
declare @b table
(
otherID int,
value int
)
insert into @a values (1, 1000)
insert into @a values (1, 1001)
insert into @a values (2, 1000)
insert into @a values (2, 1001)
insert into @a values (2, 1002)
insert into @b values (-1, 1000)
insert into @b values (-1, 1001)
insert into @b values (-1, 1002)
```
How do I query for all the values in @a that completely match up with @b?
`{@a.pkid = 1, @b.otherID = -1}` would not be returned (only 2 of 3 values match)
`{@a.pkid = 2, @b.otherID = -1}` would be returned (3 of 3 values match)
Refactoring tables can be an option.
**EDIT:** I've had success with the answers from James and Tom H.
When I add another case in @b, they fall a little short.
```
insert into @b values (-2, 1000)
```
Assuming this should return two additional rows (`{@a.pkid = 1, @b.otherID = -2}` and `{@a.pkid = 2, @b.otherID = -2}`, it doesn't work. However, for my project this is not an issue. | Probably not the cheapest way to do it:
```
SELECT a.pkId,b.otherId FROM
(SELECT a.pkId,CHECKSUM_AGG(DISTINCT a.value) as 'ValueHash' FROM @a a GROUP BY a.pkId) a
INNER JOIN (SELECT b.otherId,CHECKSUM_AGG(DISTINCT b.value) as 'ValueHash' FROM @b b GROUP BY b.otherId) b
ON a.ValueHash = b.ValueHash
```
You can see, basically I'm creating a new result set for each representing one value for each Id's set of values in each table and joining only where they match. |
103,844 | <p>List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers.</p>
<p>Say, I have a 2D list:</p>
<pre><code>li = [[0,1,2],[3,4,5],[6,7,8]]
</code></pre>
<p>I would like to merge this either into one long list</p>
<pre><code>li2 = [0,1,2,3,4,5,6,7,8]
</code></pre>
<p>or into a string with separators:</p>
<pre><code>s = "0,1,2,3,4,5,6,7,8"
</code></pre>
<p>Really, I'd like to know how to do both.</p>
| [
{
"answer_id": 103873,
"author": "joeld",
"author_id": 19104,
"author_profile": "https://Stackoverflow.com/users/19104",
"pm_score": 0,
"selected": false,
"text": "<pre><code>import itertools\nitertools.flatten( li )\n</code></pre>\n"
},
{
"answer_id": 103883,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 0,
"selected": false,
"text": "<p>To make it a flattened list use either:</p>\n\n<ol>\n<li><a href=\"http://code.activestate.com/recipes/121294/\" rel=\"nofollow noreferrer\">http://code.activestate.com/recipes/121294/</a></li>\n<li><a href=\"http://code.activestate.com/recipes/363051/\" rel=\"nofollow noreferrer\">http://code.activestate.com/recipes/363051/</a></li>\n</ol>\n\n<p>Then, <code>join</code> to make it a string.</p>\n"
},
{
"answer_id": 103886,
"author": "Allen",
"author_id": 6043,
"author_profile": "https://Stackoverflow.com/users/6043",
"pm_score": 3,
"selected": false,
"text": "<p>There's a couple choices. First, you can just create a new list and add the contents of each list to it:</p>\n\n<pre><code>li2 = []\nfor sublist in li:\n li2.extend(sublist)\n</code></pre>\n\n<p>Alternately, you can use the <code>itertools</code> module's <code>chain</code> function, which produces an iterable containing all the items in multiple iterables:</p>\n\n<pre><code>import itertools\nli2 = list(itertools.chain(*li))\n</code></pre>\n\n<p>If you take this approach, you can produce the string without creating an intermediate list:</p>\n\n<pre><code>s = \",\".join(itertools.chain(*li))\n</code></pre>\n"
},
{
"answer_id": 103887,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 1,
"selected": false,
"text": "<p>For the second one, there is a built-in string method to do that :</p>\n\n<pre><code>>>> print ','.join(str(x) for x in li2)\n\"0,1,2,3,4,5,6,7,8\"\n</code></pre>\n\n<p>For the first one, you can use join within a comprehension list :</p>\n\n<pre><code>>>> print \",\".join([\",\".join(str(x) for x in li])\n\"0,1,2,3,4,5,6,7,8\"\n</code></pre>\n\n<p>But it's easier to use itertools.flatten :</p>\n\n<pre><code>>>> import itertools\n>>> print itertools.flatten(li)\n[0,1,2,3,4,5,6,7,8]\n>>> print \",\".join(str(x) for x in itertools.flatten(li))\n\"0,1,2,3,4,5,6,7,8\"\n</code></pre>\n\n<p>N.B : itertools is a module that help you to deal with common tasks with iterators such as list, tuples or string... It's handy because it does not store a copy of the structure you're working on but process the items one by one.</p>\n\n<p>EDIT : funny, I am learning plenty of way to do it. Who said that there was only one good way to do it ?</p>\n"
},
{
"answer_id": 103890,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 3,
"selected": false,
"text": "<p>My favorite, and the shortest one, is this:</p>\n\n<pre><code>li2 = sum(li, [])\n</code></pre>\n\n<p>and</p>\n\n<pre><code>s = ','.join(li2)\n</code></pre>\n\n<p>EDIT: use <code>sum</code> instead of <code>reduce</code>, (thanks <a href=\"https://stackoverflow.com/users/17624/thomas-wouters\">Thomas Wouters</a>!)</p>\n"
},
{
"answer_id": 103895,
"author": "Thomas Wouters",
"author_id": 17624,
"author_profile": "https://Stackoverflow.com/users/17624",
"pm_score": 6,
"selected": true,
"text": "<p>Like so:</p>\n\n<pre><code>[ item for innerlist in outerlist for item in innerlist ]\n</code></pre>\n\n<p>Turning that directly into a string with separators:</p>\n\n<pre><code>','.join(str(item) for innerlist in outerlist for item in innerlist)\n</code></pre>\n\n<p>Yes, the order of 'for innerlist in outerlist' and 'for item in innerlist' is correct. Even though the \"body\" of the loop is at the start of the listcomp, the order of nested loops (and 'if' clauses) is still the same as when you would write the loop out:</p>\n\n<pre><code>for innerlist in outerlist:\n for item in innerlist:\n ...\n</code></pre>\n"
},
{
"answer_id": 103908,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": 3,
"selected": false,
"text": "<p>Try that:</p>\n\n<pre><code>li=[[0,1,2],[3,4,5],[6,7,8]]\nli2 = [ y for x in li for y in x]\n</code></pre>\n\n<p>You can read it like this:<br>\nGive me the list of every ys.<br>\nThe ys come from the xs.<br>\nThe xs come from li.</p>\n\n<p>To map that in a string:</p>\n\n<pre><code>','.join(map(str,li2))\n</code></pre>\n"
},
{
"answer_id": 244477,
"author": "Alex",
"author_id": 30181,
"author_profile": "https://Stackoverflow.com/users/30181",
"pm_score": 0,
"selected": false,
"text": "<p>There are many ways to do this problem. I like <a href=\"http://numpy.scipy.org/\" rel=\"nofollow noreferrer\">Numpy</a>'s tools because it is normally already imported in everything I do. However, if you aren't using Numpy for anything else this probably isn't a good method.</p>\n\n<pre><code>import numpy\nli = [[0,1,2],[3,4,5],[6,7,8]]\nli2=li[0] #first element of array to merge\ni=1 \nwhile i<len(li):\n li2=numpy.concatenate((li2,li[i]))\n i+=1\nprint li2\n</code></pre>\n\n<p>This would print [0 1 2 3 4 5 6 7 8] and then you can convert this into your string too.</p>\n"
},
{
"answer_id": 65776145,
"author": "Franco",
"author_id": 13435688,
"author_profile": "https://Stackoverflow.com/users/13435688",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a way:</p>\n<pre><code>def convert2DArrtostring(ndArr):\n '''converts 2D array to string'''\n arr_str = "["\n for i in ndArr:\n arr_str += "["\n for j in i:\n arr_str += str(j) + " "\n arr_str += "]\\n"\n arr_str += "]"\n return arr_str\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/577/"
]
| List Comprehension for me seems to be like the opaque block of granite that regular expressions are for me. I need pointers.
Say, I have a 2D list:
```
li = [[0,1,2],[3,4,5],[6,7,8]]
```
I would like to merge this either into one long list
```
li2 = [0,1,2,3,4,5,6,7,8]
```
or into a string with separators:
```
s = "0,1,2,3,4,5,6,7,8"
```
Really, I'd like to know how to do both. | Like so:
```
[ item for innerlist in outerlist for item in innerlist ]
```
Turning that directly into a string with separators:
```
','.join(str(item) for innerlist in outerlist for item in innerlist)
```
Yes, the order of 'for innerlist in outerlist' and 'for item in innerlist' is correct. Even though the "body" of the loop is at the start of the listcomp, the order of nested loops (and 'if' clauses) is still the same as when you would write the loop out:
```
for innerlist in outerlist:
for item in innerlist:
...
``` |
103,918 | <p>I am trying to install the ibm_db gem so that I can access DB2 from Ruby. When I try:</p>
<pre><code>sudo gem install ibm_db
</code></pre>
<p>I get the following request for clarification:</p>
<pre>
Select which gem to install for your platform (i486-linux)
1. ibm_db 0.10.0 (ruby)
2. ibm_db 0.10.0 (mswin32)
3. ibm_db 0.9.5 (mswin32)
4. ibm_db 0.9.5 (ruby)
5. Skip this gem
6. Cancel installation
</pre>
<p>I am always going to be installing the linux version (which I assume is the "ruby" version), so is there a way to pick which one I will install straight from the gem install command?</p>
<p>The reason this is a problem is that I need to automate this install via a bash script, so I would like to select that I want the "ruby" version ahead of time.</p>
| [
{
"answer_id": 104102,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>sudo gem install --platform ruby ibm_db\n</code></pre>\n\n<p>Note that you can get help on the install command using:</p>\n\n<pre><code>gem help install\n</code></pre>\n\n<hr>\n\n<p><strong>UPDATE:</strong> Looks like this option only works for RubyGems 0.9.5 or above.</p>\n"
},
{
"answer_id": 104140,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "<p>@<a href=\"https://stackoverflow.com/questions/103918/automate-a-ruby-gem-install-that-has-input#104102\">John Topley</a></p>\n\n<p>I already tried gem help install, and --platform is not an option, both in help and in practice:</p>\n\n<pre>\n$ sudo gem install ibm_db --platform ruby\nERROR: While executing gem ... (OptionParser::InvalidOption)\n invalid option: --platform\n</pre>\n\n<hr>\n\n<p><strong>UPDATE</strong>: The Ubuntu repos have 0.9.4 version of rubygems, which doesn't have the --platform option. It appears it may be <a href=\"http://rubyforge.org/forum/forum.php?forum_id=23112\" rel=\"nofollow noreferrer\">a new feature in 0.9.5</a>, but there is still no online documentation for it, and regardless, it won't work on Ubuntu which is the platform I need it to work on.</p>\n"
},
{
"answer_id": 104163,
"author": "paradoja",
"author_id": 18396,
"author_profile": "https://Stackoverflow.com/users/18396",
"pm_score": 3,
"selected": true,
"text": "<p>You can use a 'here document'. That is:</p>\n\n<pre><code>sudo gem install ibm_db <<heredoc\n 1\nheredoc\n</code></pre>\n\n<p>What's between the \\<\\<\\SOMETHING and SOMETHING gets inputted as entry to the previous command (somewhat like ruby's own heredocuments). The 1 there alone, of course, is the selection of the \"ibm_db 0.10.0 (ruby)\" platform.</p>\n\n<p>Hope it's enough.</p>\n"
},
{
"answer_id": 104195,
"author": "Josti",
"author_id": 11231,
"author_profile": "https://Stackoverflow.com/users/11231",
"pm_score": 0,
"selected": false,
"text": "<p>Try this, I think it only works on Bash though</p>\n\n<pre><code>sudo gem install ibm_db < <(echo 1)\n</code></pre>\n"
},
{
"answer_id": 104419,
"author": "Charles Roper",
"author_id": 1944,
"author_profile": "https://Stackoverflow.com/users/1944",
"pm_score": 0,
"selected": false,
"text": "<p>Versions of Rubygems from 1.0 and up automatically detect the platform you are running and thus do not ask that question. Are you able to update your gems to the latest?</p>\n\n<pre><code>$ sudo gem update --system\n</code></pre>\n\n<p>Be warned if you are on Windows once you have updated; you might run into <a href=\"https://stackoverflow.com/questions/43778/sqlite3-ruby-gem-failed-to-build-gem-native-extension\">this issue</a>.</p>\n"
},
{
"answer_id": 104490,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 0,
"selected": false,
"text": "<p>Another option is to download the .gem file and install it manually as such:</p>\n\n<pre><code>sudo gem install path/to/ibm_db-0.10.0.gem\n</code></pre>\n\n<p>This particular gem was at <a href=\"http://rubyforge.org/frs/?group_id=2361&release_id=25677\" rel=\"nofollow noreferrer\">rubyforge</a>.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
]
| I am trying to install the ibm\_db gem so that I can access DB2 from Ruby. When I try:
```
sudo gem install ibm_db
```
I get the following request for clarification:
```
Select which gem to install for your platform (i486-linux)
1. ibm_db 0.10.0 (ruby)
2. ibm_db 0.10.0 (mswin32)
3. ibm_db 0.9.5 (mswin32)
4. ibm_db 0.9.5 (ruby)
5. Skip this gem
6. Cancel installation
```
I am always going to be installing the linux version (which I assume is the "ruby" version), so is there a way to pick which one I will install straight from the gem install command?
The reason this is a problem is that I need to automate this install via a bash script, so I would like to select that I want the "ruby" version ahead of time. | You can use a 'here document'. That is:
```
sudo gem install ibm_db <<heredoc
1
heredoc
```
What's between the \<\<\SOMETHING and SOMETHING gets inputted as entry to the previous command (somewhat like ruby's own heredocuments). The 1 there alone, of course, is the selection of the "ibm\_db 0.10.0 (ruby)" platform.
Hope it's enough. |
103,919 | <p>I want to store the current URL in a session variable to reference the previous visited page.</p>
<p>If I store every URL (via a before_filter on ApplicationController), also actions which end in a redirect (create, update, etc) are considered as last visited page.</p>
<p>Is there a way to tell Rails only to execute a function if a template is rendered??</p>
<p><strong>Update</strong></p>
<p>Thanks for the after_filter tip... having written so many before_filters I didn't see the obvious. But the Trick with @performed_redirect doesn't work-</p>
<p>This is what I got so far</p>
<pre><code>class ApplicationController < ActionController::Base
after_filter :set_page_as_previous_page
def set_page_as_previous_page
unless @performed_redirect
flash[:previous_page] = request.request_uri
else
flash[:previous_page] = flash[:previous_page]
end
end
end
</code></pre>
<p>I need to implement a "Go Back" Link, without the use of Javascript, the HTTP Referer. Sorry If I should have mentioned that, I appreciate your help!</p>
<p><strong>Update 2</strong></p>
<p>I found a solution, which is not very elegant and only works if your app follows the standard naming scheme</p>
<pre><code>def after_filter
if File.exists?(File.join(Rails.root,"app","views", controller_path, action_name+".html.erb"))
flash[:previous_page] = request.request_uri
else
flash[:previous_page] = flash[:previous_page]
end
end
</code></pre>
| [
{
"answer_id": 103954,
"author": "William Yeung",
"author_id": 16371,
"author_profile": "https://Stackoverflow.com/users/16371",
"pm_score": 0,
"selected": false,
"text": "<p>Can be a bit more specific? I cant get your question- by template you means render :view, the layout? or only when called with render :template?</p>\n\n<p>Rendering a page? render :action=>:new is a page too... Can you be a bit more specific on which you want to capture and which you want to exclude?</p>\n\n<p>Saw the accepted answer :) </p>\n"
},
{
"answer_id": 103975,
"author": "kch",
"author_id": 13989,
"author_profile": "https://Stackoverflow.com/users/13989",
"pm_score": 0,
"selected": false,
"text": "<p>The controller will have these variables, which might be helpful:</p>\n\n<pre><code>@performed_render\n@performed_redirect\n</code></pre>\n\n<p>But anyway, how exactly are you storing the url? Show us the filter code. Why not using an <code>after_filter</code>?</p>\n"
},
{
"answer_id": 104460,
"author": "kch",
"author_id": 13989,
"author_profile": "https://Stackoverflow.com/users/13989",
"pm_score": 3,
"selected": true,
"text": "<p>Not sure why <code>@performed_redirect</code> isn't working, you can see that it does exist and have the desired values by calling the actions on this test controller:</p>\n\n<pre><code>class RedirController < ApplicationController\n after_filter :redir_raise\n\n def raise_true\n redirect_to :action => :whatever\n end\n\n def raise_false\n render :text => 'foo'\n end\n\n private\n\n def redir_raise\n raise @performed_redirect.to_s\n end\n\nend\n</code></pre>\n\n<p>As an aside, instead of doing</p>\n\n<pre><code>flash[:previous_page] = flash[:previous_page]\n</code></pre>\n\n<p>you can do</p>\n\n<pre><code>flash.keep :previous_page\n</code></pre>\n\n<p>(My patch, that. back in the days :P)</p>\n"
},
{
"answer_id": 803093,
"author": "Travis",
"author_id": 524373,
"author_profile": "https://Stackoverflow.com/users/524373",
"pm_score": 1,
"selected": false,
"text": "<p>Another possible approach to determine whether the response is a redirect vs. render is to check the status code:</p>\n\n<pre><code>class ApplicationController < ActionController::Base\n\n after_filter :set_page_as_previous_page\n\n def set_page_as_previous_page\n unless 302 == request.status #redirecting\n flash[:previous_page] = request.request_uri\n else\n flash[:previous_page] = flash[:previous_page]\n end\n end\n\nend\n</code></pre>\n\n<p>It really seems like there should be a redirect? method in ActionController::Base for this.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11231/"
]
| I want to store the current URL in a session variable to reference the previous visited page.
If I store every URL (via a before\_filter on ApplicationController), also actions which end in a redirect (create, update, etc) are considered as last visited page.
Is there a way to tell Rails only to execute a function if a template is rendered??
**Update**
Thanks for the after\_filter tip... having written so many before\_filters I didn't see the obvious. But the Trick with @performed\_redirect doesn't work-
This is what I got so far
```
class ApplicationController < ActionController::Base
after_filter :set_page_as_previous_page
def set_page_as_previous_page
unless @performed_redirect
flash[:previous_page] = request.request_uri
else
flash[:previous_page] = flash[:previous_page]
end
end
end
```
I need to implement a "Go Back" Link, without the use of Javascript, the HTTP Referer. Sorry If I should have mentioned that, I appreciate your help!
**Update 2**
I found a solution, which is not very elegant and only works if your app follows the standard naming scheme
```
def after_filter
if File.exists?(File.join(Rails.root,"app","views", controller_path, action_name+".html.erb"))
flash[:previous_page] = request.request_uri
else
flash[:previous_page] = flash[:previous_page]
end
end
``` | Not sure why `@performed_redirect` isn't working, you can see that it does exist and have the desired values by calling the actions on this test controller:
```
class RedirController < ApplicationController
after_filter :redir_raise
def raise_true
redirect_to :action => :whatever
end
def raise_false
render :text => 'foo'
end
private
def redir_raise
raise @performed_redirect.to_s
end
end
```
As an aside, instead of doing
```
flash[:previous_page] = flash[:previous_page]
```
you can do
```
flash.keep :previous_page
```
(My patch, that. back in the days :P) |
103,938 | <p>I've been doing code review (mostly using tools like FindBugs) of one of our pet projects and FindBugs marked following code as erroneous (pseudocode):</p>
<pre><code>Connection conn = dataSource.getConnection();
try{
PreparedStatement stmt = conn.prepareStatement();
//initialize the statement
stmt.execute();
ResultSet rs = stmt.getResultSet();
//get data
}finally{
conn.close();
}
</code></pre>
<p>The error was that this code might not release resources. I figured out that the ResultSet and Statement were not closed, so I closed them in finally:</p>
<pre><code>finally{
try{
rs.close()
}catch(SqlException se){
//log it
}
try{
stmt.close();
}catch(SqlException se){
//log it
}
conn.close();
}
</code></pre>
<p>But I encountered the above pattern in many projects (from quite a few companies), and no one was closing ResultSets or Statements.</p>
<p>Did you have troubles with ResultSets and Statements not being closed when the Connection is closed? </p>
<p>I found only <a href="http://www.theserverside.com/discussions/thread.tss?thread_id=41036" rel="noreferrer">this</a> and it refers to Oracle having problems with closing ResultSets when closing Connections (we use Oracle db, hence my corrections). java.sql.api says nothing in Connection.close() javadoc.</p>
| [
{
"answer_id": 103994,
"author": "neu242",
"author_id": 13365,
"author_profile": "https://Stackoverflow.com/users/13365",
"pm_score": 5,
"selected": false,
"text": "<p>I've had problems with unclosed ResultSets in Oracle, even though the connection was closed. The error I got was </p>\n\n<pre><code>\"ORA-01000: maximum open cursors exceeded\"\n</code></pre>\n\n<p>So: Always close your ResultSet!</p>\n"
},
{
"answer_id": 104061,
"author": "John Gardner",
"author_id": 13687,
"author_profile": "https://Stackoverflow.com/users/13687",
"pm_score": 3,
"selected": false,
"text": "<p>Oracle will give you errors about open cursors in this case.</p>\n\n<p>According to: <a href=\"http://java.sun.com/javase/6/docs/api/java/sql/Statement.html\" rel=\"noreferrer\">http://java.sun.com/javase/6/docs/api/java/sql/Statement.html</a></p>\n\n<p>it looks like reusing a statement will close any open resultsets, and closing a statement will close any resultsets, but i don't see anything about closing a connection will close any of the resources it created.</p>\n\n<p>All of those details are left to the JDBC driver provider. </p>\n\n<p>Its always safest to close everything explicitly. We wrote a util class that wraps everything with try{ xxx } catch (Throwable {} so that you can just call Utils.close(rs) and Utils.close(stmt), etc without having to worry about exceptions that close scan supposedly throw.</p>\n"
},
{
"answer_id": 104101,
"author": "JavadocMD",
"author_id": 9304,
"author_profile": "https://Stackoverflow.com/users/9304",
"pm_score": 2,
"selected": false,
"text": "<p>I've definitely seen problems with unclosed ResultSets, and what can it hurt to close them all the time, right? The unreliability of needing to remembering to do this is one of the best reasons to move to frameworks that manage these details for you. It might not be feasible in your development environment, but I've had great luck using Spring to manage JPA transactions. The messy details of opening connections, statements, result sets, and writing over-complicated try/catch/finally blocks (with try/catch blocks <em>in the finally block!</em>) to close them again just disappears, leaving you to actually get some work done. I'd highly recommend migrating to that kind of a solution.</p>\n"
},
{
"answer_id": 104120,
"author": "Spencer Kormos",
"author_id": 8528,
"author_profile": "https://Stackoverflow.com/users/8528",
"pm_score": 2,
"selected": false,
"text": "<p>In Java, Statements (not Resultsets) correlate to Cursors in Oracle. It is best to close the resources that you open as unexpected behavior can occur in regards to the JVM and system resources.</p>\n\n<p>Additionally, some JDBC pooling frameworks pool Statements and Connections, so not closing them might not mark those objects as free in the pool, and cause performance issues in the framework.</p>\n\n<p>In general, if there is a close() or destroy() method on an object, there's a reason to call it, and to ignore it is done so at your own peril.</p>\n"
},
{
"answer_id": 104123,
"author": "Aaron",
"author_id": 19130,
"author_profile": "https://Stackoverflow.com/users/19130",
"pm_score": 7,
"selected": true,
"text": "<p>One problem with ONLY closing the connection and not the result set, is that if your connection management code is using connection pooling, the <code>connection.close()</code> would just put the connection back in the pool. Additionally, some database have a cursor resource on the server that will not be freed properly unless it is explicitly closed.</p>\n"
},
{
"answer_id": 104504,
"author": "Horcrux7",
"author_id": 12631,
"author_profile": "https://Stackoverflow.com/users/12631",
"pm_score": 3,
"selected": false,
"text": "<p>The ODBC Bridge can produce a memory leak with some ODBC drivers.</p>\n\n<p>If you use a good JDBC driver then you should does not have any problems with closing the connection. But there are 2 problems:</p>\n\n<ul>\n<li>Does you know if you have a good driver?</li>\n<li>Will you use other JDBC drivers in the future?</li>\n</ul>\n\n<p>That the best practice is to close it all.</p>\n"
},
{
"answer_id": 104830,
"author": "Stefan Schweizer",
"author_id": 13559,
"author_profile": "https://Stackoverflow.com/users/13559",
"pm_score": 4,
"selected": false,
"text": "<p>You should always close all JDBC resources explicitly. As Aaron and John already said, closing a connection will often only return it to a pool and not all JDBC drivers are implemented exact the same way.</p>\n\n<p>Here is a utility method that can be used from a finally block:</p>\n\n<pre><code>public static void closeEverything(ResultSet rs, Statement stmt,\n Connection con) {\n if (rs != null) {\n try {\n rs.close();\n } catch (SQLException e) {\n }\n }\n if (stmt != null) {\n try {\n stmt.close();\n } catch (SQLException e) {\n }\n }\n if (con != null) {\n try {\n con.close();\n } catch (SQLException e) {\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 105088,
"author": "Konrad",
"author_id": 8143,
"author_profile": "https://Stackoverflow.com/users/8143",
"pm_score": 3,
"selected": false,
"text": "<p>I work in a large J2EE web environment. We have several databases that may be connected to in a single request. We began getting logical deadlocks in some of our applications. The issue was that as follows:</p>\n\n<ol>\n<li>User would request page</li>\n<li>Server connects to DB 1</li>\n<li>Server Selects on DB 1</li>\n<li>Server \"closes\" connection to DB 1</li>\n<li>Server connects to DB 2</li>\n<li>Deadlocked!</li>\n</ol>\n\n<p>This occurred for 2 reasons, we were experiencing far higher volume of traffic than normal and the J2EE Spec by default does not actually close your connection until the thread finishes execution. So, in the above example step 4 never actually closed the connection even though they were closed properly in finally .</p>\n\n<p>To fix this, you you have to use resource references in the web.xml for your Database Connections and you have to set the res-sharing-scope to unsharable. </p>\n\n<p>Example:</p>\n\n<pre><code><resource-ref>\n <description>My Database</description>\n <res-ref-name>jdbc/jndi/pathtodatasource</res-ref-name>\n <res-type>javax.sql.DataSource</res-type>\n <res-auth>Container</res-auth>\n <res-sharing-scope>Unshareable</res-sharing-scope>\n</resource-ref>\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7918/"
]
| I've been doing code review (mostly using tools like FindBugs) of one of our pet projects and FindBugs marked following code as erroneous (pseudocode):
```
Connection conn = dataSource.getConnection();
try{
PreparedStatement stmt = conn.prepareStatement();
//initialize the statement
stmt.execute();
ResultSet rs = stmt.getResultSet();
//get data
}finally{
conn.close();
}
```
The error was that this code might not release resources. I figured out that the ResultSet and Statement were not closed, so I closed them in finally:
```
finally{
try{
rs.close()
}catch(SqlException se){
//log it
}
try{
stmt.close();
}catch(SqlException se){
//log it
}
conn.close();
}
```
But I encountered the above pattern in many projects (from quite a few companies), and no one was closing ResultSets or Statements.
Did you have troubles with ResultSets and Statements not being closed when the Connection is closed?
I found only [this](http://www.theserverside.com/discussions/thread.tss?thread_id=41036) and it refers to Oracle having problems with closing ResultSets when closing Connections (we use Oracle db, hence my corrections). java.sql.api says nothing in Connection.close() javadoc. | One problem with ONLY closing the connection and not the result set, is that if your connection management code is using connection pooling, the `connection.close()` would just put the connection back in the pool. Additionally, some database have a cursor resource on the server that will not be freed properly unless it is explicitly closed. |
103,945 | <p>I've implemented a custom item renderer that I'm using with a combobox on a flex project I'm working on. It displays and icon and some text for each item. The only problem is that when the text is long the width of the menu is not being adjusted properly and the text is being truncated when displayed. I've tried tweaking all of the obvious properties to alleviate this problem but have not had any success. Does anyone know how to make the combobox menu width scale appropriately to whatever data it's rendering?</p>
<p>My custom item renderer implementation is:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml"
styleName="plain" horizontalScrollPolicy="off">
<mx:Image source="{data.icon}" />
<mx:Label text="{data.label}" fontSize="11" fontWeight="bold" truncateToFit="false"/>
</mx:HBox>
</code></pre>
<p>And my combobox uses it like so:</p>
<pre><code> <mx:ComboBox id="quicklinksMenu" change="quicklinkHandler(quicklinksMenu.selectedItem.data);" click="event.stopImmediatePropagation();" itemRenderer="renderers.QuickLinkItemRenderer" width="100%"/>
</code></pre>
<p>EDIT:
I should clarify on thing: I can set the dropdownWidth property on the combobox to some arbitrarily large value - this will make everything fit, but it will be too wide. Since the data being displayed in this combobox is generic, I want it to automatically size itself to the largest element in the dataprovider (the flex documentation says it will do this, but I have the feeling my custom item renderer is somehow breaking that behavior)</p>
| [
{
"answer_id": 104165,
"author": "Herms",
"author_id": 1409,
"author_profile": "https://Stackoverflow.com/users/1409",
"pm_score": 1,
"selected": false,
"text": "<p>Just a random thought (no clue if this will help):</p>\n\n<p>Try setting the parent HBox and the Label's widths to 100%. That's generally fixed any problems I've run into that were similar.</p>\n"
},
{
"answer_id": 104314,
"author": "defmeta",
"author_id": 10875,
"author_profile": "https://Stackoverflow.com/users/10875",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried using the <strong>calculatePreferredSizeFromData()</strong> method?</p>\n\n<pre><code>protected override function calculatePreferredSizeFromData(count:int):Object\n</code></pre>\n"
},
{
"answer_id": 155207,
"author": "Aaron H.",
"author_id": 16258,
"author_profile": "https://Stackoverflow.com/users/16258",
"pm_score": 0,
"selected": false,
"text": "<p>This answer is probably too late, but I had a very similar problem with the DataGrid's column widths. </p>\n\n<p>After much noodling, I decided to pre-render my text in a private TextField, get the width of the rendered text from that, and explicitly set the width of the column on all of the appropriate resize type events. A little hack-y but works well enough if you haven't got a lot of changing data.</p>\n"
},
{
"answer_id": 1432078,
"author": "Mario Ruggier",
"author_id": 2185854,
"author_profile": "https://Stackoverflow.com/users/2185854",
"pm_score": 0,
"selected": false,
"text": "<p>You would need to do two things:</p>\n\n<ul>\n<li>for the text, use <code>mx.controls.Text</code> (that supports text wrapping) instead of mx.controls.Label</li>\n<li>set comboBox's <code>dropdownFactory.variableRowHeight=true</code> -- this dropdownFactory is normally a subclass of List, and the itemRenderer you are setting on ComboBox is what will be used to render each item in the list</li>\n</ul>\n\n<p>And, do not explicitly set <code>comboBox.dropdownWidth</code> -- let the default value of <code>comboBox.widt</code>h be used as dropdown width.</p>\n"
},
{
"answer_id": 1688600,
"author": "Ryan Lynch",
"author_id": 194784,
"author_profile": "https://Stackoverflow.com/users/194784",
"pm_score": 0,
"selected": false,
"text": "<p>If you look at the <code>measure</code> method of <code>mx.controls.ComboBase</code>, you'll see that the the comboBox calculates it's <code>measuredMinWidth</code> as a sum of the width of the text and the width of the comboBox button.</p>\n\n<pre><code> // Text fields have 4 pixels of white space added to each side\n // by the player, so fudge this amount.\n // If we don't have any data, measure a single space char for defaults\n if (collection && collection.length > 0)\n {\n var prefSize:Object = calculatePreferredSizeFromData(collection.length);\n\n var bm:EdgeMetrics = borderMetrics;\n\n var textWidth:Number = prefSize.width + bm.left + bm.right + 8;\n var textHeight:Number = prefSize.height + bm.top + bm.bottom \n + UITextField.TEXT_HEIGHT_PADDING;\n\n measuredMinWidth = measuredWidth = textWidth + buttonWidth;\n measuredMinHeight = measuredHeight = Math.max(textHeight, buttonHeight);\n }\n</code></pre>\n\n<p>The <code>calculatePreferredSizeFromData</code> method mentioned by @defmeta (implemented in <code>mx.controls.ComboBox</code>) assumes that the data renderer is just a text field, and uses <code>flash.text.lineMetrics</code> to calculate the text width from label field in the <code>data</code> object. If you want to add an additional visual element to the item renderer and have the <code>ComboBox</code> take it's size into account when calculating it's own size, you will have to extend the <code>mx.controls.ComboBox</code> class and override the <code>calculatePreferredSizeFromData</code> method like so:</p>\n\n<pre><code> override protected function calculatePreferredSizeFromData(count:int):Object\n {\n var prefSize:Object = super.calculatePrefferedSizeFromData(count);\n var maxW:Number = 0;\n var maxH:Number = 0;\n var bookmark:CursorBookmark = iterator ? iterator.bookmark : null;\n var more:Boolean = iterator != null;\n\n for ( var i:int = 0 ; i < count ; i++)\n {\n var data:Object;\n if (more) data = iterator ? iterator.current : null;\n else data = null;\n if(data)\n {\n var imgH:Number;\n var imgW:Number;\n\n //calculate the image height and width using the data object here\n\n maxH = Math.max(maxH, prefSize.height + imgH);\n maxW = Math.max(maxW, prefSize.width + imgW);\n }\n if(iterator) iterator.moveNext();\n }\n\n if(iterator) iterator.seek(bookmark, 0);\n return {width: maxW, height: maxH};\n }\n</code></pre>\n\n<p>If possible store the image dimensions in the data object and use those values as <code>imgH</code> and <code>imgW</code>, that will make sizing much easier.</p>\n\n<p>EDIT: </p>\n\n<p>If you are adding elements to the render besides an image, like a label, you will also have to calculate their size as well when you iterate through the data elements and take those dimensions into account when calculating <code>maxH</code> and <code>maxW</code>.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2327/"
]
| I've implemented a custom item renderer that I'm using with a combobox on a flex project I'm working on. It displays and icon and some text for each item. The only problem is that when the text is long the width of the menu is not being adjusted properly and the text is being truncated when displayed. I've tried tweaking all of the obvious properties to alleviate this problem but have not had any success. Does anyone know how to make the combobox menu width scale appropriately to whatever data it's rendering?
My custom item renderer implementation is:
```
<?xml version="1.0" encoding="utf-8"?>
<mx:HBox xmlns:mx="http://www.adobe.com/2006/mxml"
styleName="plain" horizontalScrollPolicy="off">
<mx:Image source="{data.icon}" />
<mx:Label text="{data.label}" fontSize="11" fontWeight="bold" truncateToFit="false"/>
</mx:HBox>
```
And my combobox uses it like so:
```
<mx:ComboBox id="quicklinksMenu" change="quicklinkHandler(quicklinksMenu.selectedItem.data);" click="event.stopImmediatePropagation();" itemRenderer="renderers.QuickLinkItemRenderer" width="100%"/>
```
EDIT:
I should clarify on thing: I can set the dropdownWidth property on the combobox to some arbitrarily large value - this will make everything fit, but it will be too wide. Since the data being displayed in this combobox is generic, I want it to automatically size itself to the largest element in the dataprovider (the flex documentation says it will do this, but I have the feeling my custom item renderer is somehow breaking that behavior) | Just a random thought (no clue if this will help):
Try setting the parent HBox and the Label's widths to 100%. That's generally fixed any problems I've run into that were similar. |
103,976 | <p>How can you programmatically set the parameters for a subreport? For the top-level report, you can do the following:</p>
<pre>
reportViewer.LocalReport.SetParameters
(
new Microsoft.Reporting.WebForms.ReportParameter[]
{
new Microsoft.Reporting.WebForms.ReportParameter("ParameterA", "Test"),
new Microsoft.Reporting.WebForms.ReportParameter("ParameterB", "1/10/2009 10:30 AM"),
new Microsoft.Reporting.WebForms.ReportParameter("ParameterC", "1234")
}
);
</pre>
<p>Passing parameters like the above only seems to pass them to the top-level report, not the subreports.</p>
<p>The LocalReport allows you to handle the SubreportProcessing event. That passes you an instance of SubreportProcessingEventArgs, which has a property of Type ReportParameterInfoCollection. The values in this collection are read-only.</p>
| [
{
"answer_id": 108859,
"author": "John Hoven",
"author_id": 1907,
"author_profile": "https://Stackoverflow.com/users/1907",
"pm_score": 1,
"selected": false,
"text": "<p>Add the parameter to the parent report and set the sub report parameter value from the parent report (in the actual report definition). This is what I've read. Let me know if it works for you.</p>\n"
},
{
"answer_id": 2179135,
"author": "abmaheco",
"author_id": 263768,
"author_profile": "https://Stackoverflow.com/users/263768",
"pm_score": -1,
"selected": false,
"text": "<p>set the parameter to <Expression...> and use formula builder to add the parent parameter.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10834/"
]
| How can you programmatically set the parameters for a subreport? For the top-level report, you can do the following:
```
reportViewer.LocalReport.SetParameters
(
new Microsoft.Reporting.WebForms.ReportParameter[]
{
new Microsoft.Reporting.WebForms.ReportParameter("ParameterA", "Test"),
new Microsoft.Reporting.WebForms.ReportParameter("ParameterB", "1/10/2009 10:30 AM"),
new Microsoft.Reporting.WebForms.ReportParameter("ParameterC", "1234")
}
);
```
Passing parameters like the above only seems to pass them to the top-level report, not the subreports.
The LocalReport allows you to handle the SubreportProcessing event. That passes you an instance of SubreportProcessingEventArgs, which has a property of Type ReportParameterInfoCollection. The values in this collection are read-only. | Add the parameter to the parent report and set the sub report parameter value from the parent report (in the actual report definition). This is what I've read. Let me know if it works for you. |
103,980 | <p>I'm working on a document "wizard" for the company that I work for. It's a .dot file with a header consisting of some text and some form fields, and a lot of VBA code. The body of the document is pulled in as an OLE object from a separate .doc file.</p>
<p>Currently, this is being done as a <code>Shape</code>, rather than an <code>InlineShape</code>. I did this because I can absolutely position the Shape, whereas the InlineShape always appears at the beginning of the document.</p>
<p>The problem with this is that a <code>Shape</code> doesn't move when the size of the header changes. If someone needs to add or remove a line from the header due to a special case, they also need to move the object that defines the body. This is a pain, and I'd like to avoid it if possible.</p>
<p>Long story short, how do I position an <code>InlineShape</code> using VBA in Word?</p>
<p>The version I'm using is Word 97.</p>
| [
{
"answer_id": 104116,
"author": "GSerg",
"author_id": 11683,
"author_profile": "https://Stackoverflow.com/users/11683",
"pm_score": 3,
"selected": true,
"text": "<p>InlineShape is treated as a letter. Hence, the same technique.</p>\n\n<pre><code>ThisDocument.Range(15).InlineShapes.AddPicture \"1.gif\"\n</code></pre>\n"
},
{
"answer_id": 128344,
"author": "Branan",
"author_id": 13894,
"author_profile": "https://Stackoverflow.com/users/13894",
"pm_score": -1,
"selected": false,
"text": "<p>My final code ended up using <code>ThisDocument.Paragraphs</code> to get the range I needed. But GSerg pointed me in the right direction of using a <code>Range</code> to get my object where it needed to be.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13894/"
]
| I'm working on a document "wizard" for the company that I work for. It's a .dot file with a header consisting of some text and some form fields, and a lot of VBA code. The body of the document is pulled in as an OLE object from a separate .doc file.
Currently, this is being done as a `Shape`, rather than an `InlineShape`. I did this because I can absolutely position the Shape, whereas the InlineShape always appears at the beginning of the document.
The problem with this is that a `Shape` doesn't move when the size of the header changes. If someone needs to add or remove a line from the header due to a special case, they also need to move the object that defines the body. This is a pain, and I'd like to avoid it if possible.
Long story short, how do I position an `InlineShape` using VBA in Word?
The version I'm using is Word 97. | InlineShape is treated as a letter. Hence, the same technique.
```
ThisDocument.Range(15).InlineShapes.AddPicture "1.gif"
``` |
103,989 | <p>I need to implement an in-memory tuple-of-strings matching feature in C. There will be large list of tuples associated with different actions and a high volume of events to be matched against the list.</p>
<p>List of tuples:</p>
<pre><code>("one", "four")
("one")
("three")
("four", "five")
("six")
</code></pre>
<p>event ("one", "two", "three", "four") should match list item ("one", "four") and ("one") and ("three") but not ("four", "five") and not ("six")</p>
<p>my current approach uses a map of all tuple field values as keys for lists of each tuple using that value. there is a lot of redundant hashing and list insertion.</p>
<p>is there a right or classic way to do this?</p>
| [
{
"answer_id": 104151,
"author": "freespace",
"author_id": 8297,
"author_profile": "https://Stackoverflow.com/users/8297",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know of any classical or right way to do this, so here is what I would do :P</p>\n\n<p>It looks like you want to decide if A is a superset of B, using set theory jargon. One way you can do it is to sort A and B, and do a merge sort-esque operation on A and B, in that you try to find where in A a value in B goes. Those elements of B which are also in A, will have duplicates, and the other elements won't. Because both A and B are sorted, this shouldn't be too horrible.</p>\n\n<p>For example, you take the first value of B, and walk A until you find its duplicate in A. Then you take the second value of B, and start walking A from where you left off previously. If you get to end of A without finding a match, then A is not a superset of B, and you return false.</p>\n\n<p>If these tuples can stay sorted, then the sorting cost is only incurred once.</p>\n"
},
{
"answer_id": 104182,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 3,
"selected": true,
"text": "<p>If you only have a small number of possible tuple values it would make sense to write some sort of hashing function which could turn them into integer indexes for quick searching.</p>\n\n<p>If there are < 32 values you could do something with bitmasks:</p>\n\n<pre><code>unsigned int hash(char *value){...}\n\ntypedef struct _tuple {\n unsigned int bitvalues;\n void * data\n} tuple;\n\ntuple a,b,c,d;\na.bitvalues = hash(\"one\");\na.bitvalues |= hash(\"four\");\n//a.data = something;\n\nunsigned int event = 0;\n//foreach value in event;\nevent |= hash(string_val);\n\n// foreach tuple\nif(x->bitvalues & test == test)\n{\n //matches\n}\n</code></pre>\n\n<p>If there are too many values to do a bitmask solution you could have an array of linked lists. Go through each item in the event. If the item matches key_one, walk through the tuples with that first key and check the event for the second key:</p>\n\n<pre><code>typedef struct _tuple {\n unsigned int key_one;\n unsigned int key_two;\n _tuple *next;\n void * data;\n} tuple;\n\ntuple a,b,c,d;\na.key_one = hash(\"one\");\na.key_two = hash(\"four\");\n\ntuple * list = malloc(/*big enough for all hash indexes*/\nmemset(/*clear list*/);\n\n//foreach touple item\nif(list[item->key_one])\n put item on the end of the list;\nelse\n list[item->key_one] = item;\n\n\n//foreach event\n //foreach key\n if(item_ptr = list[key])\n while(item_ptr.next)\n if(!item_ptr.key_two || /*item has key_two*/)\n //match\n item_ptr = item_ptr.next;\n</code></pre>\n\n<p>This code is in no way tested and probably has many small errors but you should get the idea. (one error that was corrected was the test condition for tuple match)</p>\n\n<hr>\n\n<p>If event processing speed is of utmost importance it would make sense to iterate through all of your constructed tuples, count the number of occurrences and go through possibly re-ordering the key one/key two of each tuple so the most unique value is listed first. </p>\n"
},
{
"answer_id": 104290,
"author": "Nick Johnson",
"author_id": 12030,
"author_profile": "https://Stackoverflow.com/users/12030",
"pm_score": 0,
"selected": false,
"text": "<p>If you have a smallish number of possible strings, you can assign an index to each and use bitmaps. That way a simple bitwise and will tell you if there's overlap.</p>\n\n<p>If that's not practical, your inverted index setup is probably going to be hard to match for speed, especially if you only have to build it once. (does the list of tuples change at runtime?)</p>\n"
},
{
"answer_id": 104296,
"author": "LeppyR64",
"author_id": 16592,
"author_profile": "https://Stackoverflow.com/users/16592",
"pm_score": 0,
"selected": false,
"text": "<pre><code> public static void Main()\n {\n List<List<string>> tuples = new List<List<string>>();\n\n string [] tuple = {\"one\", \"four\"};\n tuples.Add(new List<string>(tuple));\n\n tuple = new string [] {\"one\"};\n tuples.Add(new List<string>(tuple));\n\n tuple = new string [] {\"three\"};\n tuples.Add(new List<string>(tuple));\n\n tuple = new string[]{\"four\", \"five\"};\n tuples.Add(new List<string>(tuple));\n\n tuple = new string[]{\"six\"};\n tuples.Add(new List<string>(tuple));\n\n tuple = new string[] {\"one\", \"two\", \"three\", \"four\"};\n\n List<string> checkTuple = new List<string>(tuple);\n\n List<List<string>> result = new List<List<string>>();\n\n foreach (List<string> ls in tuples)\n {\n bool ok = true;\n foreach(string s in ls)\n if(!checkTuple.Contains(s))\n {\n ok = false;\n break;\n }\n if (ok)\n result.Add(ls);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 111442,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 2,
"selected": false,
"text": "<p>A possible solution would be to assign a unique prime number to each of the words.</p>\n\n<p>Then if you multiply the words together in each tuple, then you have a number that represents the words in the list. </p>\n\n<p>Divide one list by another, and if you get an integer remainder, then the one list is contained in the other.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/103989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7223/"
]
| I need to implement an in-memory tuple-of-strings matching feature in C. There will be large list of tuples associated with different actions and a high volume of events to be matched against the list.
List of tuples:
```
("one", "four")
("one")
("three")
("four", "five")
("six")
```
event ("one", "two", "three", "four") should match list item ("one", "four") and ("one") and ("three") but not ("four", "five") and not ("six")
my current approach uses a map of all tuple field values as keys for lists of each tuple using that value. there is a lot of redundant hashing and list insertion.
is there a right or classic way to do this? | If you only have a small number of possible tuple values it would make sense to write some sort of hashing function which could turn them into integer indexes for quick searching.
If there are < 32 values you could do something with bitmasks:
```
unsigned int hash(char *value){...}
typedef struct _tuple {
unsigned int bitvalues;
void * data
} tuple;
tuple a,b,c,d;
a.bitvalues = hash("one");
a.bitvalues |= hash("four");
//a.data = something;
unsigned int event = 0;
//foreach value in event;
event |= hash(string_val);
// foreach tuple
if(x->bitvalues & test == test)
{
//matches
}
```
If there are too many values to do a bitmask solution you could have an array of linked lists. Go through each item in the event. If the item matches key\_one, walk through the tuples with that first key and check the event for the second key:
```
typedef struct _tuple {
unsigned int key_one;
unsigned int key_two;
_tuple *next;
void * data;
} tuple;
tuple a,b,c,d;
a.key_one = hash("one");
a.key_two = hash("four");
tuple * list = malloc(/*big enough for all hash indexes*/
memset(/*clear list*/);
//foreach touple item
if(list[item->key_one])
put item on the end of the list;
else
list[item->key_one] = item;
//foreach event
//foreach key
if(item_ptr = list[key])
while(item_ptr.next)
if(!item_ptr.key_two || /*item has key_two*/)
//match
item_ptr = item_ptr.next;
```
This code is in no way tested and probably has many small errors but you should get the idea. (one error that was corrected was the test condition for tuple match)
---
If event processing speed is of utmost importance it would make sense to iterate through all of your constructed tuples, count the number of occurrences and go through possibly re-ordering the key one/key two of each tuple so the most unique value is listed first. |
104,022 | <p>I'm currently using <code>.resx</code> files to manage my server side resources for .NET.</p>
<p>the application that I am dealing with also allows developers to plugin JavaScript into various event handlers for client side validation, etc.. What is the best way for me to localize my JavaScript messages and strings? </p>
<p>Ideally, I would like to store the strings in the <code>.resx</code> files to keep them with the rest of the localized resources.</p>
<p>I'm open to suggestions.</p>
| [
{
"answer_id": 104051,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 2,
"selected": false,
"text": "<p>I would use an object/array notation:</p>\n\n<pre><code>var phrases={};\nphrases['fatalError'] ='On no!';\n</code></pre>\n\n<p>Then you can just swap the JS file, or use an Ajax call to redefine your phrase list.</p>\n"
},
{
"answer_id": 104075,
"author": "Lasar",
"author_id": 9438,
"author_profile": "https://Stackoverflow.com/users/9438",
"pm_score": 0,
"selected": false,
"text": "<p>Expanding on diodeus.myopenid.com's answer: Have your code write out a file containing a JS array with all the required strings, then load the appropriate file/script before the other JS code. </p>\n"
},
{
"answer_id": 104080,
"author": "Joel Anair",
"author_id": 7441,
"author_profile": "https://Stackoverflow.com/users/7441",
"pm_score": 5,
"selected": false,
"text": "<p>A basic JavaScript object is an associative array, so it can easily be used to store key/value pairs. So using <a href=\"http://www.json.org\" rel=\"noreferrer\">JSON</a>, you could create an object for each string to be localized like this:</p>\n\n<pre><code>var localizedStrings={\n confirmMessage:{\n 'en/US':'Are you sure?',\n 'fr/FR':'Est-ce que vous êtes certain?',\n ...\n },\n\n ...\n}\n</code></pre>\n\n<p>Then you could get the locale version of each string like this:</p>\n\n<pre><code>var locale='en/US';\nvar confirm=localizedStrings['confirmMessage'][locale];\n</code></pre>\n"
},
{
"answer_id": 104157,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Inspired by <a href=\"http://www.sproutcore.com/\" rel=\"noreferrer\">SproutCore</a> You can set properties of\nstrings:</p>\n\n<pre><code>'Hello'.fr = 'Bonjour';\n'Hello'.es = 'Hola';\n</code></pre>\n\n<p>and then simply spit out the proper localization based on your locale:</p>\n\n<pre><code>var locale = 'en';\nalert( message[locale] );\n</code></pre>\n"
},
{
"answer_id": 278229,
"author": "Erik Hesselink",
"author_id": 8071,
"author_profile": "https://Stackoverflow.com/users/8071",
"pm_score": 2,
"selected": false,
"text": "<p>With a satellite assembly (instead of a resx file) you can enumerate all strings on the server, where you know the language, thus generating a Javascript object with only the strings for the correct language. </p>\n\n<p>Something like this works for us (VB.NET code):</p>\n\n<pre><code>Dim rm As New ResourceManager([resource name], [your assembly])\nDim rs As ResourceSet = \n rm.GetResourceSet(Thread.CurrentThread.CurrentCulture, True, True)\nFor Each kvp As DictionaryEntry In rs\n [Write out kvp.Key and kvp.Value]\nNext\n</code></pre>\n\n<p>However, we haven't found a way to do this for .resx files yet, sadly.</p>\n"
},
{
"answer_id": 926261,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>JSGettext does an excellent job -- dynamic loading of GNU Gettext .po files using pretty much any language on the backend. Google for \"Dynamic Javascript localization with Gettext and PHP\" to find a walkthrough for JSGettext with PHP (I'd post the link, but this silly site won't let me, sigh...)</p>\n\n<p><strong>Edit</strong>: <a href=\"http://openflights.org/blog/2009/05/29/dynamic-javascript-localization-with-gettext-and-php/\" rel=\"nofollow noreferrer\">this</a> should be the link</p>\n"
},
{
"answer_id": 2489589,
"author": "brunosp86",
"author_id": 100431,
"author_profile": "https://Stackoverflow.com/users/100431",
"pm_score": -1,
"selected": false,
"text": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/bb398935.aspx\" rel=\"nofollow noreferrer\"><code>MSDN</code> way of doing it</a>, basically is:</p>\n\n<blockquote>\n <p>You create a separate script file for each supported language and culture. In each script file, you include an object in JSON format that contains the localized resources values for that language and culture.</p>\n</blockquote>\n\n<p>I can't tell you the best solution for your question, but IMHO this is the worst way of doing it. At least now you know how NOT to do it.</p>\n"
},
{
"answer_id": 7141901,
"author": "Jaime Botero",
"author_id": 330091,
"author_profile": "https://Stackoverflow.com/users/330091",
"pm_score": 2,
"selected": false,
"text": "<p>I did the following to localize JavaScript for a mobile app running HTML5:</p>\n\n<p>1.Created a set of resource files for each language calling them like \"en.js\" for English. Each contained the different strings the app as follows:</p>\n\n<pre><code>\n var localString = {\n appName: \"your app name\",\n message1: \"blah blah\"\n };\n</code></pre>\n\n<p>2.Used Lazyload to load the proper resource file based on the locale language of the app: <a href=\"https://github.com/rgrove/lazyload\" rel=\"nofollow\">https://github.com/rgrove/lazyload</a></p>\n\n<p>3.Pass the language code via a Query String (As I am launching the html file from Android using PhoneGap)</p>\n\n<p>4.Then I wrote the following code to load dynamically the proper resource file:</p>\n\n<pre><code>\nvar lang = getQueryString(\"language\");\nlocalization(lang);\nfunction localization(languageCode) {\n try {\n var defaultLang = \"en\";\n var resourcesFolder = \"values/\";\n if(!languageCode || languageCode.length == 0)\n languageCode = defaultLang;\n // var LOCALIZATION = null;\n LazyLoad.js(resourcesFolder + languageCode + \".js\", function() {\n if( typeof LOCALIZATION == 'undefined') {\n LazyLoad.js(resourcesFolder + defaultLang + \".js\", function() {\n for(var propertyName in LOCALIZATION) {\n $(\"#\" + propertyName).html(LOCALIZATION[propertyName]);\n }\n });\n } else {\n for(var propertyName in LOCALIZATION) {\n $(\"#\" + propertyName).html(LOCALIZATION[propertyName]);\n }\n }\n });\n } catch (e) {\n errorEvent(e);\n }\n}\nfunction getQueryString(name)\n{\n name = name.replace(/[\\[]/, \"\\\\\\[\").replace(/[\\]]/, \"\\\\\\]\");\n var regexS = \"[\\\\?&]\" + name + \"=([^&#]*)\";\n var regex = new RegExp(regexS);\n var results = regex.exec(window.location.href);\n if(results == null)\n return \"\";\n else\n return decodeURIComponent(results[1].replace(/\\+/g, \" \"));\n}\n</code></pre>\n\n<p>5.From the html file I refer to the strings as follows:</p>\n\n<pre><code>\n span id=\"appName\"\n</code></pre>\n"
},
{
"answer_id": 13392851,
"author": "Amir E. Aharoni",
"author_id": 1387230,
"author_profile": "https://Stackoverflow.com/users/1387230",
"pm_score": 2,
"selected": false,
"text": "<p>There's a library for localizing JavaScript applications:\n<a href=\"https://github.com/wikimedia/jquery.i18n\" rel=\"nofollow\">https://github.com/wikimedia/jquery.i18n</a></p>\n\n<p>It can do parameter replacement, supports gender (clever he/she handling), number (clever plural handling, including languages that have more than one plural form), and custom grammar rules that some languages need.</p>\n\n<p>The strings are stored in JSON files.</p>\n\n<p>The only requirement is jQuery.</p>\n"
},
{
"answer_id": 14782225,
"author": "Leniel Maccaferri",
"author_id": 114029,
"author_profile": "https://Stackoverflow.com/users/114029",
"pm_score": 4,
"selected": false,
"text": "<p>After Googling a lot and not satisfied with the majority of solutions presented, I have just found an amazing/generic solution that uses <a href=\"http://www.leniel.net/2011/06/c-code-with-preprocessed-t4-templates.html\" rel=\"noreferrer\">T4 templates</a>. The complete post by <a href=\"http://www.blogger.com/profile/01681886305363941109\" rel=\"noreferrer\">Jochen van Wylick</a> you can read here:</p>\n\n<p><a href=\"http://jiffie.blogspot.com.br/2012/11/localized-javascript-resources-based-on.html\" rel=\"noreferrer\">Using T4 for localizing JavaScript resources based on .resx files</a></p>\n\n<p>Main advantages are:</p>\n\n<ol>\n<li>Having only 1 place where resources are managed ( namely the .resx\nfiles )</li>\n<li>Support for multiple cultures</li>\n<li>Leverage IntelliSense - allow for code completion</li>\n</ol>\n\n<p>Disadvantages:</p>\n\n<blockquote>\n <p>The shortcomings of this solution are of course that the size of the\n .js file might become quite large. However, since it's cached by the\n browser, we don't consider this a problem for our application. However\n - this caching can also result in the browser not finding the resource called from code.</p>\n</blockquote>\n\n<hr>\n\n<p><strong>How this works?</strong></p>\n\n<p>Basically he defined a T4 template that points to your .resx files. With some C# code he traverses each and every resource string and add it to JavaScript pure key value properties that then are output in a single JavaScript file called <code>Resources.js</code> (you can tweak the names if you wish).</p>\n\n<hr>\n\n<p><strong>T4 template</strong> [ change accordingly to point to your .resx files location ]</p>\n\n<pre><code><#@ template language=\"C#\" debug=\"false\" hostspecific=\"true\"#>\n<#@ assembly name=\"System.Windows.Forms\" #>\n<#@ import namespace=\"System.Resources\" #>\n<#@ import namespace=\"System.Collections\" #>\n<#@ import namespace=\"System.IO\" #>\n<#@ output extension=\".js\"#>\n<#\n var path = Path.GetDirectoryName(Host.TemplateFile) + \"/../App_GlobalResources/\";\n var resourceNames = new string[1]\n {\n \"Common\"\n };\n\n#>\n/**\n* Resources\n* ---------\n* This file is auto-generated by a tool\n* 2012 Jochen van Wylick\n**/\nvar Resources = {\n <# foreach (var name in resourceNames) { #>\n <#=name #>: {},\n <# } #>\n};\n<# foreach (var name in resourceNames) {\n var nlFile = Host.ResolvePath(path + name + \".nl.resx\" );\n var enFile = Host.ResolvePath(path + name + \".resx\" );\n ResXResourceSet nlResxSet = new ResXResourceSet(nlFile);\n ResXResourceSet enResxSet = new ResXResourceSet(enFile);\n#>\n\n<# foreach (DictionaryEntry item in nlResxSet) { #>\nResources.<#=name#>.<#=item.Key.ToString()#> = {\n 'nl-NL': '<#= (\"\" + item.Value).Replace(\"\\r\\n\", string.Empty).Replace(\"'\",\"\\\\'\")#>',\n 'en-GB': '<#= (\"\" + enResxSet.GetString(item.Key.ToString())).Replace(\"\\r\\n\", string.Empty).Replace(\"'\",\"\\\\'\")#>'\n };\n<# } #>\n<# } #>\n</code></pre>\n\n<p><strong>In the Form/View side</strong></p>\n\n<p>To have the correct translation picked up, add this in your master if you're using WebForms:</p>\n\n<pre><code><script type=\"text/javascript\">\n\n var locale = '<%= System.Threading.Thread.CurrentThread.CurrentCulture.Name %>';\n\n</script>\n\n<script type=\"text/javascript\" src=\"/Scripts/Resources.js\"></script>\n</code></pre>\n\n<p>If you're using ASP.NET MVC (like me), you can do this:</p>\n\n<pre><code><script type=\"text/javascript\">\n\n // Setting Locale that will be used by JavaScript translations\n var locale = $(\"meta[name='accept-language']\").attr(\"content\");\n\n</script>\n\n<script type=\"text/javascript\" src=\"/Scripts/Resources.js\"></script>\n</code></pre>\n\n<p>The <code>MetaAcceptLanguage</code> helper I got from this awesome post by Scott Hanselman:</p>\n\n<p><a href=\"http://www.hanselman.com/blog/GlobalizationInternationalizationAndLocalizationInASPNETMVC3JavaScriptAndJQueryPart1.aspx\" rel=\"noreferrer\">Globalization, Internationalization and Localization in ASP.NET MVC 3, JavaScript and jQuery - Part 1</a> </p>\n\n<pre><code>public static IHtmlString MetaAcceptLanguage<T>(this HtmlHelper<T> html)\n{\n var acceptLanguage =\n HttpUtility.HtmlAttributeEncode(\n Thread.CurrentThread.CurrentUICulture.ToString());\n\n return new HtmlString(\n String.Format(\"<meta name=\\\"{0}\\\" content=\\\"{1}\\\">\", \"accept-language\",\n acceptLanguage));\n }\n</code></pre>\n\n<p><strong>Use it</strong></p>\n\n<pre><code>var msg = Resources.Common.Greeting[locale];\nalert(msg);\n</code></pre>\n"
},
{
"answer_id": 24460976,
"author": "hhh575",
"author_id": 2923866,
"author_profile": "https://Stackoverflow.com/users/2923866",
"pm_score": -1,
"selected": false,
"text": "<p>We use MVC and have simply created a controller action to return a localized string. We maintain the user's culture in session and set the thread culture before any call to retrieve a language string, AJAX or otherwise. This means we always return a localized string.</p>\n\n<p>I'll admit, it isn't the most efficient method but getting a localised string in javascript is seldom required as most localization is done in our partial views.</p>\n\n<p><strong>Global.asax.cs</strong></p>\n\n<pre><code>protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)\n{\n if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)\n {\n // Set the current thread's culture\n var culture = (CultureInfo)Session[\"CultureInfo\"];\n if (culture != null)\n {\n Thread.CurrentThread.CurrentCulture = culture;\n Thread.CurrentThread.CurrentUICulture = culture;\n }\n }\n}\n</code></pre>\n\n<p><strong>Controller Action</strong></p>\n\n<pre><code>public string GetString(string key)\n{\n return Language.ResourceManager.GetString(key);\n}\n</code></pre>\n\n<p><strong>Javascript</strong></p>\n\n<pre><code>/*\n Retrieve a localized language string given a lookup key.\n Example use:\n var str = language.getString('MyString');\n*/\nvar language = new function () {\n this.getString = function (key) {\n var retVal = '';\n $.ajax({\n url: rootUrl + 'Language/GetString?key=' + key,\n async: false,\n success: function (results) {\n retVal = results;\n }\n });\n return retVal;\n }\n};\n</code></pre>\n"
},
{
"answer_id": 26422551,
"author": "Morcilla de Arroz",
"author_id": 1410097,
"author_profile": "https://Stackoverflow.com/users/1410097",
"pm_score": 2,
"selected": false,
"text": "<p>Well, I think that you can consider this. English-Spanish example:</p>\n\n<p>Write 2 Js Scripts, like that:</p>\n\n<pre><code>en-GB.js\nlang = {\n date_message: 'The start date is incorrect',\n ...\n};\nes-ES.js\nlang = {\n date_message: 'Fecha de inicio incorrecta',\n ...\n};\n</code></pre>\n\n<p>Server side - code behind: </p>\n\n<pre><code>Protected Overrides Sub InitializeCulture()\n Dim sLang As String \n sLang = \"es-ES\" \n\n Me.Culture = sLang\n Me.UICulture = sLang\n Page.ClientScript.RegisterClientScriptInclude(sLang & \".js\", \"../Scripts/\" & sLang & \".js\")\n\n MyBase.InitializeCulture()\nEnd Sub\n</code></pre>\n\n<p>Where sLang could be \"en-GB\", you know, depending on current user's selection ...</p>\n\n<p>Javascript calls:</p>\n\n<pre><code>alert (lang.date_message);\n</code></pre>\n\n<p>And it works, very easy, I think.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7215/"
]
| I'm currently using `.resx` files to manage my server side resources for .NET.
the application that I am dealing with also allows developers to plugin JavaScript into various event handlers for client side validation, etc.. What is the best way for me to localize my JavaScript messages and strings?
Ideally, I would like to store the strings in the `.resx` files to keep them with the rest of the localized resources.
I'm open to suggestions. | A basic JavaScript object is an associative array, so it can easily be used to store key/value pairs. So using [JSON](http://www.json.org), you could create an object for each string to be localized like this:
```
var localizedStrings={
confirmMessage:{
'en/US':'Are you sure?',
'fr/FR':'Est-ce que vous êtes certain?',
...
},
...
}
```
Then you could get the locale version of each string like this:
```
var locale='en/US';
var confirm=localizedStrings['confirmMessage'][locale];
``` |
104,055 | <p>I know how to use rpm to list the contents of a package (<code>rpm -qpil package.rpm</code>). However, this requires knowing the location of the .rpm file on the filesystem. A more elegant solution would be to use the package manager, which in my case is YUM. How can YUM be used to achieve this?</p>
| [
{
"answer_id": 104087,
"author": "Thomi",
"author_id": 1304,
"author_profile": "https://Stackoverflow.com/users/1304",
"pm_score": 5,
"selected": false,
"text": "<p>I don't think you can list the contents of a package using yum, but if you have the .rpm file on your local system (as will most likely be the case for all installed packages), you can use the rpm command to list the contents of that package like so:</p>\n\n<pre><code>rpm -qlp /path/to/fileToList.rpm\n</code></pre>\n\n<p>If you don't have the package file (.rpm), but you have the package installed, try this:</p>\n\n<pre><code>rpm -ql packageName\n</code></pre>\n"
},
{
"answer_id": 104093,
"author": "Haabda",
"author_id": 16292,
"author_profile": "https://Stackoverflow.com/users/16292",
"pm_score": 0,
"selected": false,
"text": "<p>Yum doesn't have it's own package type. Yum operates and helps manage RPMs. So, you can use yum to list the available RPMs and then run the rpm -qlp command to see the contents of that package.</p>\n"
},
{
"answer_id": 107520,
"author": "Thomas Vander Stichele",
"author_id": 2900,
"author_profile": "https://Stackoverflow.com/users/2900",
"pm_score": 10,
"selected": true,
"text": "<p>There is a package called <code>yum-utils</code> that builds on YUM and contains a tool called <code>repoquery</code> that can do this.</p>\n\n<pre><code>$ repoquery --help | grep -E \"list\\ files\" \n -l, --list list files in this package/group\n</code></pre>\n\n<p>Combined into one example:</p>\n\n<pre><code>$ repoquery -l time\n/usr/bin/time\n/usr/share/doc/time-1.7\n/usr/share/doc/time-1.7/COPYING\n/usr/share/doc/time-1.7/NEWS\n/usr/share/doc/time-1.7/README\n/usr/share/info/time.info.gz\n</code></pre>\n\n<p>On at least one RH system, with rpm v4.8.0, yum v3.2.29, and repoquery v0.0.11, <code>repoquery -l rpm</code> prints nothing.</p>\n\n<p>If you are having this issue, try adding the <code>--installed</code> flag: <code>repoquery --installed -l rpm</code>.</p>\n\n<hr>\n\n<h2><code>DNF</code> Update:</h2>\n\n<p>To use <code>dnf</code> instead of <code>yum-utils</code>, use the following command:</p>\n\n<pre><code>$ dnf repoquery -l time\n/usr/bin/time\n/usr/share/doc/time-1.7\n/usr/share/doc/time-1.7/COPYING\n/usr/share/doc/time-1.7/NEWS\n/usr/share/doc/time-1.7/README\n/usr/share/info/time.info.gz\n</code></pre>\n"
},
{
"answer_id": 9160761,
"author": "Hüseyin Ozan TOK",
"author_id": 1192370,
"author_profile": "https://Stackoverflow.com/users/1192370",
"pm_score": 6,
"selected": false,
"text": "<pre><code>$ yum install -y yum-utils\n\n$ repoquery -l packagename\n</code></pre>\n"
},
{
"answer_id": 26711409,
"author": "Levite",
"author_id": 1680919,
"author_profile": "https://Stackoverflow.com/users/1680919",
"pm_score": 7,
"selected": false,
"text": "<pre><code>rpm -ql [packageName]\n</code></pre>\n\n<h2>Example</h2>\n\n<pre><code># rpm -ql php-fpm\n\n/etc/php-fpm.conf\n/etc/php-fpm.d\n/etc/php-fpm.d/www.conf\n/etc/sysconfig/php-fpm\n...\n/run/php-fpm\n/usr/lib/systemd/system/php-fpm.service\n/usr/sbin/php-fpm\n/usr/share/doc/php-fpm-5.6.0\n/usr/share/man/man8/php-fpm.8.gz\n...\n/var/lib/php/sessions\n/var/log/php-fpm\n</code></pre>\n\n<p>No need to install yum-utils, or to know the location of the rpm file.</p>\n"
},
{
"answer_id": 40918680,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>There are several good answers here, so let me provide a terrible one:</p>\n\n<pre><code>: you can type in anything below, doesnt have to match anything\n\nyum whatprovides \"me with a life\"\n\n: result of the above (some liberties taken with spacing):\n\nLoaded plugins: fastestmirror\nbase | 3.6 kB 00:00 \nextras | 3.4 kB 00:00 \nupdates | 3.4 kB 00:00 \n(1/4): extras/7/x86_64/primary_db | 166 kB 00:00 \n(2/4): base/7/x86_64/group_gz | 155 kB 00:00 \n(3/4): updates/7/x86_64/primary_db | 9.1 MB 00:04 \n(4/4): base/7/x86_64/primary_db | 5.3 MB 00:05 \nDetermining fastest mirrors\n * base: mirrors.xmission.com\n * extras: mirrors.xmission.com\n * updates: mirrors.xmission.com\nbase/7/x86_64/filelists_db | 6.2 MB 00:02 \nextras/7/x86_64/filelists_db | 468 kB 00:00 \nupdates/7/x86_64/filelists_db | 5.3 MB 00:01 \nNo matches found\n\n: the key result above is that \"primary_db\" files were downloaded\n\n: filelists are downloaded EVEN IF you have keepcache=0 in your yum.conf\n\n: note you can limit this to \"primary_db.sqlite\" if you really want\n\nfind /var/cache/yum -name '*.sqlite'\n\n: if you download/install a new repo, run the exact same command again\n: to get the databases for the new repo\n\n: if you know sqlite you can stop reading here\n\n: if not heres a sample command to dump the contents\n\necho 'SELECT packages.name, GROUP_CONCAT(files.name, \", \") AS files FROM files JOIN packages ON (files.pkgKey = packages.pkgKey) GROUP BY packages.name LIMIT 10;' | sqlite3 -line /var/cache/yum/x86_64/7/base/gen/primary_db.sqlite \n\n: remove \"LIMIT 10\" above for the whole list\n\n: format chosen for proof-of-concept purposes, probably can be improved a lot</code></pre>\n"
},
{
"answer_id": 51822546,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>currently <code>reopquery</code> is integrated into <code>dnf</code> and <code>yum</code>, so typing:</p>\n\n<pre><code>dnf repoquery -l <pkg-name>\n</code></pre>\n\n<p>will list package contents from a remote repository (even for the packages that are not installed yet)</p>\n\n<p>meaning installing a separate <code>dnf-utils</code> or <code>yum-utils</code> package is no longer required for the functionality as it is now being supported natively.</p>\n\n<hr>\n\n<p>for listing <em>installed</em> or <em>local</em> (<code>*.rpm</code> files) packages' contents there is <code>rpm -ql</code></p>\n\n<p>i don't think it is possible with <code>yum</code> org <code>dnf</code> (not <code>repoquery</code> subcommand)</p>\n\n<p>please correct me if i am wrong</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
]
| I know how to use rpm to list the contents of a package (`rpm -qpil package.rpm`). However, this requires knowing the location of the .rpm file on the filesystem. A more elegant solution would be to use the package manager, which in my case is YUM. How can YUM be used to achieve this? | There is a package called `yum-utils` that builds on YUM and contains a tool called `repoquery` that can do this.
```
$ repoquery --help | grep -E "list\ files"
-l, --list list files in this package/group
```
Combined into one example:
```
$ repoquery -l time
/usr/bin/time
/usr/share/doc/time-1.7
/usr/share/doc/time-1.7/COPYING
/usr/share/doc/time-1.7/NEWS
/usr/share/doc/time-1.7/README
/usr/share/info/time.info.gz
```
On at least one RH system, with rpm v4.8.0, yum v3.2.29, and repoquery v0.0.11, `repoquery -l rpm` prints nothing.
If you are having this issue, try adding the `--installed` flag: `repoquery --installed -l rpm`.
---
`DNF` Update:
-------------
To use `dnf` instead of `yum-utils`, use the following command:
```
$ dnf repoquery -l time
/usr/bin/time
/usr/share/doc/time-1.7
/usr/share/doc/time-1.7/COPYING
/usr/share/doc/time-1.7/NEWS
/usr/share/doc/time-1.7/README
/usr/share/info/time.info.gz
``` |
104,063 | <p>I noticed in another post, someone had done something like:</p>
<pre><code>double d = 3.1415;
int i = Convert.ToInt32(Math.Floor(d));
</code></pre>
<p>Why did they use the convert function, rather than:</p>
<pre><code>double d = 3.1415;
int i = (int)d;
</code></pre>
<p>which has an implicit floor and convert.</p>
<p>Also, more concerning, I noticed in some production code I was reading:</p>
<pre><code>double d = 3.1415;
float f = Convert.ToSingle(d);
</code></pre>
<p>Is that the same as:</p>
<pre><code>float f = (float)d;
</code></pre>
<p>Are all those otherwise implicit conversions just in the Convert class for completeness, or do they serve a purpose? I can understand a need for .ToString(), but not the rest.</p>
| [
{
"answer_id": 104180,
"author": "NotDan",
"author_id": 3291,
"author_profile": "https://Stackoverflow.com/users/3291",
"pm_score": 1,
"selected": false,
"text": "<p>You can use Convert when you have a string that you want to convert to an int </p>\n\n<pre><code>int i = Convert.ToInt32(\"1234\");\n</code></pre>\n\n<p>Convert and casting will both throw an exception if they fail.</p>\n\n<p>i.e, this will still throw an exception, it will not return 0:</p>\n\n<pre><code>Convert.ToInt32(\"1234NonNumber\");\n</code></pre>\n\n<p>In many cases Convert and casting will have the same result, but a cast is often times easier to read.</p>\n"
},
{
"answer_id": 104387,
"author": "Michael L Perry",
"author_id": 7668,
"author_profile": "https://Stackoverflow.com/users/7668",
"pm_score": 5,
"selected": true,
"text": "<p>Casting to int is implicit truncation, not implicit flooring:</p>\n\n<pre><code>double d = -3.14;\nint i = (int)d;\n// i == -3\n</code></pre>\n\n<p>I choose Math.Floor or Math.Round to make my intentions more explicit.</p>\n"
},
{
"answer_id": 106815,
"author": "ddc0660",
"author_id": 16027,
"author_profile": "https://Stackoverflow.com/users/16027",
"pm_score": 1,
"selected": false,
"text": "<p>Convert.ToInt32() is used on strings (<a href=\"http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx</a>) while casting can only be used on types that have internal converters (numeric types). The real trick comes in deciding between Int32.Parse and Convert.ToInt32(). Convert.ToInt32() is tolerant of a null parameter and returns 0 while Int32.Parse() will throw an ArgumentNullException.</p>\n"
},
{
"answer_id": 246895,
"author": "Mark T",
"author_id": 10722,
"author_profile": "https://Stackoverflow.com/users/10722",
"pm_score": 2,
"selected": false,
"text": "<p>Rounding is also handled differently:<br></p>\n\n<p>x=-2.5 (int)x=-2 Convert.ToInt32(x)=-2<br>\nx=-1.5 (int)x=-1 Convert.ToInt32(x)=-2<br>\nx=-0.5 (int)x= 0 Convert.ToInt32(x)= 0<br>\nx= 0.5 (int)x= 0 Convert.ToInt32(x)= 0<br>\nx= 1.5 (int)x= 1 Convert.ToInt32(x)= 2<br>\nx= 2.5 (int)x= 2 Convert.ToInt32(x)= 2<br></p>\n\n<p>Notice the x=-1.5 and x=1.5 cases.<br>\nIn some algorithms, the rounding method used is critical to getting the right answer.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104063",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15261/"
]
| I noticed in another post, someone had done something like:
```
double d = 3.1415;
int i = Convert.ToInt32(Math.Floor(d));
```
Why did they use the convert function, rather than:
```
double d = 3.1415;
int i = (int)d;
```
which has an implicit floor and convert.
Also, more concerning, I noticed in some production code I was reading:
```
double d = 3.1415;
float f = Convert.ToSingle(d);
```
Is that the same as:
```
float f = (float)d;
```
Are all those otherwise implicit conversions just in the Convert class for completeness, or do they serve a purpose? I can understand a need for .ToString(), but not the rest. | Casting to int is implicit truncation, not implicit flooring:
```
double d = -3.14;
int i = (int)d;
// i == -3
```
I choose Math.Floor or Math.Round to make my intentions more explicit. |
104,066 | <p>I have two insert statements, almost exactly the same, which run in two different schemas on the same Oracle instance. What the insert statement looks like doesn't matter - I'm looking for a troubleshooting strategy here.</p>
<p>Both schemas have 99% the same structure. A few columns have slightly different names, other than that they're the same. The insert statements are almost exactly the same. The explain plan on one gives a cost of 6, the explain plan on the other gives a cost of 7. The tables involved in both sets of insert statements have exactly the same indexes. Statistics have been gathered for both schemas.</p>
<p>One insert statement inserts 12,000 records in 5 seconds.</p>
<p>The other insert statement inserts 25,000 records in 4 minutes 19 seconds.</p>
<p>The number of records being insert is correct. It's the vast disparity in execution times that confuses me. Given that nothing stands out in the explain plan, how would you go about determining what's causing this disparity in runtimes?</p>
<p>(I am using Oracle 10.2.0.4 on a Windows box).</p>
<p><strong>Edit:</strong> The problem ended up being an inefficient query plan, involving a cartesian merge which didn't need to be done. Judicious use of index hints and a hash join hint solved the problem. It now takes 10 seconds. Sql Trace / TKProf gave me the direction, as I it showed me how many seconds each step in the plan took, and how many rows were being generated. Thus TKPROF showed me:-</p>
<pre><code>Rows Row Source Operation
------- ---------------------------------------------------
23690 NESTED LOOPS OUTER (cr=3310466 pr=17 pw=0 time=174881374 us)
23690 NESTED LOOPS (cr=3310464 pr=17 pw=0 time=174478629 us)
2160900 MERGE JOIN CARTESIAN (cr=102 pr=0 pw=0 time=6491451 us)
1470 TABLE ACCESS BY INDEX ROWID TBL1 (cr=57 pr=0 pw=0 time=23978 us)
8820 INDEX RANGE SCAN XIF5TBL1 (cr=16 pr=0 pw=0 time=8859 us)(object id 272041)
2160900 BUFFER SORT (cr=45 pr=0 pw=0 time=4334777 us)
1470 TABLE ACCESS BY INDEX ROWID TBL1 (cr=45 pr=0 pw=0 time=2956 us)
8820 INDEX RANGE SCAN XIF5TBL1 (cr=10 pr=0 pw=0 time=8830 us)(object id 272041)
23690 MAT_VIEW ACCESS BY INDEX ROWID TBL2 (cr=3310362 pr=17 pw=0 time=235116546 us)
96565 INDEX RANGE SCAN XPK_TBL2 (cr=3219374 pr=3 pw=0 time=217869652 us)(object id 272084)
0 TABLE ACCESS BY INDEX ROWID TBL3 (cr=2 pr=0 pw=0 time=293390 us)
0 INDEX RANGE SCAN XIF1TBL3 (cr=2 pr=0 pw=0 time=180345 us)(object id 271983)
</code></pre>
<p>Notice the rows where the operations are MERGE JOIN CARTESIAN and BUFFER SORT. Things that keyed me into looking at this were the number of rows generated (over 2 million!), and the amount of time spent on each operation (compare to other operations).</p>
| [
{
"answer_id": 104103,
"author": "Eddie Awad",
"author_id": 17273,
"author_profile": "https://Stackoverflow.com/users/17273",
"pm_score": 3,
"selected": true,
"text": "<p>Use the <a href=\"http://docs.oracle.com/cd/B19306_01/server.102/b14211/sqltrace.htm#g33356\" rel=\"nofollow noreferrer\">SQL Trace facility and TKPROF</a>.</p>\n"
},
{
"answer_id": 104148,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "<p>The main culprits in insert slow downs are indexes, constraints, and oninsert triggers. Do a test without as many of these as you can remove and see if it's fast. Then introduce them back in and see which one is causing the problem.</p>\n\n<p>I have seen systems where they drop indexes before bulk inserts and rebuild at the end -- and it's faster. </p>\n"
},
{
"answer_id": 104206,
"author": "user11318",
"author_id": 11318,
"author_profile": "https://Stackoverflow.com/users/11318",
"pm_score": 1,
"selected": false,
"text": "<p>The first thing to realize is that, as <a href=\"http://download.oracle.com/docs/cd/A87860_01/doc/server.817/a76965/c20a_opt.htm#16287\" rel=\"nofollow noreferrer\">the documentation says</a>, the cost you see displayed is relative to one of the query plans. The costs for 2 different explains are <strong>not</strong> comparable. Secondly the costs are based on an internal estimate. As hard as Oracle tries, those estimates are not accurate. Particularly not when the optimizer misbehaves. Your situation suggests that there are two query plans which, according to Oracle, are very close in performance. But which, in fact, perform very differently.</p>\n\n<p>The actual information that you want to look at is the actual explain plan itself. That tells you exactly how Oracle executes that query. It has a lot of technical gobbeldy-gook, but what you really care about is knowing that it works from the most indented part out, and at each step it merges according to one of a small number of rules. That will tell you what Oracle is doing differently in your two instances.</p>\n\n<p>What next? Well there are a variety of strategies to tune bad statements. The first option that I would suggest, if you're in Oracle 10g, is to try their <a href=\"http://www.oracle-base.com/articles/10g/AutomaticSQLTuning10g.php\" rel=\"nofollow noreferrer\">SQL tuning advisor</a> to see if a more detailed analysis will tell Oracle the error of its ways. It can then store that plan, and you will use the more efficient plan.</p>\n\n<p>If you can't do that, or if that doesn't work, then you need to get into things like providing query hints, manual stored query outlines, and the like. That is a complex topic. This is where it helps to have a real DBA. If you don't, then you'll want to start reading the <a href=\"http://download-west.oracle.com/docs/cd/B10501_01/server.920/a96533/toc.htm\" rel=\"nofollow noreferrer\">documentation</a>, but be aware that there is a lot to learn. (Oracle also has a SQL tuning class that is, or at least used to be, very good. It isn't cheap though.)</p>\n"
},
{
"answer_id": 104294,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with a previous poster that SQL Trace and tkprof are a good place to start. I also highly recommend the book <a href=\"https://rads.stackoverflow.com/amzn/click/com/059600527X\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Optimizing Oracle Performance</a>, which discusses similar tools for tracing execution and analyzing the output.</p>\n"
},
{
"answer_id": 116209,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 1,
"selected": false,
"text": "<p>I've put up my general list of things to check to improve performance as an answer to another question: </p>\n\n<p><a href=\"https://stackoverflow.com/questions/18783/sql-what-are-your-favorite-performance-tricks#103176\">Favourite performance tuning tricks</a></p>\n\n<p>... It might be helpful as a checklist, even though it's not Oracle-specific. </p>\n"
},
{
"answer_id": 123031,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>SQL Trace and tkprof are only good if you have access to theses tools. Most of the large companies that I do work for do not allow developers to access anything under the Oracle unix IDs. </p>\n\n<p>I believe you should be able to determine the problem by first understanding the question that is being asked and by reading the explain plans for each of the queries. Many times I find that the big difference is that there are some tables and indexes that have not been analyzed.</p>\n"
},
{
"answer_id": 123100,
"author": "thoroughly",
"author_id": 8943,
"author_profile": "https://Stackoverflow.com/users/8943",
"pm_score": 0,
"selected": false,
"text": "<p>Another good reference that presents a general technique for query tuning is the book <a href=\"https://rads.stackoverflow.com/amzn/click/com/0596005733\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">SQL Tuning</a> by Dan Tow. </p>\n"
},
{
"answer_id": 806541,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p><strong><em>analyzing the oI also highly recommend the book Optimizing Oracle Performance, which discusses similar tools for tracing execution and utput.</em></strong></p>\n"
},
{
"answer_id": 20796814,
"author": "Jens Schauder",
"author_id": 66686,
"author_profile": "https://Stackoverflow.com/users/66686",
"pm_score": 0,
"selected": false,
"text": "<p>When the performance of a sql statement isn't as expected / desired, one of the first things I do is to check the execution plan.</p>\n\n<p>The trick is to check for things that aren't as expected. For example you might find table scans where you think an index scan should be faster or vice versa. </p>\n\n<p>A point where the oracle optimizer sometimes takes a wrong turn are the estimates how many rows a step will return. If the execution plan expects 2 rows, but you know it will more like 2000 rows, the execution plan is bound to be less than optimal. </p>\n\n<p>With two statements to compare you can obviously compare the two execution plans to see where they differ.</p>\n\n<p>From this analysis, I come up with an execution plan that I think should be suited better. This is not an exact execution plan, but just some crucial changes, to the one I found, like: It should use Index X or a Hash Join instead of a nested loop. </p>\n\n<p>Next thing is to figure out a way to make Oracle use that execution plan. Often by using Hints, or creating additonal indexes, sometimes changing the SQL statement. Then of course test that the changed statement</p>\n\n<p>a) still does what it is supposed to do</p>\n\n<p>b) is actually faster</p>\n\n<p>With b it is very important to make sure you are testing the correct use case. A typical pit fall is the difference between returning the first row, versus returning the last row. Most tools show you the first results as soon as they are available, with no direct indication, that there is more work to be done. But if your actual program has to process all rows before it continues to the next processing step, it is almost irrelevant when the first row appears, it is only relevant when the last row is available.</p>\n\n<p>If you find a better execution plan, the final step is to make you database actually use it in the actual program. If you added an index, this will often work out of the box. Hints are an option, but can be problematic if a library creates your sql statement, those ofte don't support hints. As a last resort you can save and fix execution plans for specific sql statements. I'd avoid this approach, because its easy to become forgotten and in a year or so some poor developer will scratch her head why the statement performs in a way that might have been apropriate with the data one year ago, but not with the current data ... </p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104066",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16247/"
]
| I have two insert statements, almost exactly the same, which run in two different schemas on the same Oracle instance. What the insert statement looks like doesn't matter - I'm looking for a troubleshooting strategy here.
Both schemas have 99% the same structure. A few columns have slightly different names, other than that they're the same. The insert statements are almost exactly the same. The explain plan on one gives a cost of 6, the explain plan on the other gives a cost of 7. The tables involved in both sets of insert statements have exactly the same indexes. Statistics have been gathered for both schemas.
One insert statement inserts 12,000 records in 5 seconds.
The other insert statement inserts 25,000 records in 4 minutes 19 seconds.
The number of records being insert is correct. It's the vast disparity in execution times that confuses me. Given that nothing stands out in the explain plan, how would you go about determining what's causing this disparity in runtimes?
(I am using Oracle 10.2.0.4 on a Windows box).
**Edit:** The problem ended up being an inefficient query plan, involving a cartesian merge which didn't need to be done. Judicious use of index hints and a hash join hint solved the problem. It now takes 10 seconds. Sql Trace / TKProf gave me the direction, as I it showed me how many seconds each step in the plan took, and how many rows were being generated. Thus TKPROF showed me:-
```
Rows Row Source Operation
------- ---------------------------------------------------
23690 NESTED LOOPS OUTER (cr=3310466 pr=17 pw=0 time=174881374 us)
23690 NESTED LOOPS (cr=3310464 pr=17 pw=0 time=174478629 us)
2160900 MERGE JOIN CARTESIAN (cr=102 pr=0 pw=0 time=6491451 us)
1470 TABLE ACCESS BY INDEX ROWID TBL1 (cr=57 pr=0 pw=0 time=23978 us)
8820 INDEX RANGE SCAN XIF5TBL1 (cr=16 pr=0 pw=0 time=8859 us)(object id 272041)
2160900 BUFFER SORT (cr=45 pr=0 pw=0 time=4334777 us)
1470 TABLE ACCESS BY INDEX ROWID TBL1 (cr=45 pr=0 pw=0 time=2956 us)
8820 INDEX RANGE SCAN XIF5TBL1 (cr=10 pr=0 pw=0 time=8830 us)(object id 272041)
23690 MAT_VIEW ACCESS BY INDEX ROWID TBL2 (cr=3310362 pr=17 pw=0 time=235116546 us)
96565 INDEX RANGE SCAN XPK_TBL2 (cr=3219374 pr=3 pw=0 time=217869652 us)(object id 272084)
0 TABLE ACCESS BY INDEX ROWID TBL3 (cr=2 pr=0 pw=0 time=293390 us)
0 INDEX RANGE SCAN XIF1TBL3 (cr=2 pr=0 pw=0 time=180345 us)(object id 271983)
```
Notice the rows where the operations are MERGE JOIN CARTESIAN and BUFFER SORT. Things that keyed me into looking at this were the number of rows generated (over 2 million!), and the amount of time spent on each operation (compare to other operations). | Use the [SQL Trace facility and TKPROF](http://docs.oracle.com/cd/B19306_01/server.102/b14211/sqltrace.htm#g33356). |
104,068 | <p>Let's say we have the following method declaration:</p>
<pre><code>Public Function MyMethod(ByVal param1 As Integer, _
Optional ByVal param2 As Integer = 0, _
Optional ByVal param3 As Integer = 1) As Integer
Return param1 + param2 + param3
End Function
</code></pre>
<p>How does VB.NET make the optional parameters work within the confines of the CLR? Are optional parameters CLS-Compliant?</p>
| [
{
"answer_id": 104094,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 3,
"selected": false,
"text": "<p>Contrary to popular belief, optional parameters do appear to be CLS-compliant. (However, my primary check for this was to mark the assembly, class and method all with the CLSCompliant attribute, set to True.)</p>\n\n<p>So what does this look like in MSIL? </p>\n\n<pre><code>.method public static int32 MyMethod(int32 param1,\n [opt] int32 param2,\n [opt] int32 param3) cil managed\n{\n .custom instance void [mscorlib]System.CLSCompliantAttribute::.ctor(bool) = ( 01 00 01 00 00 ) \n .param [2] = int32(0x00000000)\n .param [3] = int32(0x00000001)\n // Code size 11 (0xb)\n .maxstack 2\n .locals init ([0] int32 MyMethod)\n IL_0000: nop\n IL_0001: ldarg.0\n IL_0002: ldarg.1\n IL_0003: add.ovf\n IL_0004: ldarg.2\n IL_0005: add.ovf\n IL_0006: stloc.0\n IL_0007: br.s IL_0009\n IL_0009: ldloc.0\n IL_000a: ret\n} // end of method Module1::MyMethod\n</code></pre>\n\n<p>Note the [opt] markings on the parameters -- MSIL supports this natively, without any hacks. (Unlike MSIL's support for VB's Static keyword, which is another topic altogether.)</p>\n\n<p>So, why aren't these in C#? I can't answer that, other than my speculation that it might be a presumed lack of demand. My own preference has always been to specify the parameters, even if they were optional -- to me, the code looks cleaner and is easier to read. (If there are omitted parameters, I often look first for an overload that matches the visible signature -- it's only after I fail to find one that I realize that optional parameters are involved.)</p>\n"
},
{
"answer_id": 104174,
"author": "MagicKat",
"author_id": 8505,
"author_profile": "https://Stackoverflow.com/users/8505",
"pm_score": 4,
"selected": true,
"text": "<p>Interestingly, this is the decompiled C# code, obtained via reflector.</p>\n\n<pre><code>public int MyMethod(int param1, \n [Optional, DefaultParameterValue(0)] int param2, \n [Optional, DefaultParameterValue(1)] int param3)\n{\n return ((param1 + param2) + param3);\n}\n</code></pre>\n\n<p>Notice the Optional and DefaultParameterValue attributes. Try putting them in C# methods. You will find that you are still required to pass values to the method. In VB code however, its turned into Default! That being said, I personally have never use Default even in VB code. It feels like a hack. Method overloading does the trick for me.</p>\n\n<p>Default does help though, when dealing with the Excel Interop, which is a pain in the ass to use straight out of the box in C#.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104068",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14048/"
]
| Let's say we have the following method declaration:
```
Public Function MyMethod(ByVal param1 As Integer, _
Optional ByVal param2 As Integer = 0, _
Optional ByVal param3 As Integer = 1) As Integer
Return param1 + param2 + param3
End Function
```
How does VB.NET make the optional parameters work within the confines of the CLR? Are optional parameters CLS-Compliant? | Interestingly, this is the decompiled C# code, obtained via reflector.
```
public int MyMethod(int param1,
[Optional, DefaultParameterValue(0)] int param2,
[Optional, DefaultParameterValue(1)] int param3)
{
return ((param1 + param2) + param3);
}
```
Notice the Optional and DefaultParameterValue attributes. Try putting them in C# methods. You will find that you are still required to pass values to the method. In VB code however, its turned into Default! That being said, I personally have never use Default even in VB code. It feels like a hack. Method overloading does the trick for me.
Default does help though, when dealing with the Excel Interop, which is a pain in the ass to use straight out of the box in C#. |
104,158 | <p>I came across this recently, up until now I have been happily overriding the equality operator (<strong>==</strong>) and/or <strong>Equals</strong> method in order to see if two references types actually contained the same <strong>data</strong> (i.e. two different instances that look the same).</p>
<p>I have been using this even more since I have been getting more in to automated testing (comparing reference/expected data against that returned).</p>
<p>While looking over some of the <a href="http://msdn.microsoft.com/en-us/library/ms229042(VS.80).aspx" rel="noreferrer">coding standards guidelines in MSDN</a> I came across an <a href="http://msdn.microsoft.com/en-us/library/7h9bszxx(VS.80).aspx" rel="noreferrer">article</a> that advises against it. Now I understand <em>why</em> the article is saying this (because they are not the same <em>instance</em>) but it does not answer the question:</p>
<ol>
<li><strong>What is the best way to compare two reference types?</strong></li>
<li>Should we implement <a href="http://msdn.microsoft.com/en-us/library/system.icomparable.aspx" rel="noreferrer">IComparable</a>? (I have also seen mention that this should be reserved for value types only).</li>
<li>Is there some interface I don't know about?</li>
<li>Should we just roll our own?!</li>
</ol>
<p>Many Thanks ^_^</p>
<h2>Update</h2>
<p>Looks like I had mis-read some of the documentation (it's been a long day) and overriding <a href="http://msdn.microsoft.com/en-us/library/336aedhh(VS.71).aspx" rel="noreferrer">Equals</a> may be the way to go..</p>
<blockquote>
<p>If you are implementing reference
types, you should consider overriding
the Equals method on a reference type
if your type looks like a base type
such as a Point, String, BigNumber,
and so on. Most reference types should
not overload the <strong>equality</strong> operator,
even <strong>if they override Equals</strong>. However,
if you are implementing a reference
type that is intended to have value
semantics, such as a complex number
type, you should override the equality
operator.</p>
</blockquote>
| [
{
"answer_id": 104178,
"author": "Paul Shannon",
"author_id": 11503,
"author_profile": "https://Stackoverflow.com/users/11503",
"pm_score": 2,
"selected": false,
"text": "<p>For complex objects that will yield specific comparisons then implementing IComparable and defining the comparison in the Compare methods is a good implementation.</p>\n\n<p>For example we have \"Vehicle\" objects where the only difference may be the registration number and we use this to compare to ensure that the expected value returned in testing is the one we want.</p>\n"
},
{
"answer_id": 104197,
"author": "Matt J",
"author_id": 18528,
"author_profile": "https://Stackoverflow.com/users/18528",
"pm_score": 6,
"selected": true,
"text": "<p>It looks like you're coding in C#, which has a method called Equals that your class should implement, should you want to compare two objects using some other metric than \"are these two pointers (because object handles are just that, pointers) to the same memory address?\".</p>\n\n<p>I grabbed some sample code from <a href=\"http://msdn.microsoft.com/en-us/library/ms173147(VS.80).aspx\" rel=\"noreferrer\">here</a>:</p>\n\n<pre><code>class TwoDPoint : System.Object\n{\n public readonly int x, y;\n\n public TwoDPoint(int x, int y) //constructor\n {\n this.x = x;\n this.y = y;\n }\n\n public override bool Equals(System.Object obj)\n {\n // If parameter is null return false.\n if (obj == null)\n {\n return false;\n }\n\n // If parameter cannot be cast to Point return false.\n TwoDPoint p = obj as TwoDPoint;\n if ((System.Object)p == null)\n {\n return false;\n }\n\n // Return true if the fields match:\n return (x == p.x) && (y == p.y);\n }\n\n public bool Equals(TwoDPoint p)\n {\n // If parameter is null return false:\n if ((object)p == null)\n {\n return false;\n }\n\n // Return true if the fields match:\n return (x == p.x) && (y == p.y);\n }\n\n public override int GetHashCode()\n {\n return x ^ y;\n }\n}\n</code></pre>\n\n<p>Java has very similar mechanisms. The <em>equals()</em> method is part of the <em>Object</em> class, and your class overloads it if you want this type of functionality.</p>\n\n<p>The reason overloading '==' can be a bad idea for objects is that, usually, you still want to be able to do the \"are these the same pointer\" comparisons. These are usually relied upon for, for instance, inserting an element into a list where no duplicates are allowed, and some of your framework stuff may not work if this operator is overloaded in a non-standard way.</p>\n"
},
{
"answer_id": 104207,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 2,
"selected": false,
"text": "<p>That article just recommends against overriding the equality operator (for reference types), not against overriding Equals. You should override Equals within your object (reference or value) if equality checks will mean something more than reference checks. If you want an interface, you can also implement <a href=\"http://msdn.microsoft.com/en-us/library/ms131187.aspx\" rel=\"nofollow noreferrer\">IEquatable</a> (used by generic collections). If you do implement IEquatable, however, you should also override equals, as the IEquatable remarks section states:</p>\n\n<blockquote>\n <p>If you implement IEquatable<T>, you should also override the base class implementations of Object.Equals(Object) and GetHashCode so that their behavior is consistent with that of the IEquatable<T>.Equals method. If you do override Object.Equals(Object), your overridden implementation is also called in calls to the static Equals(System.Object, System.Object) method on your class. This ensures that all invocations of the Equals method return consistent results. </p>\n</blockquote>\n\n<p>In regards to whether you should implement Equals and/or the equality operator:</p>\n\n<p>From <a href=\"http://msdn.microsoft.com/en-us/library/336aedhh(VS.80).aspx\" rel=\"nofollow noreferrer\">Implementing the Equals Method</a></p>\n\n<blockquote>\n <p>Most reference types should not overload the equality operator, even if they override Equals.</p>\n</blockquote>\n\n<p>From <a href=\"http://msdn.microsoft.com/en-us/library/7h9bszxx(VS.80).aspx\" rel=\"nofollow noreferrer\">Guidelines for Implementing Equals and the Equality Operator (==)</a></p>\n\n<blockquote>\n <p>Override the Equals method whenever you implement the equality operator (==), and make them do the same thing.</p>\n</blockquote>\n\n<p>This only says that you need to override Equals whenever you implement the equality operator. It does <em>not</em> say that you need to override the equality operator when you override Equals.</p>\n"
},
{
"answer_id": 104209,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 1,
"selected": false,
"text": "<p>I tend to use what Resharper automatically makes. for example, it autocreated this for one of my reference types:</p>\n\n<pre><code>public override bool Equals(object obj)\n{\n if (ReferenceEquals(null, obj)) return false;\n if (ReferenceEquals(this, obj)) return true;\n return obj.GetType() == typeof(SecurableResourcePermission) && Equals((SecurableResourcePermission)obj);\n}\n\npublic bool Equals(SecurableResourcePermission obj)\n{\n if (ReferenceEquals(null, obj)) return false;\n if (ReferenceEquals(this, obj)) return true;\n return obj.ResourceUid == ResourceUid && Equals(obj.ActionCode, ActionCode) && Equals(obj.AllowDeny, AllowDeny);\n}\n\npublic override int GetHashCode()\n{\n unchecked\n {\n int result = (int)ResourceUid;\n result = (result * 397) ^ (ActionCode != null ? ActionCode.GetHashCode() : 0);\n result = (result * 397) ^ AllowDeny.GetHashCode();\n return result;\n }\n}\n</code></pre>\n\n<p>If you want to override <code>==</code> and still do ref checks, you can still use <code>Object.ReferenceEquals</code>.</p>\n"
},
{
"answer_id": 104309,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<p>Implementing equality in .NET correctly, efficiently and <em>without code duplication</em> is hard. Specifically, for reference types with value semantics (i.e. <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-define-value-equality-for-a-type\" rel=\"nofollow noreferrer\">immutable types that treat equvialence as equality</a>), you should implement <a href=\"https://msdn.microsoft.com/en-us/library/ms131187%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\">the <code>System.IEquatable<T></code> interface</a>, and you should implement all the different operations (<code>Equals</code>, <code>GetHashCode</code> and <code>==</code>, <code>!=</code>).</p>\n\n<p>As an example, here’s a class implementing value equality:</p>\n\n<pre><code>class Point : IEquatable<Point> {\n public int X { get; }\n public int Y { get; }\n\n public Point(int x = 0, int y = 0) { X = x; Y = y; }\n\n public bool Equals(Point other) {\n if (other is null) return false;\n <b>return X.Equals(other.X) && Y.Equals(other.Y);</b>\n }\n\n public override bool Equals(object obj) => Equals(obj as Point);\n\n public static bool operator ==(Point lhs, Point rhs) => object.Equals(lhs, rhs);\n\n public static bool operator !=(Point lhs, Point rhs) => ! (lhs == rhs);\n\n public override int GetHashCode() => <b>X.GetHashCode() ^ Y.GetHashCode();</b>\n}</code></pre>\n\n<p>The only movable parts in the above code are the bolded parts: the second line in <code>Equals(Point other)</code> and the <code>GetHashCode()</code> method. The other code should remain unchanged.</p>\n\n<p>For reference classes that do not represent immutable values, do not implement the operators <code>==</code> and <code>!=</code>. Instead, use their default meaning, which is to compare object identity.</p>\n\n<p>The code <em>intentionally</em> equates even objects of a derived class type. Often, this might not be desirable because equality between the base class and derived classes is not well-defined. Unfortunately, .NET and the coding guidelines are not very clear here. The code that Resharper creates, posted <a href=\"https://stackoverflow.com/q/104158/1968#104209\">in another answer</a>, is susceptible to undesired behaviour in such cases because <code>Equals(object x)</code> and <code>Equals(SecurableResourcePermission x)</code> <em>will</em> treat this case differently.</p>\n\n<p>In order to change this behaviour, an additional type check has to be inserted in the strongly-typed <code>Equals</code> method above:</p>\n\n<pre><code>public bool Equals(Point other) {\n if (other is null) return false;\n if (other.GetType() != GetType()) return false;\n <b>return X.Equals(other.X) && Y.Equals(other.Y);</b>\n}</code></pre>\n"
},
{
"answer_id": 730857,
"author": "Zach Burlingame",
"author_id": 2233,
"author_profile": "https://Stackoverflow.com/users/2233",
"pm_score": 4,
"selected": false,
"text": "<p>Below I have summed up what you need to do when implementing IEquatable and provided the justification from the various MSDN documentation pages.</p>\n\n<hr>\n\n<h2>Summary</h2>\n\n<ul>\n<li>When testing for value equality is desired (such as when using objects in collections) you should implement the IEquatable interface, override Object.Equals, and GetHashCode for your class.</li>\n<li>When testing for reference equality is desired you should use operator==,operator!= and <a href=\"http://msdn.microsoft.com/en-us/library/system.object.referenceequals.aspx\" rel=\"nofollow noreferrer\">Object.ReferenceEquals</a>.</li>\n<li>You should only override operator== and operator!= for <a href=\"http://msdn.microsoft.com/en-us/library/system.valuetype.aspx\" rel=\"nofollow noreferrer\">ValueTypes</a> and immutable reference types.</li>\n</ul>\n\n<hr>\n\n<h2>Justification</h2>\n\n<p><strong><a href=\"http://msdn.microsoft.com/en-us/library/ms131187.aspx\" rel=\"nofollow noreferrer\">IEquatable</a></strong></p>\n\n<blockquote>\n <p>The System.IEquatable interface is used to compare two instances of an object for equality. The objects are compared based on the logic implemented in the class. The comparison results in a boolean value indicating if the objects are different. This is in contrast to the System.IComparable interface, which return an integer indicating how the object values are different.</p>\n \n <p>The IEquatable interface declares two methods that must be overridden. The Equals method contains the implementation to perform the actual comparison and return true if the object values are equal, or false if they are not. The GetHashCode method should return a unique hash value that may be used to uniquely identify identical objects that contain different values. The type of hashing algorithm used is implementation-specific. </p>\n</blockquote>\n\n<p><strong><a href=\"http://msdn.microsoft.com/en-us/library/ms131190.aspx\" rel=\"nofollow noreferrer\">IEquatable.Equals Method</a></strong></p>\n\n<blockquote>\n <ul>\n <li>You should implement IEquatable for your objects to handle the possibility that they will be stored in an array or generic collection.</li>\n <li>If you implement IEquatable you should also override the base class implementations of Object.Equals(Object) and GetHashCode so that their behavior is consistent with that of the IEquatable.Equals method</li>\n </ul>\n</blockquote>\n\n<p><strong><a href=\"http://msdn.microsoft.com/en-us/library/ms173147.aspx\" rel=\"nofollow noreferrer\">Guidelines for Overriding Equals() and Operator == (C# Programming Guide)</a></strong></p>\n\n<blockquote>\n <ul>\n <li>x.Equals(x) returns true.</li>\n <li>x.Equals(y) returns the same value as y.Equals(x)</li>\n <li>if (x.Equals(y) && y.Equals(z)) returns true, then x.Equals(z) returns true.</li>\n <li>Successive invocations of x. Equals (y) return the same value as long as the objects referenced by x and y are not modified.</li>\n <li>x. Equals (null) returns false (for non-nullable value types only. For more information, see <a href=\"http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx\" rel=\"nofollow noreferrer\">Nullable Types (C# Programming Guide)</a>.) </li>\n <li>The new implementation of Equals should not throw exceptions.</li>\n <li>It is recommended that any class that overrides Equals also override Object.GetHashCode.</li>\n <li>Is is recommended that in addition to implementing Equals(object), any class also implement Equals(type) for their own type, to enhance performance.</li>\n </ul>\n \n <p><strong>By default, the operator == tests for reference equality by determining whether two references indicate the same object.</strong> Therefore, reference types do not have to implement operator == in order to gain this functionality. When a type is immutable, that is, the data that is contained in the instance cannot be changed, overloading operator == to compare value equality instead of reference equality can be useful because, as immutable objects, they can be considered the same as long as they have the same value. <strong>It is not a good idea to override operator == in non-immutable types.</strong></p>\n \n <ul>\n <li>Overloaded operator == implementations should not throw exceptions.</li>\n <li>Any type that overloads operator == should also overload operator !=.</li>\n </ul>\n</blockquote>\n\n<p><strong><a href=\"http://msdn.microsoft.com/en-us/library/53k8ybth.aspx\" rel=\"nofollow noreferrer\">== Operator (C# Reference)</a></strong></p>\n\n<blockquote>\n <ul>\n <li>For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise.</li>\n <li>For reference types other than string, == returns true if its two operands refer to the same object. </li>\n <li>For the string type, == compares the values of the strings.</li>\n <li>When testing for null using == comparisons within your operator== overrides, make sure you use the base object class operator. If you don't, infinite recursion will occur resulting in a stackoverflow.</li>\n </ul>\n</blockquote>\n\n<p><strong><a href=\"http://msdn.microsoft.com/en-us/library/bsc2ak47.aspx\" rel=\"nofollow noreferrer\">Object.Equals Method (Object)</a></strong></p>\n\n<blockquote>\n <p>If your programming language supports operator overloading and if you choose to overload the equality operator for a given type, that type must override the Equals method. Such implementations of the Equals method must return the same results as the equality operator</p>\n \n <p>The following guidelines are for implementing a <strong>value type</strong>:</p>\n \n <ul>\n <li>Consider overriding Equals to gain increased performance over that provided by the default implementation of Equals on ValueType.</li>\n <li>If you override Equals and the language supports operator overloading, you must overload the equality operator for your value type.</li>\n </ul>\n \n <p>The following guidelines are for implementing a <strong>reference type</strong>:</p>\n \n <ul>\n <li>Consider overriding Equals on a reference type if the semantics of the type are based on the fact that the type represents some value(s).</li>\n <li>Most reference types must not overload the equality operator, even if they override Equals. However, if you are implementing a reference type that is intended to have value semantics, such as a complex number type, you must override the equality operator.</li>\n </ul>\n</blockquote>\n\n<hr>\n\n<h2>Additional Gotchas</h2>\n\n<ul>\n<li>When overriding GetHashCode() make sure you test reference types for NULL before using them in the hash code.</li>\n<li>I ran into a problem with interface-based programming and operator overloading described here: <a href=\"https://stackoverflow.com/questions/728434/operator-overloading-with-interface-based-programming-in-c\">Operator Overloading with Interface-Based Programming in C#</a></li>\n</ul>\n"
},
{
"answer_id": 13905114,
"author": "nawfal",
"author_id": 661933,
"author_profile": "https://Stackoverflow.com/users/661933",
"pm_score": 0,
"selected": false,
"text": "<p>I believe getting something as simple as checking objects for equality correct is a bit tricky with .NET's design.</p>\n\n<p><strong>For Struct</strong></p>\n\n<p>1) Implement <code>IEquatable<T></code>. It improves performance noticeably.</p>\n\n<p>2) Since you're having your own <code>Equals</code> now, override <code>GetHashCode</code>, and to be consistent with various equality checking override <code>object.Equals</code> as well.</p>\n\n<p>3) Overloading <code>==</code> and <code>!=</code> operators need not be religiously done since the compiler will warn if you unintentionally equate a struct with another with a <code>==</code> or <code>!=</code>, but its good to do so to be consistent with <code>Equals</code> methods.</p>\n\n<pre><code>public struct Entity : IEquatable<Entity>\n{\n public bool Equals(Entity other)\n {\n throw new NotImplementedException(\"Your equality check here...\");\n }\n\n public override bool Equals(object obj)\n {\n if (obj == null || !(obj is Entity))\n return false;\n\n return Equals((Entity)obj);\n }\n\n public static bool operator ==(Entity e1, Entity e2)\n {\n return e1.Equals(e2);\n }\n\n public static bool operator !=(Entity e1, Entity e2)\n {\n return !(e1 == e2);\n }\n\n public override int GetHashCode()\n {\n throw new NotImplementedException(\"Your lightweight hashing algorithm, consistent with Equals method, here...\");\n }\n}\n</code></pre>\n\n<p><strong>For Class</strong></p>\n\n<p>From MS:</p>\n\n<blockquote>\n <p>Most reference types should not overload the equality operator, even if they override Equals.</p>\n</blockquote>\n\n<p>To me <code>==</code> feels like value equality, more like a syntactic sugar for <code>Equals</code> method. Writing <code>a == b</code> is much more intuitive than writing <code>a.Equals(b)</code>. Rarely we'll need to check reference equality. In abstract levels dealing with logical representations of physical objects this is not something we would need to check. I think having different semantics for <code>==</code> and <code>Equals</code> can actually be confusing. I believe it should have been <code>==</code> for value equality and <code>Equals</code> for reference (or a better name like <code>IsSameAs</code>) equality in the first place. <em>I would love to not take MS guideline seriously here, not just because it isn't natural to me, but also because overloading <code>==</code> doesn't do any major harm.</em> That's unlike not overriding non-generic <code>Equals</code> or <code>GetHashCode</code> which can bite back, because framework doesn't use <code>==</code> anywhere but only if we ourself use it. The only real benefit I gain from <em>not overloading <code>==</code> and <code>!=</code></em> will be the consistency with design of the entire framework over which I have no control of. And that's indeed a big thing, <strong>so sadly I will stick to it</strong>.</p>\n\n<p><em>With reference semantics (mutable objects)</em></p>\n\n<p>1) Override <code>Equals</code> and <code>GetHashCode</code>.</p>\n\n<p>2) Implementing <code>IEquatable<T></code> isn't a must, but will be nice if you have one.</p>\n\n<pre><code>public class Entity : IEquatable<Entity>\n{\n public bool Equals(Entity other)\n {\n if (ReferenceEquals(this, other))\n return true;\n\n if (ReferenceEquals(null, other))\n return false;\n\n //if your below implementation will involve objects of derived classes, then do a \n //GetType == other.GetType comparison\n throw new NotImplementedException(\"Your equality check here...\");\n }\n\n public override bool Equals(object obj)\n {\n return Equals(obj as Entity);\n }\n\n public override int GetHashCode()\n {\n throw new NotImplementedException(\"Your lightweight hashing algorithm, consistent with Equals method, here...\");\n }\n}\n</code></pre>\n\n<p><em>With value semantics (immutable objects)</em></p>\n\n<p>This is the tricky part. Can get easily messed up if not taken care..</p>\n\n<p>1) Override <code>Equals</code> and <code>GetHashCode</code>.</p>\n\n<p>2) Overload <code>==</code> and <code>!=</code> to match <code>Equals</code>. <em>Make sure it works for nulls</em>.</p>\n\n<p>2) Implementing <code>IEquatable<T></code> isn't a must, but will be nice if you have one.</p>\n\n<pre><code>public class Entity : IEquatable<Entity>\n{\n public bool Equals(Entity other)\n {\n if (ReferenceEquals(this, other))\n return true;\n\n if (ReferenceEquals(null, other))\n return false;\n\n //if your below implementation will involve objects of derived classes, then do a \n //GetType == other.GetType comparison\n throw new NotImplementedException(\"Your equality check here...\");\n }\n\n public override bool Equals(object obj)\n {\n return Equals(obj as Entity);\n }\n\n public static bool operator ==(Entity e1, Entity e2)\n {\n if (ReferenceEquals(e1, null))\n return ReferenceEquals(e2, null);\n\n return e1.Equals(e2);\n }\n\n public static bool operator !=(Entity e1, Entity e2)\n {\n return !(e1 == e2);\n }\n\n public override int GetHashCode()\n {\n throw new NotImplementedException(\"Your lightweight hashing algorithm, consistent with Equals method, here...\");\n }\n}\n</code></pre>\n\n<p><strong>Take special care to see how it should fare if your class can be inherited, in such cases you will have to determine if a base class object can be equal to a derived class object. Ideally, if no objects of derived class is used for equality checking, then a base class instance can be equal to a derived class instance and in such cases, there is no need to check <code>Type</code> equality in generic <code>Equals</code> of base class.</strong></p>\n\n<p>In general take care not to duplicate code. I could have made a generic abstract base class (<code>IEqualizable<T></code> or so) as a template to allow re-use easier, but sadly in C# that stops me from deriving from additional classes.</p>\n"
},
{
"answer_id": 39581164,
"author": "Bob Bryan",
"author_id": 643828,
"author_profile": "https://Stackoverflow.com/users/643828",
"pm_score": 1,
"selected": false,
"text": "<p>Microsoft appears to have changed their tune, or at least there is conflicting info about not overloading the equality operator. According to this <a href=\"https://msdn.microsoft.com/en-us/library/dd183755.aspx\" rel=\"nofollow noreferrer\">Microsoft article</a> titled How to: Define Value Equality for a Type:</p>\n\n<p>\"The == and != operators can be used with classes even if the class does not overload them. However, the default behavior is to perform a reference equality check. In a class, if you overload the Equals method, you should overload the == and != operators, but it is not required.\"</p>\n\n<p>According to Eric Lippert in his <a href=\"https://stackoverflow.com/a/32184635/643828\">answer</a> to a question I asked about <a href=\"https://stackoverflow.com/questions/32172273/minimal-code-for-equality-in-c-sharp\">Minimal code for equality in C#</a> - he says:</p>\n\n<p>\"The danger you run into here is that you get an == operator defined for you that does reference equality by default. You could easily end up in a situation where an overloaded Equals method does value equality and == does reference equality, and then you accidentally use reference equality on not-reference-equal things that are value-equal. This is an error-prone practice that is hard to spot by human code review.</p>\n\n<p>A couple years ago I worked on a static analysis algorithm to statistically detect this situation, and we found a defect rate of about two instances per million lines of code across all codebases we studied. When considering just codebases which had somewhere overridden Equals, the defect rate was obviously considerably higher!</p>\n\n<p>Moreover, consider the costs vs the risks. If you already have implementations of IComparable then writing all the operators is trivial one-liners that will not have bugs and will never be changed. It's the cheapest code you're ever going to write. If given the choice between the fixed cost of writing and testing a dozen tiny methods vs the unbounded cost of finding and fixing a hard-to-see bug where reference equality is used instead of value equality, I know which one I would pick.\"</p>\n\n<p>The .NET Framework will not ever use == or != with any type that you write. But, the danger is what would happen if someone else does. So, if the class is for a 3rd party, then I would always provide the == and != operators. If the class is only intended to be used internally by the group, I would still probably implement the == and != operators.</p>\n\n<p>I would only implement the <, <=, >, and >= operators if IComparable was implemented. IComparable should only be implemented if the type needs to support ordering - like when sorting or being used in an ordered generic container like SortedSet.</p>\n\n<p>If the group or company had a policy in place to not ever implement the == and != operators - then I would of course follow that policy. If such a policy were in place, then it would be wise to enforce it with a Q/A code analysis tool that flags any occurrence of the == and != operators when used with a reference type.</p>\n"
},
{
"answer_id": 51130223,
"author": "kofifus",
"author_id": 460084,
"author_profile": "https://Stackoverflow.com/users/460084",
"pm_score": 0,
"selected": false,
"text": "<p>All the answers above do not consider polymorphism, often you want derived references to use the derived Equals even when compared via a base reference. Please see the question/ discussion/ answers here - <a href=\"https://stackoverflow.com/questions/54877077/equality-and-polymorphism/54934113#54934113\">Equality and polymorphism</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104158",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
]
| I came across this recently, up until now I have been happily overriding the equality operator (**==**) and/or **Equals** method in order to see if two references types actually contained the same **data** (i.e. two different instances that look the same).
I have been using this even more since I have been getting more in to automated testing (comparing reference/expected data against that returned).
While looking over some of the [coding standards guidelines in MSDN](http://msdn.microsoft.com/en-us/library/ms229042(VS.80).aspx) I came across an [article](http://msdn.microsoft.com/en-us/library/7h9bszxx(VS.80).aspx) that advises against it. Now I understand *why* the article is saying this (because they are not the same *instance*) but it does not answer the question:
1. **What is the best way to compare two reference types?**
2. Should we implement [IComparable](http://msdn.microsoft.com/en-us/library/system.icomparable.aspx)? (I have also seen mention that this should be reserved for value types only).
3. Is there some interface I don't know about?
4. Should we just roll our own?!
Many Thanks ^\_^
Update
------
Looks like I had mis-read some of the documentation (it's been a long day) and overriding [Equals](http://msdn.microsoft.com/en-us/library/336aedhh(VS.71).aspx) may be the way to go..
>
> If you are implementing reference
> types, you should consider overriding
> the Equals method on a reference type
> if your type looks like a base type
> such as a Point, String, BigNumber,
> and so on. Most reference types should
> not overload the **equality** operator,
> even **if they override Equals**. However,
> if you are implementing a reference
> type that is intended to have value
> semantics, such as a complex number
> type, you should override the equality
> operator.
>
>
> | It looks like you're coding in C#, which has a method called Equals that your class should implement, should you want to compare two objects using some other metric than "are these two pointers (because object handles are just that, pointers) to the same memory address?".
I grabbed some sample code from [here](http://msdn.microsoft.com/en-us/library/ms173147(VS.80).aspx):
```
class TwoDPoint : System.Object
{
public readonly int x, y;
public TwoDPoint(int x, int y) //constructor
{
this.x = x;
this.y = y;
}
public override bool Equals(System.Object obj)
{
// If parameter is null return false.
if (obj == null)
{
return false;
}
// If parameter cannot be cast to Point return false.
TwoDPoint p = obj as TwoDPoint;
if ((System.Object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
public bool Equals(TwoDPoint p)
{
// If parameter is null return false:
if ((object)p == null)
{
return false;
}
// Return true if the fields match:
return (x == p.x) && (y == p.y);
}
public override int GetHashCode()
{
return x ^ y;
}
}
```
Java has very similar mechanisms. The *equals()* method is part of the *Object* class, and your class overloads it if you want this type of functionality.
The reason overloading '==' can be a bad idea for objects is that, usually, you still want to be able to do the "are these the same pointer" comparisons. These are usually relied upon for, for instance, inserting an element into a list where no duplicates are allowed, and some of your framework stuff may not work if this operator is overloaded in a non-standard way. |
104,184 | <p>There is a case where a map will be constructed, and once it is initialized, it will never be modified again. It will however, be accessed (via get(key) only) from multiple threads. Is it safe to use a <code>java.util.HashMap</code> in this way?</p>
<p>(Currently, I'm happily using a <code>java.util.concurrent.ConcurrentHashMap</code>, and have no measured need to improve performance, but am simply curious if a simple <code>HashMap</code> would suffice. Hence, this question is <em>not</em> "Which one should I use?" nor is it a performance question. Rather, the question is "Would it be safe?")</p>
| [
{
"answer_id": 104251,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.docjar.com/html/api/java/util/HashMap.java.html\" rel=\"nofollow noreferrer\">http://www.docjar.com/html/api/java/util/HashMap.java.html</a></p>\n\n<p>here is the source for HashMap. As you can tell, there is absolutely no locking / mutex code there.</p>\n\n<p>This means that while its okay to read from a HashMap in a multithreaded situation, I'd definitely use a ConcurrentHashMap if there were multiple writes.</p>\n\n<p>Whats interesting is that both the .NET HashTable and Dictionary<K,V> have built in synchronization code.</p>\n"
},
{
"answer_id": 104265,
"author": "Dave L.",
"author_id": 3093,
"author_profile": "https://Stackoverflow.com/users/3093",
"pm_score": 4,
"selected": false,
"text": "<p>After a bit more looking, I found this in the <a href=\"http://java.sun.com/javase/6/docs/api/java/util/HashMap.html\" rel=\"noreferrer\">java doc</a> (emphasis mine):</p>\n\n<blockquote>\n <p>Note that this implementation is not\n synchronized. <strong>If multiple threads\n access a hash map concurrently, and at\n least one of the threads modifies the\n map structurally, it must be\n synchronized externally.</strong> (A structural\n modification is any operation that\n adds or deletes one or more mappings;\n merely changing the value associated\n with a key that an instance already\n contains is not a structural\n modification.)</p>\n</blockquote>\n\n<p>This seems to imply that it will be safe, assuming the converse of the statement there is true.</p>\n"
},
{
"answer_id": 104398,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 1,
"selected": false,
"text": "<p>Be warned that even in single-threaded code, replacing a ConcurrentHashMap with a HashMap may not be safe. ConcurrentHashMap forbids null as a key or value. HashMap does not forbid them (don't ask).</p>\n\n<p>So in the unlikely situation that your existing code might add a null to the collection during setup (presumably in a failure case of some kind), replacing the collection as described will change the functional behaviour.</p>\n\n<p>That said, provided you do nothing else concurrent reads from a HashMap are safe. </p>\n\n<p>[Edit: by \"concurrent reads\", I mean that there are not also concurrent modifications.</p>\n\n<p>Other answers explain how to ensure this. One way is to make the map immutable, but it's not necessary. For example, the JSR133 memory model explicitly defines starting a thread to be a synchronised action, meaning that changes made in thread A before it starts thread B are visible in thread B.</p>\n\n<p>My intent is not to contradict those more detailed answers about the Java Memory Model. This answer is intended to point out that even aside from concurrency issues, there is at least one API difference between ConcurrentHashMap and HashMap, which could scupper even a single-threaded program which replaced one with the other.]</p>\n"
},
{
"answer_id": 104534,
"author": "Taylor Gautier",
"author_id": 19013,
"author_profile": "https://Stackoverflow.com/users/19013",
"pm_score": 6,
"selected": false,
"text": "<p>Jeremy Manson, the god when it comes to the Java Memory Model, has a three part blog on this topic - because in essence you are asking the question \"Is it safe to access an immutable HashMap\" - the answer to that is yes. But you must answer the predicate to that question which is - \"Is my HashMap immutable\". The answer might surprise you - Java has a relatively complicated set of rules to determine immutability.</p>\n\n<p>For more info on the topic, read Jeremy's blog posts:</p>\n\n<p>Part 1 on Immutability in Java:\n<a href=\"http://jeremymanson.blogspot.com/2008/04/immutability-in-java.html\" rel=\"noreferrer\">http://jeremymanson.blogspot.com/2008/04/immutability-in-java.html</a> </p>\n\n<p>Part 2 on Immutability in Java:\n<a href=\"http://jeremymanson.blogspot.com/2008/07/immutability-in-java-part-2.html\" rel=\"noreferrer\">http://jeremymanson.blogspot.com/2008/07/immutability-in-java-part-2.html</a></p>\n\n<p>Part 3 on Immutability in Java:\n<a href=\"http://jeremymanson.blogspot.com/2008/07/immutability-in-java-part-3.html\" rel=\"noreferrer\">http://jeremymanson.blogspot.com/2008/07/immutability-in-java-part-3.html</a></p>\n"
},
{
"answer_id": 104636,
"author": "Heath Borders",
"author_id": 9636,
"author_profile": "https://Stackoverflow.com/users/9636",
"pm_score": 5,
"selected": false,
"text": "<p>The reads are safe from a synchronization standpoint but not a memory standpoint. This is something that is widely misunderstood among Java developers including here on Stackoverflow. (Observe the rating of <a href=\"https://stackoverflow.com/questions/84285/calling-threadstart-within-its-own-constructor#84937\">this answer</a> for proof.)</p>\n\n<p>If you have other threads running, they may not see an updated copy of the HashMap if there is no memory write out of the current thread. Memory writes occur through the use of the synchronized or volatile keywords, or through uses of some java concurrency constructs.</p>\n\n<p>See <a href=\"http://www.ibm.com/developerworks/java/library/j-jtp03304/\" rel=\"nofollow noreferrer\">Brian Goetz's article on the new Java Memory Model</a> for details. </p>\n"
},
{
"answer_id": 104699,
"author": "Alexander",
"author_id": 16724,
"author_profile": "https://Stackoverflow.com/users/16724",
"pm_score": 3,
"selected": false,
"text": "<p>There is an important twist though. It's safe to access the map, but in general it's not guaranteed that all threads will see exactly the same state (and thus values) of the HashMap. This might happen on multiprocessor systems where the modifications to the HashMap done by one thread (e.g., the one that populated it) can sit in that CPU's cache and won't be seen by threads running on other CPUs, until a memory fence operation is performed ensuring cache coherence. The Java Language Specification is explicit on this one: the solution is to acquire a lock (synchronized (...)) which emits a memory fence operation. So, if you are sure that after populating the HashMap each of the threads acquires ANY lock, then it's OK from that point on to access the HashMap from any thread until the HashMap is modified again.</p>\n"
},
{
"answer_id": 105670,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 3,
"selected": false,
"text": "<p>One note is that under some circumstances, a get() from an unsynchronized HashMap can cause an infinite loop. This can occur if a concurrent put() causes a rehash of the Map.</p>\n\n<p><a href=\"http://lightbody.net/blog/2005/07/hashmapget_can_cause_an_infini.html\" rel=\"noreferrer\">http://lightbody.net/blog/2005/07/hashmapget_can_cause_an_infini.html</a></p>\n"
},
{
"answer_id": 1702190,
"author": "Will",
"author_id": 207084,
"author_profile": "https://Stackoverflow.com/users/207084",
"pm_score": 2,
"selected": false,
"text": "<p>So the scenario you described is that you need to put a bunch of data into a Map, then when you're done populating it you treat it as immutable. One approach that is \"safe\" (meaning you're enforcing that it really is treated as immutable) is to replace the reference with <code>Collections.unmodifiableMap(originalMap)</code> when you're ready to make it immutable.</p>\n\n<p>For an example of how badly maps can fail if used concurrently, and the suggested workaround I mentioned, check out this bug parade entry: <a href=\"http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6423457\" rel=\"nofollow noreferrer\">bug_id=6423457</a></p>\n"
},
{
"answer_id": 12201121,
"author": "bodrin",
"author_id": 1017901,
"author_profile": "https://Stackoverflow.com/users/1017901",
"pm_score": 3,
"selected": false,
"text": "<p>According to <a href=\"http://www.ibm.com/developerworks/java/library/j-jtp03304/\" rel=\"noreferrer\">http://www.ibm.com/developerworks/java/library/j-jtp03304/</a> # Initialization safety you can make your HashMap a final field and after the constructor finishes it would be safely published.</p>\n\n<p>...\nUnder the new memory model, there is something similar to a happens-before relationship between the write of a final field in a constructor and the initial load of a shared reference to that object in another thread.\n...</p>\n"
},
{
"answer_id": 39746361,
"author": "TomWolk",
"author_id": 1037439,
"author_profile": "https://Stackoverflow.com/users/1037439",
"pm_score": 0,
"selected": false,
"text": "<p>If the initialization and every put is synchronized you are save.</p>\n\n<p>Following code is save because the classloader will take care of the synchronization:</p>\n\n<pre><code>public static final HashMap<String, String> map = new HashMap<>();\nstatic {\n map.put(\"A\",\"A\");\n\n}\n</code></pre>\n\n<p>Following code is save because the writing of volatile will take care of the synchronization.</p>\n\n<pre><code>class Foo {\n volatile HashMap<String, String> map;\n public void init() {\n final HashMap<String, String> tmp = new HashMap<>();\n tmp.put(\"A\",\"A\");\n // writing to volatile has to be after the modification of the map\n this.map = tmp;\n }\n}\n</code></pre>\n\n<p>This will also work if the member variable is final because final is also volatile. And if the method is a constructor.</p>\n"
},
{
"answer_id": 41990379,
"author": "BeeOnRope",
"author_id": 149138,
"author_profile": "https://Stackoverflow.com/users/149138",
"pm_score": 7,
"selected": true,
"text": "<p>Your idiom is safe <strong>if and only if</strong> the reference to the <code>HashMap</code> is <em>safely published</em>. Rather than anything relating the internals of <code>HashMap</code> itself, <em>safe publication</em> deals with how the constructing thread makes the reference to the map visible to other threads.</p>\n\n<p>Basically, the only possible race here is between the construction of the <code>HashMap</code> and any reading threads that may access it before it is fully constructed. Most of the discussion is about what happens to the state of the map object, but this is irrelevant since you never modify it - so the only interesting part is how the <code>HashMap</code> reference is published. </p>\n\n<p>For example, imagine you publish the map like this:</p>\n\n<pre><code>class SomeClass {\n public static HashMap<Object, Object> MAP;\n\n public synchronized static setMap(HashMap<Object, Object> m) {\n MAP = m;\n }\n}\n</code></pre>\n\n<p>... and at some point <code>setMap()</code> is called with a map, and other threads are using <code>SomeClass.MAP</code> to access the map, and check for null like this:</p>\n\n<pre><code>HashMap<Object,Object> map = SomeClass.MAP;\nif (map != null) {\n .. use the map\n} else {\n .. some default behavior\n}\n</code></pre>\n\n<p>This is <strong>not safe</strong> even though it probably appears as though it is. The problem is that there is no <a href=\"https://docs.oracle.com/javase/tutorial/essential/concurrency/memconsist.html\" rel=\"noreferrer\"><em>happens-before</em></a> relationship between the set of <code>SomeObject.MAP</code> and the subsequent read on another thread, so the reading thread is free to see a partially constructed map. This can pretty much do <em>anything</em> and even in practice it does things like <a href=\"http://mailinator.blogspot.com/2009/06/beautiful-race-condition.html\" rel=\"noreferrer\">put the reading thread into an infinite loop</a>.</p>\n\n<p>To safely publish the map, you need to establish a <em>happens-before</em> relationship between the <em>writing of the reference</em> to the <code>HashMap</code> (i.e., the <em>publication</em>) and the subsequent readers of that reference (i.e., the consumption). Conveniently, there are only a few easy-to-remember ways to <a href=\"https://stackoverflow.com/q/5458848/149138\">accomplish</a> that<sup>[1]</sup>:</p>\n\n<ol>\n<li>Exchange the reference through a properly locked field (<a href=\"http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5\" rel=\"noreferrer\">JLS 17.4.5</a>)</li>\n<li>Use static initializer to do the initializing stores (<a href=\"http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4\" rel=\"noreferrer\">JLS 12.4</a>)</li>\n<li>Exchange the reference via a volatile field (<a href=\"http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5\" rel=\"noreferrer\">JLS 17.4.5</a>), or as the consequence of this rule, via the AtomicX classes</li>\n<li>Initialize the value into a final field (<a href=\"http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.5\" rel=\"noreferrer\">JLS 17.5</a>).</li>\n</ol>\n\n<p>The ones most interesting for your scenario are (2), (3) and (4). In particular, (3) applies directly to the code I have above: if you transform the declaration of <code>MAP</code> to:</p>\n\n<pre><code>public static volatile HashMap<Object, Object> MAP;\n</code></pre>\n\n<p>then everything is kosher: readers who see a <em>non-null</em> value necessarily have a <em>happens-before</em> relationship with the store to <code>MAP</code> and hence see all the stores associated with the map initialization.</p>\n\n<p>The other methods change the semantics of your method, since both (2) (using the static initalizer) and (4) (using <em>final</em>) imply that you cannot set <code>MAP</code> dynamically at runtime. If you don't <em>need</em> to do that, then just declare <code>MAP</code> as a <code>static final HashMap<></code> and you are guaranteed safe publication.</p>\n\n<p>In practice, the rules are simple for safe access to \"never-modified objects\":</p>\n\n<p>If you are publishing an object which is not <em>inherently immutable</em> (as in all fields declared <code>final</code>) and:</p>\n\n<ul>\n<li>You already can create the object that will be assigned at the moment of declaration<sup>a</sup>: just use a <code>final</code> field (including <code>static final</code> for static members).</li>\n<li>You want to assign the object later, after the reference is already visible: use a volatile field<sup>b</sup>.</li>\n</ul>\n\n<p>That's it!</p>\n\n<p>In practice, it is very efficient. The use of a <code>static final</code> field, for example, allows the JVM to assume the value is unchanged for the life of the program and optimize it heavily. The use of a <code>final</code> member field allows <em>most</em> architectures to read the field in a way equivalent to a normal field read and doesn't inhibit further optimizations<sup>c</sup>. </p>\n\n<p>Finally, the use of <code>volatile</code> does have some impact: no hardware barrier is needed on many architectures (such as x86, specifically those that don't allow reads to pass reads), but some optimization and reordering may not occur at compile time - but this effect is generally small. In exchange, you actually get more than what you asked for - not only can you safely publish one <code>HashMap</code>, you can store as many more not-modified <code>HashMap</code>s as you want to the same reference and be assured that all readers will see a safely published map.</p>\n\n<p>For more gory details, refer to <a href=\"https://shipilev.net/blog/2014/safe-public-construction/\" rel=\"noreferrer\">Shipilev</a> or <a href=\"https://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#finalRight\" rel=\"noreferrer\">this FAQ by Manson and Goetz</a>.</p>\n\n<hr>\n\n<p>[1] Directly quoting from <a href=\"https://shipilev.net/blog/2014/safe-public-construction/\" rel=\"noreferrer\">shipilev</a>.</p>\n\n<hr>\n\n<p><sup>a</sup> That sounds complicated, but what I mean is that you can assign the reference at construction time - either at the declaration point or in the constructor (member fields) or static initializer (static fields).</p>\n\n<p><sup>b</sup> Optionally, you can use a <code>synchronized</code> method to get/set, or an <code>AtomicReference</code> or something, but we're talking about the minimum work you can do.</p>\n\n<p>c Some architectures with very weak memory models (I'm looking at <em>you</em>, Alpha) may require some type of read barrier before a <code>final</code> read - but these are very rare today.</p>\n"
},
{
"answer_id": 58934205,
"author": "escudero380",
"author_id": 3187094,
"author_profile": "https://Stackoverflow.com/users/3187094",
"pm_score": 3,
"selected": false,
"text": "<p>This question is addressed in Brian Goetz's \"Java Concurrency in Practice\" book (Listing 16.8, page 350): </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>@ThreadSafe\npublic class SafeStates {\n private final Map<String, String> states;\n\n public SafeStates() {\n states = new HashMap<String, String>();\n states.put(\"alaska\", \"AK\");\n states.put(\"alabama\", \"AL\");\n ...\n states.put(\"wyoming\", \"WY\");\n }\n\n public String getAbbreviation(String s) {\n return states.get(s);\n }\n}\n</code></pre>\n\n<p>Since <code>states</code> is declared as <code>final</code> and its initialization is accomplished within the owner's class constructor, any thread who later reads this map is guaranteed to see it as of the time the constructor finishes, provided no other thread will try to modify the contents of the map.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3093/"
]
| There is a case where a map will be constructed, and once it is initialized, it will never be modified again. It will however, be accessed (via get(key) only) from multiple threads. Is it safe to use a `java.util.HashMap` in this way?
(Currently, I'm happily using a `java.util.concurrent.ConcurrentHashMap`, and have no measured need to improve performance, but am simply curious if a simple `HashMap` would suffice. Hence, this question is *not* "Which one should I use?" nor is it a performance question. Rather, the question is "Would it be safe?") | Your idiom is safe **if and only if** the reference to the `HashMap` is *safely published*. Rather than anything relating the internals of `HashMap` itself, *safe publication* deals with how the constructing thread makes the reference to the map visible to other threads.
Basically, the only possible race here is between the construction of the `HashMap` and any reading threads that may access it before it is fully constructed. Most of the discussion is about what happens to the state of the map object, but this is irrelevant since you never modify it - so the only interesting part is how the `HashMap` reference is published.
For example, imagine you publish the map like this:
```
class SomeClass {
public static HashMap<Object, Object> MAP;
public synchronized static setMap(HashMap<Object, Object> m) {
MAP = m;
}
}
```
... and at some point `setMap()` is called with a map, and other threads are using `SomeClass.MAP` to access the map, and check for null like this:
```
HashMap<Object,Object> map = SomeClass.MAP;
if (map != null) {
.. use the map
} else {
.. some default behavior
}
```
This is **not safe** even though it probably appears as though it is. The problem is that there is no [*happens-before*](https://docs.oracle.com/javase/tutorial/essential/concurrency/memconsist.html) relationship between the set of `SomeObject.MAP` and the subsequent read on another thread, so the reading thread is free to see a partially constructed map. This can pretty much do *anything* and even in practice it does things like [put the reading thread into an infinite loop](http://mailinator.blogspot.com/2009/06/beautiful-race-condition.html).
To safely publish the map, you need to establish a *happens-before* relationship between the *writing of the reference* to the `HashMap` (i.e., the *publication*) and the subsequent readers of that reference (i.e., the consumption). Conveniently, there are only a few easy-to-remember ways to [accomplish](https://stackoverflow.com/q/5458848/149138) that[1]:
1. Exchange the reference through a properly locked field ([JLS 17.4.5](http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5))
2. Use static initializer to do the initializing stores ([JLS 12.4](http://docs.oracle.com/javase/specs/jls/se8/html/jls-12.html#jls-12.4))
3. Exchange the reference via a volatile field ([JLS 17.4.5](http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.4.5)), or as the consequence of this rule, via the AtomicX classes
4. Initialize the value into a final field ([JLS 17.5](http://docs.oracle.com/javase/specs/jls/se8/html/jls-17.html#jls-17.5)).
The ones most interesting for your scenario are (2), (3) and (4). In particular, (3) applies directly to the code I have above: if you transform the declaration of `MAP` to:
```
public static volatile HashMap<Object, Object> MAP;
```
then everything is kosher: readers who see a *non-null* value necessarily have a *happens-before* relationship with the store to `MAP` and hence see all the stores associated with the map initialization.
The other methods change the semantics of your method, since both (2) (using the static initalizer) and (4) (using *final*) imply that you cannot set `MAP` dynamically at runtime. If you don't *need* to do that, then just declare `MAP` as a `static final HashMap<>` and you are guaranteed safe publication.
In practice, the rules are simple for safe access to "never-modified objects":
If you are publishing an object which is not *inherently immutable* (as in all fields declared `final`) and:
* You already can create the object that will be assigned at the moment of declarationa: just use a `final` field (including `static final` for static members).
* You want to assign the object later, after the reference is already visible: use a volatile fieldb.
That's it!
In practice, it is very efficient. The use of a `static final` field, for example, allows the JVM to assume the value is unchanged for the life of the program and optimize it heavily. The use of a `final` member field allows *most* architectures to read the field in a way equivalent to a normal field read and doesn't inhibit further optimizationsc.
Finally, the use of `volatile` does have some impact: no hardware barrier is needed on many architectures (such as x86, specifically those that don't allow reads to pass reads), but some optimization and reordering may not occur at compile time - but this effect is generally small. In exchange, you actually get more than what you asked for - not only can you safely publish one `HashMap`, you can store as many more not-modified `HashMap`s as you want to the same reference and be assured that all readers will see a safely published map.
For more gory details, refer to [Shipilev](https://shipilev.net/blog/2014/safe-public-construction/) or [this FAQ by Manson and Goetz](https://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html#finalRight).
---
[1] Directly quoting from [shipilev](https://shipilev.net/blog/2014/safe-public-construction/).
---
a That sounds complicated, but what I mean is that you can assign the reference at construction time - either at the declaration point or in the constructor (member fields) or static initializer (static fields).
b Optionally, you can use a `synchronized` method to get/set, or an `AtomicReference` or something, but we're talking about the minimum work you can do.
c Some architectures with very weak memory models (I'm looking at *you*, Alpha) may require some type of read barrier before a `final` read - but these are very rare today. |
104,223 | <p>I have noticed that cURL in PHP returns different data when told to output to a file via <code>CURLOPT_FILE</code> as it does when told to send the output to a string via <code>CURLOPT_RETURNTRANSFER</code>.</p>
<p><code>_RETURNTRANSFER</code> seems to strip newlines and extra white space as if parsing it for display as standard HTML code. <code>_FILE</code> on the other hand preserves the file exactly as it was intended.</p>
<p>I have read through the documentation on php.net but haven't found anything that seems to solve my problem. Ideally, I would like to have <code>_RETURNTRANSFER</code> return the exact contents so I could eliminate an intermediate file, but I don't see any way of making this possible.</p>
<p>Here is the code I am using. The data in question is a CSV file with \r\n line endings.</p>
<pre><code>function update_roster() {
$url = "http://example.com/";
$userID = "xx";
$apikey = "xxx";
$passfields = "userID=$userID&apikey=$apikey";
$file = fopen("roster.csv","w+");
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $passfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $file);
$variable_in_question = curl_exec ($ch);
curl_close ($ch);
fclose($file);
return $variable_in_question;
}
</code></pre>
<hr>
<p>Turns out, the error is not in what was being returned, but in the way I was going about parsing it. \r\n is not parsed the way I expected when put in single quotes, switching to double quotes solved my problem. I was not aware that this made a difference inside function calls like that.</p>
<p>This works just fine:<code>$cresult = split("\r\n", $cresult);</code></p>
<p>This does not: <code>$cresult = split('\r\n', $cresult);</code></p>
| [
{
"answer_id": 104750,
"author": "p4bl0",
"author_id": 12043,
"author_profile": "https://Stackoverflow.com/users/12043",
"pm_score": 0,
"selected": false,
"text": "<p>I didn't try to reproduce the \"bug\" (I think we can consider this as a bug if it is the actual behavior), but maybe you could get over it.</p>\n\n<p>The PHP Doc says that the default comportement is to write the result to a file, and that the default file is STDOUT (the browser's window). What you want is to get the same result than in a file but in a variable.</p>\n\n<p>You could do that using <code>ob_start();</code> and <code>ob_get_clean();</code>.</p>\n\n<pre><code>$ch = curl_init(...);\n// ...\nob_start();\ncurl_exec($ch);\n$yourResult = ob_get_clean();\ncurl_close($ch);\n</code></pre>\n\n<p>I know that's not really the clean way (if there is one), but at least it sould work fine.</p>\n\n<p>(Please excuse me if my english is not perfect ;-)...)</p>\n"
},
{
"answer_id": 106120,
"author": "Melikoth",
"author_id": 1536217,
"author_profile": "https://Stackoverflow.com/users/1536217",
"pm_score": 2,
"selected": true,
"text": "<p>Turns out, the error is not in what was being returned, but in the way I was going about parsing it. \\r\\n is not parsed the way I expected when put in single quotes, switching to double quotes solved my problem. I was not aware that this made a difference inside function calls like that.</p>\n\n<p>This works just fine:<code>$cresult = split(\"\\r\\n\", $cresult);</code></p>\n\n<p>This does not: <code>$cresult = split('\\r\\n', $cresult);</code></p>\n"
},
{
"answer_id": 108214,
"author": "p4bl0",
"author_id": 12043,
"author_profile": "https://Stackoverflow.com/users/12043",
"pm_score": 1,
"selected": false,
"text": "<p>In most scripting langage (it's also true in Bash for instance), simple quotes are used to represent things as they are written, whereas double quotes are \"analysed\" (i don't think it's the appropriate word but i can't find better).</p>\n\n<pre><code>$str = 'foo';\necho '$str'; // print “$str” to the screen\necho \"$str\"; // print “foo” to the screen\n</code></pre>\n\n<p>It is true for variables and escaped characters.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1536217/"
]
| I have noticed that cURL in PHP returns different data when told to output to a file via `CURLOPT_FILE` as it does when told to send the output to a string via `CURLOPT_RETURNTRANSFER`.
`_RETURNTRANSFER` seems to strip newlines and extra white space as if parsing it for display as standard HTML code. `_FILE` on the other hand preserves the file exactly as it was intended.
I have read through the documentation on php.net but haven't found anything that seems to solve my problem. Ideally, I would like to have `_RETURNTRANSFER` return the exact contents so I could eliminate an intermediate file, but I don't see any way of making this possible.
Here is the code I am using. The data in question is a CSV file with \r\n line endings.
```
function update_roster() {
$url = "http://example.com/";
$userID = "xx";
$apikey = "xxx";
$passfields = "userID=$userID&apikey=$apikey";
$file = fopen("roster.csv","w+");
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $passfields);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $file);
$variable_in_question = curl_exec ($ch);
curl_close ($ch);
fclose($file);
return $variable_in_question;
}
```
---
Turns out, the error is not in what was being returned, but in the way I was going about parsing it. \r\n is not parsed the way I expected when put in single quotes, switching to double quotes solved my problem. I was not aware that this made a difference inside function calls like that.
This works just fine:`$cresult = split("\r\n", $cresult);`
This does not: `$cresult = split('\r\n', $cresult);` | Turns out, the error is not in what was being returned, but in the way I was going about parsing it. \r\n is not parsed the way I expected when put in single quotes, switching to double quotes solved my problem. I was not aware that this made a difference inside function calls like that.
This works just fine:`$cresult = split("\r\n", $cresult);`
This does not: `$cresult = split('\r\n', $cresult);` |
104,224 | <p>I'm working on a WPF application that sometimes exhibits odd problems and appears to <em>hang</em> in the UI. It is inconsistent, it happens in different pages, but it happens often enough that it is a big problem. I should mention that it is not a true hang as described below.</p>
<p>My first thought was that the animations of some buttons was the problem since they are used on most pages, but after removing them the hangs still occur, although seemingly a bit less often. I have tried to break into the debugger when the hang occurs; however there is never any code to view. No code of mine is running. I have also noticed that the "hang" is not complete. I have code that lets me drag the form around (it has no border or title) which continues to work. I also have my won close button which functions when I click it. Clicking on buttons appears to actually work as my code runs, but the UI simply never updates to show a new page.</p>
<p>I'm looking for any advice, tools or techniques to track down this odd problem, so if you have any thoughts at all, I will greatly appreciate it.</p>
<p>EDIT: It just happened again, so this time when I tried to break into the debugger I chose to "show disassembly". It brings me to MS.Win32.UnsafeNativeMethods.GetMessageW. The stack trace follows:</p>
<pre><code>[Managed to Native Transition]
</code></pre>
<blockquote>
<p>WindowsBase.dll!MS.Win32.UnsafeNativeMethods.GetMessageW(ref System.Windows.Interop.MSG msg, System.Runtime.InteropServices.HandleRef hWnd, int uMsgFilterMin, int uMsgFilterMax) + 0x15 bytes<br>
WindowsBase.dll!System.Windows.Threading.Dispatcher.GetMessage(ref System.Windows.Interop.MSG msg, System.IntPtr hwnd, int minMessage, int maxMessage) + 0x48 bytes
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame = {System.Windows.Threading.DispatcherFrame}) + 0x8b bytes
WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes<br>
WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4c bytes<br>
PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x1e bytes<br>
PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes
PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes
PresentationFramework.dll!System.Windows.Application.Run() + 0x19 bytes
WinterGreen.exe!WinterGreen.App.Main() + 0x5e bytes C#
[Native to Managed Transition]<br>
[Managed to Native Transition]<br>
mscorlib.dll!System.AppDomain.nExecuteAssembly(System.Reflection.Assembly assembly, string[] args) + 0x19 bytes
mscorlib.dll!System.Runtime.Hosting.ManifestRunner.Run(bool checkAptModel) + 0x6e bytes
mscorlib.dll!System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly() + 0x84 bytes
mscorlib.dll!System.Runtime.Hosting.ApplicationActivator.CreateInstance(System.ActivationContext activationContext, string[] activationCustomData) + 0x65 bytes
mscorlib.dll!System.Runtime.Hosting.ApplicationActivator.CreateInstance(System.ActivationContext activationContext) + 0xa bytes
mscorlib.dll!System.Activator.CreateInstance(System.ActivationContext activationContext) + 0x3e bytes<br>
Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone() + 0x23 bytes<br>
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x66 bytes<br>
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x6f bytes<br>
mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x44 bytes </p>
</blockquote>
| [
{
"answer_id": 104272,
"author": "Bob King",
"author_id": 6897,
"author_profile": "https://Stackoverflow.com/users/6897",
"pm_score": 4,
"selected": true,
"text": "<p>Try removing the borderless behavior of your window and see if that helps. Also, are you BeginInvoke()'ing or Invoke()'ing any long running operations?</p>\n\n<p>Another thing to look at: When you break into your code, try looking at threads other than your main thread. One of them may be blocking the UI thread.</p>\n"
},
{
"answer_id": 104275,
"author": "Rob",
"author_id": 18505,
"author_profile": "https://Stackoverflow.com/users/18505",
"pm_score": 2,
"selected": false,
"text": "<p>One great tool is <a href=\"http://blois.us/Snoop/\" rel=\"nofollow noreferrer\">Snoop</a>. Really nice for looking at what WPF objects are displayed on the visual tree at a given time. I'm not sure how much it will help, but it's possible you're jamming the UI thread with a lot of extra things it has to do. Snoop may be able to help you track down what is on the screen to give you an idea what to look for.</p>\n"
},
{
"answer_id": 104306,
"author": "Alan Le",
"author_id": 1133,
"author_profile": "https://Stackoverflow.com/users/1133",
"pm_score": 3,
"selected": false,
"text": "<p>Your WPF app could be hanging due to performance issues. Try using <a href=\"http://msdn.microsoft.com/en-us/library/aa969767.aspx\" rel=\"noreferrer\">Perforator</a> to see if you have any parts that are software rendered or if you app is using too much video ram.</p>\n"
},
{
"answer_id": 116167,
"author": "palehorse",
"author_id": 312,
"author_profile": "https://Stackoverflow.com/users/312",
"pm_score": 2,
"selected": false,
"text": "<p>I have removed the borderless behavior as suggested by Bob King. To date, that seems to have gotten rid of the problem.</p>\n\n<p>Now the question is, why and how can I fix the issue? The product is designed to have no border with some rounded corners and transparent parts.</p>\n"
},
{
"answer_id": 1908286,
"author": "EightyOne Unite",
"author_id": 5559,
"author_profile": "https://Stackoverflow.com/users/5559",
"pm_score": 1,
"selected": false,
"text": "<p>Hurrah,... it seems that the problem isn't related to borderless windows (at least in my case).</p>\n\n<p>There is a big performance hit when you set <code>AllowsTransparency</code> to true. So much of a hit it would seem, that the whole thing can hang the UI thread. Very strange behaviour. Could be related to <a href=\"http://support.microsoft.com/kb/937106\" rel=\"nofollow noreferrer\">this ticket</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104224",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/312/"
]
| I'm working on a WPF application that sometimes exhibits odd problems and appears to *hang* in the UI. It is inconsistent, it happens in different pages, but it happens often enough that it is a big problem. I should mention that it is not a true hang as described below.
My first thought was that the animations of some buttons was the problem since they are used on most pages, but after removing them the hangs still occur, although seemingly a bit less often. I have tried to break into the debugger when the hang occurs; however there is never any code to view. No code of mine is running. I have also noticed that the "hang" is not complete. I have code that lets me drag the form around (it has no border or title) which continues to work. I also have my won close button which functions when I click it. Clicking on buttons appears to actually work as my code runs, but the UI simply never updates to show a new page.
I'm looking for any advice, tools or techniques to track down this odd problem, so if you have any thoughts at all, I will greatly appreciate it.
EDIT: It just happened again, so this time when I tried to break into the debugger I chose to "show disassembly". It brings me to MS.Win32.UnsafeNativeMethods.GetMessageW. The stack trace follows:
```
[Managed to Native Transition]
```
>
> WindowsBase.dll!MS.Win32.UnsafeNativeMethods.GetMessageW(ref System.Windows.Interop.MSG msg, System.Runtime.InteropServices.HandleRef hWnd, int uMsgFilterMin, int uMsgFilterMax) + 0x15 bytes
>
> WindowsBase.dll!System.Windows.Threading.Dispatcher.GetMessage(ref System.Windows.Interop.MSG msg, System.IntPtr hwnd, int minMessage, int maxMessage) + 0x48 bytes
> WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrameImpl(System.Windows.Threading.DispatcherFrame frame = {System.Windows.Threading.DispatcherFrame}) + 0x8b bytes
> WindowsBase.dll!System.Windows.Threading.Dispatcher.PushFrame(System.Windows.Threading.DispatcherFrame frame) + 0x49 bytes
>
> WindowsBase.dll!System.Windows.Threading.Dispatcher.Run() + 0x4c bytes
>
> PresentationFramework.dll!System.Windows.Application.RunDispatcher(object ignore) + 0x1e bytes
>
> PresentationFramework.dll!System.Windows.Application.RunInternal(System.Windows.Window window) + 0x6f bytes
> PresentationFramework.dll!System.Windows.Application.Run(System.Windows.Window window) + 0x26 bytes
> PresentationFramework.dll!System.Windows.Application.Run() + 0x19 bytes
> WinterGreen.exe!WinterGreen.App.Main() + 0x5e bytes C#
> [Native to Managed Transition]
>
> [Managed to Native Transition]
>
> mscorlib.dll!System.AppDomain.nExecuteAssembly(System.Reflection.Assembly assembly, string[] args) + 0x19 bytes
> mscorlib.dll!System.Runtime.Hosting.ManifestRunner.Run(bool checkAptModel) + 0x6e bytes
> mscorlib.dll!System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly() + 0x84 bytes
> mscorlib.dll!System.Runtime.Hosting.ApplicationActivator.CreateInstance(System.ActivationContext activationContext, string[] activationCustomData) + 0x65 bytes
> mscorlib.dll!System.Runtime.Hosting.ApplicationActivator.CreateInstance(System.ActivationContext activationContext) + 0xa bytes
> mscorlib.dll!System.Activator.CreateInstance(System.ActivationContext activationContext) + 0x3e bytes
>
> Microsoft.VisualStudio.HostingProcess.Utilities.dll!Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone() + 0x23 bytes
>
> mscorlib.dll!System.Threading.ThreadHelper.ThreadStart\_Context(object state) + 0x66 bytes
>
> mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x6f bytes
>
> mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x44 bytes
>
>
> | Try removing the borderless behavior of your window and see if that helps. Also, are you BeginInvoke()'ing or Invoke()'ing any long running operations?
Another thing to look at: When you break into your code, try looking at threads other than your main thread. One of them may be blocking the UI thread. |
104,230 | <p>Situation: A PHP application with multiple installable modules creates a new table in database for each, in the style of mod_A, mod_B, mod_C etc. Each has the column section_id.</p>
<p>Now, I am looking for all entries for a specific section_id, and I'm hoping there's another way besides "Select * from mod_a, mod_b, mod_c ... mod_xyzzy where section_id=value"... or even worse, using a separate query for each module.</p>
| [
{
"answer_id": 104257,
"author": "borjab",
"author_id": 16206,
"author_profile": "https://Stackoverflow.com/users/16206",
"pm_score": 1,
"selected": false,
"text": "<p>What about?</p>\n\n<pre><code>SELECT * FROM mod_a WHERE section_id=value\nUNION ALL\nSELECT * FROM mod_b WHERE section_id=value\nUNION ALL\nSELECT * FROM mod_c WHERE section_id=value\n</code></pre>\n"
},
{
"answer_id": 104278,
"author": "neuroguy123",
"author_id": 12529,
"author_profile": "https://Stackoverflow.com/users/12529",
"pm_score": 0,
"selected": false,
"text": "<p>I was going to suggest the same think as borjab. The only problem with that is that you will have to update all of these queries if you add another table. The only other option I see is a stored procedure.</p>\n\n<p>I did think of another option here, or at least an easier way to present this. You can also use a view to these multiple tables to make them appear as one, and then your query would look cleaner, be easier to understand and you wouldn't have to rewrite a long union query when you wanted to do other queries on these multiple tables.</p>\n"
},
{
"answer_id": 104301,
"author": "µBio",
"author_id": 9796,
"author_profile": "https://Stackoverflow.com/users/9796",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps some additional info would help, but it sounds like you have the solution already. You will have to select from all the tables with a section_id. You could use joins instead of a table list, joining on section_id. For example</p>\n\n<pre><code>select a.some_field, b.some_field.... \nfrom mod_a a\ninner join mod_b b on a.section_id = b.section_id\n...\nwhere a.section_id = <parameter>\n</code></pre>\n\n<p>You could also package this up as a view.\nAlso notice the field list instead of *, which I would recommend if you were intending to actually use *.</p>\n"
},
{
"answer_id": 104318,
"author": "Wes P",
"author_id": 13611,
"author_profile": "https://Stackoverflow.com/users/13611",
"pm_score": 0,
"selected": false,
"text": "<p>Well, there are only so many ways to aggregate information from multiple tables. You can join, like you mentioned in your example, or you can run multiple queries and union them together as in borjab's answer. I don't know if some idea of creating a table that intersects all the module tables would be useful to you, but if section_id was on a table like that you'd be able to get everything from a single query. Otherwise, I applaud your laziness, but am afraid to say, I don't see any way to make that job eaiser :)</p>\n"
},
{
"answer_id": 104515,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 2,
"selected": true,
"text": "<p>If the tables are changing over time, you can inline code gen your solution in an SP (pseudo code - you'll have to fill in):</p>\n\n<pre><code>SET @sql = ''\n\nDECLARE CURSOR FOR\nSELECT t.[name] AS TABLE_NAME\nFROM sys.tables t\nWHERE t.[name] LIKE 'SOME_PATTERN_TO_IDENTIFY_THE_TABLES'\n</code></pre>\n\n<p>-- or this</p>\n\n<pre><code>DECLARE CURSOR FOR\nSELECT t.[name] AS TABLE_NAME\nFROM TABLE_OF_TABLES_TO_SEACRH t\n\nSTART LOOP\n\nIF @sql <> '' SET @sql = @sql + 'UNION ALL '\nSET @sql = 'SELECT * FROM [' + @TABLE_NAME + '] WHERE section_id=value '\n\nEND LOOP\n\nEXEC(@sql)\n</code></pre>\n\n<p>I've used this technique occasionally, when there just isn't any obvious way to make it future-proof without dynamic SQL.</p>\n\n<p>Note: In your loop, you can use the COALESCE/NULL propagation trick and leave the string as NULL before the loop, but it's not as clear if you are unfamiliar with the idiom:</p>\n\n<pre><code>SET @sql = COALESCE(@sql + ' UNION ALL ', '')\n + 'SELECT * FROM [' + @TABLE_NAME + '] WHERE section_id=value '\n</code></pre>\n"
},
{
"answer_id": 104623,
"author": "Lloyd",
"author_id": 9952,
"author_profile": "https://Stackoverflow.com/users/9952",
"pm_score": 1,
"selected": false,
"text": "<p>I have two suggestions.</p>\n\n<ol>\n<li><p>Perhaps you need to consolidate all your tables. If they all contain the same structure, then why not have one \"master\" module table, that just adds one new column identifying the module (\"A\", \"B\", \"C\", ....)</p>\n\n<p>If your module tables are mostly the same, but you have a few columns that are different, you might still be able to consolidate all the common information into one table, and keep smaller module-specific tables with those differences. Then you would just need to do a join on them.</p>\n\n<p>This suggestion assumes that your query on the column section_id you mention is super-critical to look up quickly. With one query you get all the common information, and with a second you would get any specific information if you needed it. (And you might not -- for instance if you were trying to validate the existense of the section, then finding it in the common table would be enough)</p></li>\n<li><p>Alternatively you can add another table that maps section_id's to the modules that they are in.</p>\n\n<pre>\nsection_id | module\n-----------+-------\n 1 | A\n 2 | B\n 3 | A\n ... | ...\n</pre>\n\n<p>This does mean though that you have to run two queries, one against this mapping table, and another against the module table to pull out any useful data.</p>\n\n<p>You can extend this table with other columns and indices on those columns if you need to look up other columns that are common to all modules.</p>\n\n<p>This method has the definite disadvanage that the data is duplicated.</p></li>\n</ol>\n"
},
{
"answer_id": 105870,
"author": "dummy",
"author_id": 6297,
"author_profile": "https://Stackoverflow.com/users/6297",
"pm_score": 0,
"selected": false,
"text": "<pre><code>SELECT * FROM (\n SELECT * FROM table1\n UNION ALL\n SELECT * FROM table2\n UNION ALL\n SELECT * FROM table3\n) subQry\nWHERE field=value\n</code></pre>\n"
},
{
"answer_id": 105994,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 0,
"selected": false,
"text": "<p>An option from the database side would be to create a view of the UNION ALL of the various tables. When you add a table, you would need to add it to the view, but otherwise it would look like a single table.</p>\n\n<pre><code>CREATE VIEW modules AS (\n SELECT * FROM mod_A\n UNION ALL \n SELECT * FROM mod_B\n UNION ALL \n SELECT * FROM mod_C\n);\n\nselect * from modules where section_id=value;\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4224/"
]
| Situation: A PHP application with multiple installable modules creates a new table in database for each, in the style of mod\_A, mod\_B, mod\_C etc. Each has the column section\_id.
Now, I am looking for all entries for a specific section\_id, and I'm hoping there's another way besides "Select \* from mod\_a, mod\_b, mod\_c ... mod\_xyzzy where section\_id=value"... or even worse, using a separate query for each module. | If the tables are changing over time, you can inline code gen your solution in an SP (pseudo code - you'll have to fill in):
```
SET @sql = ''
DECLARE CURSOR FOR
SELECT t.[name] AS TABLE_NAME
FROM sys.tables t
WHERE t.[name] LIKE 'SOME_PATTERN_TO_IDENTIFY_THE_TABLES'
```
-- or this
```
DECLARE CURSOR FOR
SELECT t.[name] AS TABLE_NAME
FROM TABLE_OF_TABLES_TO_SEACRH t
START LOOP
IF @sql <> '' SET @sql = @sql + 'UNION ALL '
SET @sql = 'SELECT * FROM [' + @TABLE_NAME + '] WHERE section_id=value '
END LOOP
EXEC(@sql)
```
I've used this technique occasionally, when there just isn't any obvious way to make it future-proof without dynamic SQL.
Note: In your loop, you can use the COALESCE/NULL propagation trick and leave the string as NULL before the loop, but it's not as clear if you are unfamiliar with the idiom:
```
SET @sql = COALESCE(@sql + ' UNION ALL ', '')
+ 'SELECT * FROM [' + @TABLE_NAME + '] WHERE section_id=value '
``` |
104,235 | <p>What is the syntax and which namespace/class needs to be imported? Give me sample code if possible. It would be of great help.</p>
| [
{
"answer_id": 104262,
"author": "MagicKat",
"author_id": 8505,
"author_profile": "https://Stackoverflow.com/users/8505",
"pm_score": 5,
"selected": false,
"text": "<p>Put the following where you need it:</p>\n\n<pre><code>System.Diagnostics.Debugger.Break();\n</code></pre>\n"
},
{
"answer_id": 104263,
"author": "Quintin Robinson",
"author_id": 12707,
"author_profile": "https://Stackoverflow.com/users/12707",
"pm_score": 2,
"selected": false,
"text": "<p>You can use <code>System.Diagnostics.Debugger.Break()</code> to break in a specific place. This can help in situations like debugging a service.</p>\n"
},
{
"answer_id": 104268,
"author": "John Hoven",
"author_id": 1907,
"author_profile": "https://Stackoverflow.com/users/1907",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.debugger.break#System_Diagnostics_Debugger_Break\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.debugger.break#System_Diagnostics_Debugger_Break</a></p>\n<pre><code>#if DEBUG\n System.Diagnostics.Debugger.Break();\n#endif\n</code></pre>\n"
},
{
"answer_id": 105599,
"author": "Philip Rieck",
"author_id": 12643,
"author_profile": "https://Stackoverflow.com/users/12643",
"pm_score": 5,
"selected": false,
"text": "<p>I also like to check to see if the debugger is attached - if you call Debugger.Break when there is no debugger, it will prompt the user if they want to attach one. Depending on the behavior you want, you may want to call Debugger.Break() only if (or if not) one is already attached</p>\n\n<pre><code>using System.Diagnostics;\n\n//.... in the method:\n\nif( Debugger.IsAttached) //or if(!Debugger.IsAttached)\n{\n Debugger.Break();\n}\n</code></pre>\n"
},
{
"answer_id": 36127453,
"author": "CAD bloke",
"author_id": 492,
"author_profile": "https://Stackoverflow.com/users/492",
"pm_score": 2,
"selected": false,
"text": "<p>The answers from @Philip Rieck and @John are subtly different. </p>\n\n<p>John's ...\n</p>\n\n<pre><code>#if DEBUG\n System.Diagnostics.Debugger.Break();\n#endif\n</code></pre>\n\n<p>only works if you compiled with the DEBUG conditional compilation symbol set.</p>\n\n<p>Phillip's answer ...\n</p>\n\n<pre><code>if( Debugger.IsAttached) //or if(!Debugger.IsAttached)\n{\n Debugger.Break();\n}\n</code></pre>\n\n<p>will work for any debugger so you will give any hackers a bit of a fright too.</p>\n\n<p>Also take note of <code>SecurityException</code> it can throw so don't let that code out into the wild.</p>\n\n<p>Another reason no to ... </p>\n\n<blockquote>\n <p>If no debugger is attached, users are asked if they want to attach a\n debugger. If users say yes, the debugger is started. If a debugger is\n attached, the debugger is signaled with a user breakpoint event, and\n the debugger suspends execution of the process just as if a debugger\n breakpoint had been hit.</p>\n</blockquote>\n\n<p>from <a href=\"https://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.break(v=vs.110).aspx\" rel=\"nofollow\">https://msdn.microsoft.com/en-us/library/system.diagnostics.debugger.break(v=vs.110).aspx</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104235",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13432/"
]
| What is the syntax and which namespace/class needs to be imported? Give me sample code if possible. It would be of great help. | Put the following where you need it:
```
System.Diagnostics.Debugger.Break();
``` |
104,238 | <p>I'm having an issue with my regex.</p>
<p>I want to capture <% some stuff %> and i need what's inside the <% and the %></p>
<p>This regex works quite well for that.</p>
<pre><code>$matches = preg_split("/<%[\s]*(.*?)[\s]*%>/i",$markup,-1,(PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE));
</code></pre>
<p>I also want to catch <code>&amp;% some stuff %&amp;gt;</code> so I need to capture <code><% or &amp;lt;% and %> or %&amp;gt;</code> respectively. </p>
<p>If I put in a second set of parens, it makes preg_split function differently (because as you can see from the flag, I'm trying to capture what's inside the parens.</p>
<p>Preferably, it would only match <code>&amp;lt; to &amp;gt; and < to ></code> as well, but that's not completely necessary</p>
<p>EDIT: The SUBJECT may contain multiple matches, and I need all of them</p>
| [
{
"answer_id": 104295,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 4,
"selected": true,
"text": "<p>In your case, it's better to use preg_match with its additional parameter and parenthesis:</p>\n\n<pre><code>preg_match(\"#((?:<|&lt;)%)([\\s]*(?:[^ø]*)[\\s]*?)(%(?:>|&gt;))#i\",$markup, $out);\nprint_r($out);\n\nArray\n(\n [0] => <% your stuff %>\n [1] => <%\n [2] => your stuff\n [3] => %>\n)\n</code></pre>\n\n<p>By the way, check this online tool to debug PHP regexp, it's so useful !</p>\n\n<p><a href=\"http://regex.larsolavtorvik.com/\" rel=\"nofollow noreferrer\">http://regex.larsolavtorvik.com/</a></p>\n\n<p>EDIT : I hacked the regexp a bit so it's faster. Tested it, it works :-)</p>\n\n<p>Now let's explain all that stuff :</p>\n\n<ul>\n<li>preg_match will store everything he captures in the var passed as third param (here $out)</li>\n<li>if preg_match matches something, it will be store in $out[0]</li>\n<li>anything that is inside () but not (?:) in the pattern will be stored in $out</li>\n</ul>\n\n<p>The patten in details :</p>\n\n<pre><code>#((?:<|&lt;)%)([\\s]*(?:[^ø]*)[\\s]*?)(%(?:>|&gt;))#i can be viewed as ((?:<|&lt;)%) + ([\\s]*(?:[^ø]*)[\\s]*?) + (%(?:>|&gt;)).\n\n((?:<|&lt;)%) is capturing < or &lt; then %\n(%(?:>|&gt;)) is capturing % then < or &gt; \n([\\s]*(?:[^ø]*)[\\s]*?) means 0 or more spaces, then 0 or more times anything that is not the ø symbol, the 0 or more spaces.\n</code></pre>\n\n<p>Why do we use [^ø] instead of . ? It's because . is very time consuming, the regexp engine will check among all the existing characters. [^ø] just check if the char is not ø. Nobody uses ø, it's an international money symbol, but if you care, you can replace it by chr(7) wich is the shell bell char that's obviously will never be typed in a web page.</p>\n\n<p>EDIT2 : I just read your edit about capturing all the matches. In that case, you´ll use preg_match_all the same way.</p>\n"
},
{
"answer_id": 104315,
"author": "Issac Kelly",
"author_id": 144,
"author_profile": "https://Stackoverflow.com/users/144",
"pm_score": 0,
"selected": false,
"text": "<p>One possible solution is to use the extra parens, like so, but to ditch those in the results, so you actually only <em>use</em> 1/2 of the total restults.</p>\n\n<p>this regex</p>\n\n<pre><code>$matches = preg_split(\"/(<|&lt;)%[\\s]*(.*?)[\\s]*%(>|&gt;)/i\",$markup,-1,(PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE));\n</code></pre>\n\n<p>for input</p>\n\n<pre><code>Hi my name is <h1>Issac</h1><% some stuff %>here&lt;% more stuff %&gt; \n</code></pre>\n\n<p>output would be</p>\n\n<pre><code>Array(\n [0]=>Hi my name is <h1>Issac</h1>\n [1]=><\n [2]=>some stuff\n [3]=>>\n [4]=>here\n [5]=>&;lt;\n [6]=>more stuff\n [7]=>&gt;\n)\n</code></pre>\n\n<p>Which would give the desired resutls, if I only used the even numbers</p>\n"
},
{
"answer_id": 104324,
"author": "Tegan Mulholland",
"author_id": 16431,
"author_profile": "https://Stackoverflow.com/users/16431",
"pm_score": 1,
"selected": false,
"text": "<p>Why are you using <code>preg_split</code> if what you really want is what matches inside the parentheses? Seems like it would be simpler to just use <code>preg_match</code>.</p>\n\n<p>It's often an issue with regex that parens are used both for grouping your logic and for capturing patterns.</p>\n\n<p>According to the PHP doc on regex syntax,</p>\n\n<blockquote>\n <p>The fact that plain parentheses fulfil two functions is not always helpful. There are often times when a grouping subpattern is required without a capturing requirement. If an opening parenthesis is followed by \"?:\", the subpattern does not do any capturing, and is not counted when computing the number of any subsequent capturing subpatterns.</p>\n</blockquote>\n"
},
{
"answer_id": 104358,
"author": "Lasar",
"author_id": 9438,
"author_profile": "https://Stackoverflow.com/users/9438",
"pm_score": 2,
"selected": false,
"text": "<pre><code><?php\n$code = 'Here is a <% test %> and &lt;% another test %&gt; for you';\npreg_match_all('/(<|&lt;)%\\s*(.*?)\\s*%(>|&gt;)/', $code, $matches);\nprint_r($matches[2]);\n?>\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>Array\n(\n [0] => test\n [1] => another test\n)\n</code></pre>\n"
},
{
"answer_id": 104422,
"author": "user19087",
"author_id": 19087,
"author_profile": "https://Stackoverflow.com/users/19087",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to match, give <code>preg_match_all</code> a shot with a <strong><em>regular expression</em></strong> like this:</p>\n\n<pre><code>preg_match_all('/((\\<\\%)(\\s)(.*?)(\\s)(\\%\\>))/i', '<% wtf %> <% sadfdsafds %>', $result);\n</code></pre>\n\n<p>This results in a match of just about everything under the sun. You can add/remove parens to match more/less:</p>\n\n<pre><code>Array\n(\n [0] => Array\n (\n [0] => <% wtf %>\n [1] => <% sadfdsafds %>\n )\n\n[1] => Array\n (\n [0] => <% wtf %>\n [1] => <% sadfdsafds %>\n )\n\n[2] => Array\n (\n [0] => <%\n [1] => <%\n )\n\n[3] => Array\n (\n [0] => \n [1] => \n )\n\n[4] => Array\n (\n [0] => wtf\n [1] => sadfdsafds\n )\n\n[5] => Array\n (\n [0] => \n [1] => \n )\n\n[6] => Array\n (\n [0] => %>\n [1] => %>\n )\n\n)\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104238",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/144/"
]
| I'm having an issue with my regex.
I want to capture <% some stuff %> and i need what's inside the <% and the %>
This regex works quite well for that.
```
$matches = preg_split("/<%[\s]*(.*?)[\s]*%>/i",$markup,-1,(PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE));
```
I also want to catch `&% some stuff %&gt;` so I need to capture `<% or &lt;% and %> or %&gt;` respectively.
If I put in a second set of parens, it makes preg\_split function differently (because as you can see from the flag, I'm trying to capture what's inside the parens.
Preferably, it would only match `&lt; to &gt; and < to >` as well, but that's not completely necessary
EDIT: The SUBJECT may contain multiple matches, and I need all of them | In your case, it's better to use preg\_match with its additional parameter and parenthesis:
```
preg_match("#((?:<|<)%)([\s]*(?:[^ø]*)[\s]*?)(%(?:>|>))#i",$markup, $out);
print_r($out);
Array
(
[0] => <% your stuff %>
[1] => <%
[2] => your stuff
[3] => %>
)
```
By the way, check this online tool to debug PHP regexp, it's so useful !
<http://regex.larsolavtorvik.com/>
EDIT : I hacked the regexp a bit so it's faster. Tested it, it works :-)
Now let's explain all that stuff :
* preg\_match will store everything he captures in the var passed as third param (here $out)
* if preg\_match matches something, it will be store in $out[0]
* anything that is inside () but not (?:) in the pattern will be stored in $out
The patten in details :
```
#((?:<|<)%)([\s]*(?:[^ø]*)[\s]*?)(%(?:>|>))#i can be viewed as ((?:<|<)%) + ([\s]*(?:[^ø]*)[\s]*?) + (%(?:>|>)).
((?:<|<)%) is capturing < or < then %
(%(?:>|>)) is capturing % then < or >
([\s]*(?:[^ø]*)[\s]*?) means 0 or more spaces, then 0 or more times anything that is not the ø symbol, the 0 or more spaces.
```
Why do we use [^ø] instead of . ? It's because . is very time consuming, the regexp engine will check among all the existing characters. [^ø] just check if the char is not ø. Nobody uses ø, it's an international money symbol, but if you care, you can replace it by chr(7) wich is the shell bell char that's obviously will never be typed in a web page.
EDIT2 : I just read your edit about capturing all the matches. In that case, you´ll use preg\_match\_all the same way. |
104,254 | <p>I use the Eclipse IDE to develop, compile, and run my Java projects. Today, I'm trying to use the <code>java.io.Console</code> class to manage output and, more importantly, user input.</p>
<p>The problem is that <code>System.console()</code> returns <code>null</code> when an application is run "through" Eclipse. Eclipse run the program on a background process, rather than a top-level process with the console window we're familiar with.</p>
<p>Is there a way to force Eclipse to run the program as a top level process, or at least create a Console that the JVM will recognize? Otherwise, I'm forced to jar the project up and run on a command-line environment external to Eclipse.</p>
| [
{
"answer_id": 104391,
"author": "perimosocordiae",
"author_id": 10601,
"author_profile": "https://Stackoverflow.com/users/10601",
"pm_score": 2,
"selected": false,
"text": "<p>As far as I can tell, there is no way to get a Console object from Eclipse. I'd just make sure that console != null, then JAR it up and run it from the command line.</p>\n"
},
{
"answer_id": 104412,
"author": "Heath Borders",
"author_id": 9636,
"author_profile": "https://Stackoverflow.com/users/9636",
"pm_score": 3,
"selected": false,
"text": "<p>The reason this occurs is because eclipse runs your app as a background process and not as a top-level process with a system console. </p>\n"
},
{
"answer_id": 104473,
"author": "John Gardner",
"author_id": 13687,
"author_profile": "https://Stackoverflow.com/users/13687",
"pm_score": 2,
"selected": false,
"text": "<p>Found something about this at <a href=\"http://www.stupidjavatricks.com/?p=43\" rel=\"nofollow noreferrer\">http://www.stupidjavatricks.com/?p=43</a> .</p>\n\n<p>And sadly, since console is final, you can't extend it to create a a wrapper around system.in and system.out that does it either. Even inside the eclipse console you still have access to those. Thats probably why eclipse hasn't plugged this into their console yet...</p>\n\n<p>I understand why you wouldn't want to have any other way to get a console other than System.console, with no setter, but i don't understand why you wouldn't want someone to be able to override the class to make a mock/testing console... </p>\n"
},
{
"answer_id": 104533,
"author": "Ross",
"author_id": 19147,
"author_profile": "https://Stackoverflow.com/users/19147",
"pm_score": 1,
"selected": false,
"text": "<p>There seems to be no way to get a java.io.Console object when running an application through Eclipse. A command-line console window is not opened with the application, as it is run as a background process (background to Eclipse?). Currently, there is no Eclipse plugin to handle this issue, mainly due to the fact that java.io.Console is a final class.</p>\n\n<p>All you can really do is test the returned Console object for null and proceed from there.</p>\n"
},
{
"answer_id": 105403,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 7,
"selected": true,
"text": "<p>I assume you want to be able to use step-through debugging from Eclipse. You can just run the classes externally by setting the built classes in the bin directories on the JRE classpath.</p>\n\n<pre><code>java -cp workspace\\p1\\bin;workspace\\p2\\bin foo.Main\n</code></pre>\n\n<p>You can debug using the remote debugger and taking advantage of the class files built in your project.</p>\n\n<p>In this example, the Eclipse project structure looks like this:</p>\n\n<pre><code>workspace\\project\\\n \\.classpath\n \\.project\n \\debug.bat\n \\bin\\Main.class\n \\src\\Main.java\n</code></pre>\n\n<p><strong>1. Start the JVM Console in Debug Mode</strong></p>\n\n<p><strong>debug.bat</strong> is a Windows batch file that should be run externally from a <strong>cmd.exe</strong> console.</p>\n\n<pre><code>@ECHO OFF\nSET A_PORT=8787\nSET A_DBG=-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=%A_PORT%,server=y,suspend=y\njava.exe %A_DBG% -cp .\\bin Main\n</code></pre>\n\n<p>In the arguments, the debug port has been set to <em>8787</em>. The <em>suspend=y</em> argument tells the JVM to wait until the debugger attaches.</p>\n\n<p><strong>2. Create a Debug Launch Configuration</strong></p>\n\n<p>In Eclipse, open the Debug dialog (Run > Open Debug Dialog...) and create a new <strong>Remote Java Application</strong> configuration with the following settings:</p>\n\n<ul>\n<li><em>Project:</em> your project name</li>\n<li><em>Connection Type:</em> Standard (Socket Attach)</li>\n<li><em>Host:</em> localhost</li>\n<li><em>Port:</em> 8787</li>\n</ul>\n\n<p><strong>3. Debugging</strong></p>\n\n<p>So, all you have to do any time you want to debug the app is:</p>\n\n<ul>\n<li>set a break point</li>\n<li>launch the batch file in a console</li>\n<li>launch the debug configuration</li>\n</ul>\n\n<hr>\n\n<p>You can track this issue in <a href=\"https://bugs.eclipse.org/bugs/show_bug.cgi?id=122429\" rel=\"noreferrer\">bug 122429</a>. You can work round this issue in your application by using an abstraction layer as described <a href=\"http://illegalargumentexception.blogspot.com/2010/09/java-systemconsole-ides-and-testing.html\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 4491872,
"author": "Laplie Anderson",
"author_id": 14204,
"author_profile": "https://Stackoverflow.com/users/14204",
"pm_score": 5,
"selected": false,
"text": "<p>The workaround that I use is to just use System.in/System.out instead of Console when using Eclipse. For example, instead of:</p>\n\n<pre><code>String line = System.console().readLine();\n</code></pre>\n\n<p>You can use:</p>\n\n<pre><code>BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));\nString line = bufferedReader.readLine();\n</code></pre>\n"
},
{
"answer_id": 11431299,
"author": "Dave Richardson",
"author_id": 847553,
"author_profile": "https://Stackoverflow.com/users/847553",
"pm_score": 1,
"selected": false,
"text": "<p>This <a href=\"http://www.xyzws.com/Javafaq/how-to-read-input-from-console-keyboard-in-java/195\" rel=\"nofollow\">link</a> offers alternatives to using System.console(). One is to use a BufferedReader wrapped around System.in, the second is to use a Scanner wrapped around System.in. </p>\n\n<p>Neither are as concise as console, but both work in eclipse without having to resort to debug silliness!</p>\n"
},
{
"answer_id": 11998803,
"author": "binarycube",
"author_id": 765546,
"author_profile": "https://Stackoverflow.com/users/765546",
"pm_score": 2,
"selected": false,
"text": "<p>Another option is to create a method to wrap up both options, and \"fail over\" to the System.in method when Console isn't available. The below example is a fairly basic one - you can follow the same process to wrap up the other methods in Console (readPassword, format) as required. That way you can run it happily in Eclipse & when its deployed you get the Console features (e.g. password hiding) kicking in.</p>\n\n<pre><code> private static String readLine(String prompt) {\n String line = null;\n Console c = System.console();\n if (c != null) {\n line = c.readLine(prompt);\n } else {\n System.out.print(prompt);\n BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));\n try {\n line = bufferedReader.readLine();\n } catch (IOException e) { \n //Ignore \n }\n }\n return line;\n }\n</code></pre>\n"
},
{
"answer_id": 15539444,
"author": "yztaoj",
"author_id": 2193610,
"author_profile": "https://Stackoverflow.com/users/2193610",
"pm_score": 3,
"selected": false,
"text": "<p>You can implement a class yourself. Following is an example:</p>\n\n<pre><code>public class Console {\n BufferedReader br;\n PrintStream ps;\n\n public Console(){\n br = new BufferedReader(new InputStreamReader(System.in));\n ps = System.out;\n }\n\n public String readLine(String out){\n ps.format(out);\n try{\n return br.readLine();\n }catch(IOException e)\n {\n return null;\n }\n }\n public PrintStream format(String format, Object...objects){\n return ps.format(format, objects);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 42139447,
"author": "Paulo Merson",
"author_id": 317522,
"author_profile": "https://Stackoverflow.com/users/317522",
"pm_score": 0,
"selected": false,
"text": "<p>Let's say your Eclipse workspace is C:\\MyWorkspace, \nyou created your java application inside a maven project MyProject, \nand your Java main class is com.mydomain.mypackage.MyClass.</p>\n\n<p>In this case, you can run your main class that uses <code>System.console()</code> on the command line:</p>\n\n<pre><code>java -cp C:\\MyWorkspace\\MyProject\\target\\classes com.mydomain.mypackage.MyClass\n</code></pre>\n\n<p>NB1: if it's not in a maven project, check the output folder in project properties | Java Build Path | Source. It might not be \"target/classes\"</p>\n\n<p>NB2: if it is a maven project, but your class is in src/test/java, you'll likely have to use \"target\\test-classes\" instead of \"target\\classes\"</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104254",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19147/"
]
| I use the Eclipse IDE to develop, compile, and run my Java projects. Today, I'm trying to use the `java.io.Console` class to manage output and, more importantly, user input.
The problem is that `System.console()` returns `null` when an application is run "through" Eclipse. Eclipse run the program on a background process, rather than a top-level process with the console window we're familiar with.
Is there a way to force Eclipse to run the program as a top level process, or at least create a Console that the JVM will recognize? Otherwise, I'm forced to jar the project up and run on a command-line environment external to Eclipse. | I assume you want to be able to use step-through debugging from Eclipse. You can just run the classes externally by setting the built classes in the bin directories on the JRE classpath.
```
java -cp workspace\p1\bin;workspace\p2\bin foo.Main
```
You can debug using the remote debugger and taking advantage of the class files built in your project.
In this example, the Eclipse project structure looks like this:
```
workspace\project\
\.classpath
\.project
\debug.bat
\bin\Main.class
\src\Main.java
```
**1. Start the JVM Console in Debug Mode**
**debug.bat** is a Windows batch file that should be run externally from a **cmd.exe** console.
```
@ECHO OFF
SET A_PORT=8787
SET A_DBG=-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,address=%A_PORT%,server=y,suspend=y
java.exe %A_DBG% -cp .\bin Main
```
In the arguments, the debug port has been set to *8787*. The *suspend=y* argument tells the JVM to wait until the debugger attaches.
**2. Create a Debug Launch Configuration**
In Eclipse, open the Debug dialog (Run > Open Debug Dialog...) and create a new **Remote Java Application** configuration with the following settings:
* *Project:* your project name
* *Connection Type:* Standard (Socket Attach)
* *Host:* localhost
* *Port:* 8787
**3. Debugging**
So, all you have to do any time you want to debug the app is:
* set a break point
* launch the batch file in a console
* launch the debug configuration
---
You can track this issue in [bug 122429](https://bugs.eclipse.org/bugs/show_bug.cgi?id=122429). You can work round this issue in your application by using an abstraction layer as described [here](http://illegalargumentexception.blogspot.com/2010/09/java-systemconsole-ides-and-testing.html). |
104,267 | <p>in short: <strong>is there any way to find the current directory full path of a xul application?</strong></p>
<p>long explanation:</p>
<p>I would like to open some html files in a xul browser application. The path to the html files should be set programmatically from the xul application. The html files reside outside the folder of my xul application, but at the same level. (users will checkout both folders from SVN, no installation available for the xul app)</p>
<p>It opened the files just fine if I set a full path like "file:///c:\temp\processing-sample\index.html"</p>
<p>what i want to do is to open the file relative to my xul application. </p>
<p>I found i can open the user's profile path:</p>
<pre><code>var DIR_SERVICE = new Components.Constructor("@mozilla.org/file/directory_service;1", "nsIProperties");
var path = (new DIR_SERVICE()).get("UChrm", Components.interfaces.nsIFile).path;
var appletPath;
// find directory separator type
if (path.search(/\\/) != -1)
{
appletPath = path + "\\myApp\\content\\applet.html"
}
else
{
appletPath = path + "/myApp/content/applet.html"
}
// Cargar el applet en el iframe
var appletFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
appletFile.initWithPath(appletPath);
var appletURL = Components.classes["@mozilla.org/network/protocol;1?name=file"].createInstance(Components.interfaces.nsIFileProtocolHandler).getURLSpecFromFile(appletFile);
var appletFrame = document.getElementById("appletFrame");
appletFrame.setAttribute("src", appletURL);
</code></pre>
<p><strong>is there any way to find the current directory full path of a xul application?</strong></p>
| [
{
"answer_id": 104950,
"author": "rec",
"author_id": 14022,
"author_profile": "https://Stackoverflow.com/users/14022",
"pm_score": 3,
"selected": true,
"text": "<p>I found a workaround: <a href=\"http://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO\" rel=\"nofollow noreferrer\">http://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO</a> i cannot exactly open a file using a relative path \"../../index.html\" but i can get the app directory and work with that. </p>\n\n<pre><code>var DIR_SERVICE = new Components.Constructor(\"@mozilla.org/file/directory_service;1\", \"nsIProperties\");\nvar path = (new DIR_SERVICE()).get(resource:app, Components.interfaces.nsIFile).path;\nvar appletPath;\n</code></pre>\n"
},
{
"answer_id": 107205,
"author": "pc1oad1etter",
"author_id": 525,
"author_profile": "https://Stackoverflow.com/users/525",
"pm_score": 0,
"selected": false,
"text": "<p>In a xul application, you can access the chrome folder of the application using a chrome url. </p>\n\n<p>I have relatively little experience with the element , so I'm not sure if this will work exactly for you. It is the way you include javascript source files in your xul file:</p>\n\n<pre><code><script src=\"chrome://includes/content/XSLTemplate.js\" type=\"application/x-javascript\"/>\n</code></pre>\n\n<p>So, perhaps if the file resides at c:\\applicationFolder\\chrome\\content\\index.html , you can access it at:</p>\n\n<pre><code>chrome://content/index.html \n</code></pre>\n\n<p>in some fashion.</p>\n\n<p>You may also look at <a href=\"http://jslib.mozdev.org/libraries/io/dir.js.html\" rel=\"nofollow noreferrer\">jslib</a>, a library that simplifies a lot of things, including file i/o. IIRC, I had trouble getting to a relative path using '../', though.</p>\n"
},
{
"answer_id": 584662,
"author": "bizzy",
"author_id": 48797,
"author_profile": "https://Stackoverflow.com/users/48797",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, html files within your extension can be addressed using chrome URIs.\nAn example from one of my extensions:</p>\n\n<pre><code>content.document.location.href = \"chrome://{appname}/content/logManager/index.html\"\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14022/"
]
| in short: **is there any way to find the current directory full path of a xul application?**
long explanation:
I would like to open some html files in a xul browser application. The path to the html files should be set programmatically from the xul application. The html files reside outside the folder of my xul application, but at the same level. (users will checkout both folders from SVN, no installation available for the xul app)
It opened the files just fine if I set a full path like "file:///c:\temp\processing-sample\index.html"
what i want to do is to open the file relative to my xul application.
I found i can open the user's profile path:
```
var DIR_SERVICE = new Components.Constructor("@mozilla.org/file/directory_service;1", "nsIProperties");
var path = (new DIR_SERVICE()).get("UChrm", Components.interfaces.nsIFile).path;
var appletPath;
// find directory separator type
if (path.search(/\\/) != -1)
{
appletPath = path + "\\myApp\\content\\applet.html"
}
else
{
appletPath = path + "/myApp/content/applet.html"
}
// Cargar el applet en el iframe
var appletFile = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
appletFile.initWithPath(appletPath);
var appletURL = Components.classes["@mozilla.org/network/protocol;1?name=file"].createInstance(Components.interfaces.nsIFileProtocolHandler).getURLSpecFromFile(appletFile);
var appletFrame = document.getElementById("appletFrame");
appletFrame.setAttribute("src", appletURL);
```
**is there any way to find the current directory full path of a xul application?** | I found a workaround: <http://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO> i cannot exactly open a file using a relative path "../../index.html" but i can get the app directory and work with that.
```
var DIR_SERVICE = new Components.Constructor("@mozilla.org/file/directory_service;1", "nsIProperties");
var path = (new DIR_SERVICE()).get(resource:app, Components.interfaces.nsIFile).path;
var appletPath;
``` |
104,292 | <p>I'm getting the following error when trying to build my app using Team Foundation Build:</p>
<blockquote>
<p>C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets(1682,9): error MSB3554: Cannot write to the output file "obj\Release\Company.Redacted.BlahBlah.Localization.Subsystems.
Startup_Shutdown_Processing.StartupShutdownProcessingMessages.de.resources". The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.</p>
</blockquote>
<p>My project builds fine on my development machine as the source is only two folders deep, but TF Build seems to use a really deep directory that is causing it to break. How do I change the folders that are used?</p>
<p><strong>Edit:</strong> I checked the .proj file for my build that is stored in source control and found the following:</p>
<pre><code><!-- BUILD DIRECTORY
This property is included only for backwards compatibility. The build directory used for a build
definition is now stored in the database, as the BuildDirectory property of the definition's
DefaultBuildAgent. For compatibility with V1 clients, keep this property in sync with the value
in the database.
-->
<BuildDirectoryPath>UNKNOWN</BuildDirectoryPath>
</code></pre>
<p>If this is stored in the database how do I change it?</p>
<p><strong>Edit:</strong> Found the following blog post which may be pointing me torward the solution. Now I just need to figure out how to change the setting in the Build Agent. <a href="http://blogs.msdn.com/jpricket/archive/2007/04/30/build-type-builddirectorypath-build-agent-working-directory.aspx" rel="noreferrer">http://blogs.msdn.com/jpricket/archive/2007/04/30/build-type-builddirectorypath-build-agent-working-directory.aspx</a></p>
<p>Currently my working directory is "$(Temp)\$(BuildDefinitionPath)" but now I don't know what wildcards are available to specify a different folder.</p>
| [
{
"answer_id": 104302,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": 0,
"selected": false,
"text": "<p>you have to checkout the build script file, from the source control explorer, and get your elbows dirty replacing the path.</p>\n"
},
{
"answer_id": 104506,
"author": "Martin Woodward",
"author_id": 6438,
"author_profile": "https://Stackoverflow.com/users/6438",
"pm_score": 5,
"selected": true,
"text": "<p>You need to edit the build working directory of your Build Agent so that the begging path is a little smaller. To edit the build agent, right click on the \"Builds\" node and select \"Manage Build Agents...\"</p>\n\n<p>I personally use something like c:\\bw\\$(BuildDefinitionId). $(BuildDefinitionId) translates into the id of the build definition (hence the name :-) ), which means you get a build path starting with something like c:\\bw\\36 rather than c:\\Documents and Settings\\tfsbuild\\Local Settings\\Temp\\BuildDefinitionName</p>\n\n<p>Good luck,</p>\n\n<p>Martin.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/327/"
]
| I'm getting the following error when trying to build my app using Team Foundation Build:
>
> C:\WINDOWS\Microsoft.NET\Framework\v3.5\Microsoft.Common.targets(1682,9): error MSB3554: Cannot write to the output file "obj\Release\Company.Redacted.BlahBlah.Localization.Subsystems.
> Startup\_Shutdown\_Processing.StartupShutdownProcessingMessages.de.resources". The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
>
>
>
My project builds fine on my development machine as the source is only two folders deep, but TF Build seems to use a really deep directory that is causing it to break. How do I change the folders that are used?
**Edit:** I checked the .proj file for my build that is stored in source control and found the following:
```
<!-- BUILD DIRECTORY
This property is included only for backwards compatibility. The build directory used for a build
definition is now stored in the database, as the BuildDirectory property of the definition's
DefaultBuildAgent. For compatibility with V1 clients, keep this property in sync with the value
in the database.
-->
<BuildDirectoryPath>UNKNOWN</BuildDirectoryPath>
```
If this is stored in the database how do I change it?
**Edit:** Found the following blog post which may be pointing me torward the solution. Now I just need to figure out how to change the setting in the Build Agent. <http://blogs.msdn.com/jpricket/archive/2007/04/30/build-type-builddirectorypath-build-agent-working-directory.aspx>
Currently my working directory is "$(Temp)\$(BuildDefinitionPath)" but now I don't know what wildcards are available to specify a different folder. | You need to edit the build working directory of your Build Agent so that the begging path is a little smaller. To edit the build agent, right click on the "Builds" node and select "Manage Build Agents..."
I personally use something like c:\bw\$(BuildDefinitionId). $(BuildDefinitionId) translates into the id of the build definition (hence the name :-) ), which means you get a build path starting with something like c:\bw\36 rather than c:\Documents and Settings\tfsbuild\Local Settings\Temp\BuildDefinitionName
Good luck,
Martin. |
104,293 | <p>I'm getting a 404 error when trying to run another web service on an IIS 6 server which is also running Sharepoint 2003. I'm pretty sure this is an issue with sharepoint taking over IIS configuration. Is there a way to make a certain web service or web site be ignored by whatever Sharepoint is doing?</p>
| [
{
"answer_id": 104340,
"author": "kemiller2002",
"author_id": 1942,
"author_profile": "https://Stackoverflow.com/users/1942",
"pm_score": 0,
"selected": false,
"text": "<p>you'll have to go into the SharePoint admin console and explicitely allow that web application to run on on the same web site as SharePoint. </p>\n\n<p>I believe it is under defined managed paths.</p>\n\n<p>Central Administration > Application Management > Define Managed Paths</p>\n"
},
{
"answer_id": 104410,
"author": "Stimy",
"author_id": 8852,
"author_profile": "https://Stackoverflow.com/users/8852",
"pm_score": 3,
"selected": true,
"text": "<p>I found the command line solution.</p>\n\n<pre><code>STSADM.EXE -o addpath -url http://localhost/<your web service/app> -type exclusion\n</code></pre>\n"
},
{
"answer_id": 105624,
"author": "spdevsolutions",
"author_id": 19086,
"author_profile": "https://Stackoverflow.com/users/19086",
"pm_score": 1,
"selected": false,
"text": "<p>I depends on what you mean by side by side, if you are trying to make something inside the same URL path as sharepoint then the above answers about managed paths should do it for you, but there is also nothing stopping you from just creating another Web Site inside of IIS, sharepoint will only take over the requests coming to its specific web.</p>\n"
},
{
"answer_id": 113105,
"author": "Daniel O",
"author_id": 697,
"author_profile": "https://Stackoverflow.com/users/697",
"pm_score": 0,
"selected": false,
"text": "<p>Hasn't this change from 2003 to 2007? There's no longer an excluded paths option.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8852/"
]
| I'm getting a 404 error when trying to run another web service on an IIS 6 server which is also running Sharepoint 2003. I'm pretty sure this is an issue with sharepoint taking over IIS configuration. Is there a way to make a certain web service or web site be ignored by whatever Sharepoint is doing? | I found the command line solution.
```
STSADM.EXE -o addpath -url http://localhost/<your web service/app> -type exclusion
``` |
104,322 | <p>How do you install Boost on MacOS?
Right now I can't find bjam for the Mac.</p>
| [
{
"answer_id": 104389,
"author": "dies",
"author_id": 19170,
"author_profile": "https://Stackoverflow.com/users/19170",
"pm_score": 8,
"selected": true,
"text": "<p>Download <a href=\"https://www.macports.org/\" rel=\"noreferrer\">MacPorts</a>, and run the following command:</p>\n\n<pre><code>sudo port install boost \n</code></pre>\n"
},
{
"answer_id": 104396,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 2,
"selected": false,
"text": "<p>you can download bjam for OSX (or any other OS) <a href=\"http://sourceforge.net/project/showfiles.php?group_id=7586&package_id=72941\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 104647,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 3,
"selected": false,
"text": "<p><A href=\"http://www.finkproject.org/\" rel=\"noreferrer\">Fink</a> appears to have a full set of Boost packages...</p>\n\n<p>With fink installed and running just do</p>\n\n<pre><code>fink install boost1.35.nopython\n</code></pre>\n\n<p>at the terminal and accept the dependencies it insists on. Or use</p>\n\n<pre><code>fink list boost\n</code></pre>\n\n<p>to get a list of different packages that are availible.</p>\n"
},
{
"answer_id": 283968,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Unless your compiler is different than the one supplied with the Mac XCode Dev tools, just follow the instructions in section 5.1 of <a href=\"http://www.boost.org/more/getting_started/unix-variants.html\" rel=\"nofollow noreferrer\">Getting Started Guide for Unix Variants</a>. The configuration and building of the latest source couldn't be easier, and it took all about about 1 minute to configure and 10 minutes to compile. </p>\n"
},
{
"answer_id": 9196677,
"author": "jrwren",
"author_id": 16998,
"author_profile": "https://Stackoverflow.com/users/16998",
"pm_score": 8,
"selected": false,
"text": "<p>You can get the latest version of Boost by using <a href=\"http://brew.sh/\" rel=\"noreferrer\">Homebrew</a>.</p>\n<p><code>brew install boost</code>.</p>\n"
},
{
"answer_id": 11297605,
"author": "snies",
"author_id": 262822,
"author_profile": "https://Stackoverflow.com/users/262822",
"pm_score": 7,
"selected": false,
"text": "<p>Just get the source, and compile Boost yourself; it has become very easy. Here is an example for the current version of Boost on the current macOS as of this writing:</p>\n\n<ol>\n<li>Download the the .tar.gz from <a href=\"https://www.boost.org/users/download/#live\" rel=\"noreferrer\">https://www.boost.org/users/download/#live</a></li>\n<li><p>Unpack and go into the directory:<pre><code>tar -xzf boost_1_50_0.tar.gz\ncd boost_1_50_0</code></pre></p></li>\n<li><p>Configure (and build <code>bjam</code>):</p>\n\n<pre><code>./bootstrap.sh --prefix=/some/dir/you/would/like/to/prefix</code></pre></li>\n<li><p>Build:</p>\n\n<pre><code>./b2</code></pre></li>\n<li><p>Install:<pre><code>./b2 install</code></pre></p></li>\n</ol>\n\n<p>Depending on the prefix you choose in Step 3, you might need to sudo Step 5, if the script tries copy files to a protected location.</p>\n"
},
{
"answer_id": 26300596,
"author": "user1823890",
"author_id": 1823890,
"author_profile": "https://Stackoverflow.com/users/1823890",
"pm_score": 2,
"selected": false,
"text": "<p>In order to avoid troubles compiling third party libraries that need boost installed in your system, run this:</p>\n\n<pre><code>sudo port install boost +universal\n</code></pre>\n"
},
{
"answer_id": 33039805,
"author": "Kondal Rao",
"author_id": 2364482,
"author_profile": "https://Stackoverflow.com/users/2364482",
"pm_score": 3,
"selected": false,
"text": "<p>Install both of them using homebrew separately.</p>\n\n<blockquote>\n <p>brew install boost <br/>\n brew install bjam</p>\n</blockquote>\n"
},
{
"answer_id": 36657597,
"author": "Jacksonkr",
"author_id": 332578,
"author_profile": "https://Stackoverflow.com/users/332578",
"pm_score": 2,
"selected": false,
"text": "<h1>Try <code>+universal</code></h1>\n<p>One thing to note: in order for that to make a difference you need to have built <code>python</code> with <code>+universal</code>, if you haven't or you're not sure you can just rebuild <code>python +universal</code>. This applies to both <strong>brew</strong> as well as <strong>macports</strong>.</p>\n<pre><code>$ brew reinstall python\n$ brew install boost\n</code></pre>\n<p>OR</p>\n<pre><code>$ sudo port -f uninstall python\n$ sudo port install python +universal\n$ sudo port install boost +universal\n</code></pre>\n"
},
{
"answer_id": 54735125,
"author": "UDAY JAIN",
"author_id": 11072474,
"author_profile": "https://Stackoverflow.com/users/11072474",
"pm_score": 3,
"selected": false,
"text": "<p>Install Xcode from the mac app store.\nThen use the command:</p>\n\n<pre><code> /usr/bin/ruby -e \"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)\"\n</code></pre>\n\n<p>the above will install homebrew and allow you to use brew in terminal</p>\n\n<p>then just use command :</p>\n\n<pre><code>brew install boost\n</code></pre>\n\n<p>which would then install the boost libraries to <code><your macusername>/usr/local/Cellar/boost</code></p>\n"
},
{
"answer_id": 65501748,
"author": "Neo li",
"author_id": 7000846,
"author_profile": "https://Stackoverflow.com/users/7000846",
"pm_score": 2,
"selected": false,
"text": "<p>If you are too lazy like me:\n<code>conda install -c conda-forge boost</code></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15124/"
]
| How do you install Boost on MacOS?
Right now I can't find bjam for the Mac. | Download [MacPorts](https://www.macports.org/), and run the following command:
```
sudo port install boost
``` |
104,323 | <p>I am quite new to JavaScript libraries. I wanted to replace my current code with jQuery. My current code looks like this:</p>
<pre><code>var req;
function createRequest() {
var key = document.getElementById("key");
var keypressed = document.getElementById("keypressed");
keypressed.value = key.value;
var url = "/My_Servlet/response?key=" + escape(key.value);
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("Get", url, true);
req.onreadystatechange = callback;
req.send(null);
}
function callback() {
if (req.readyState == 4) {
if (req.status == 200) {
var decimal = document.getElementById('decimal');
decimal.value = req.responseText;
}
}
clear();
}
</code></pre>
<p>I wanted to replace my code with something a little friendlier like jQuery's</p>
<pre><code>$.get(url, callback);
</code></pre>
<p>However it doesn't call my callback function.</p>
<p>Also I would like to call a function called <code>createRequest</code> continuously. Does jQuery have a nice way of doing that?
</p>
| [
{
"answer_id": 104343,
"author": "Wes P",
"author_id": 13611,
"author_profile": "https://Stackoverflow.com/users/13611",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think jQuery implements a timeout function, but plain old javascript does it rather nicely :)</p>\n"
},
{
"answer_id": 104347,
"author": "ceejayoz",
"author_id": 1902010,
"author_profile": "https://Stackoverflow.com/users/1902010",
"pm_score": 2,
"selected": false,
"text": "<p>According to <a href=\"http://docs.jquery.com/Ajax/jQuery.get\" rel=\"nofollow noreferrer\">the docs</a>, jQuery.get's arguments are <code>url, data, callback</code>, not <code>url, callback</code>.</p>\n\n<p>A call to JavaScript's setTimeout function at the end of your callback function should suffice to get this to continually execute.</p>\n"
},
{
"answer_id": 104408,
"author": "Lasar",
"author_id": 9438,
"author_profile": "https://Stackoverflow.com/users/9438",
"pm_score": 4,
"selected": false,
"text": "<pre><code>$.get(url, {}, callback);\n</code></pre>\n\n<p>should do the trick. Your callback could be simplified like this:</p>\n\n<pre><code>function callback(content){\n $('#decimal').val(content);\n}\n</code></pre>\n\n<p>Or even shorter:</p>\n\n<pre><code>$.get(url, {}, function(content){\n $('#decimal').val(content);\n});\n</code></pre>\n\n<p>And all in all I think this should work:</p>\n\n<pre><code>function createRequest() {\n var keyValue = $('#key').val();\n $('#keypressed').val(keyValue);\n var url = \"/My_Servlet/response\";\n $.get(url, {key: keyValue}, function(content){\n $('#decimal').val(content);\n });\n}\n</code></pre>\n"
},
{
"answer_id": 104432,
"author": "Jim",
"author_id": 8427,
"author_profile": "https://Stackoverflow.com/users/8427",
"pm_score": 2,
"selected": false,
"text": "<p>Take out the readyState and status checks. jQuery only calls your callback upon success. Your callback is supplied the arguments <code>(data, textStatus)</code>, so you should use <code>data</code> instead of <code>req.responseText</code>.</p>\n\n<p><code>window.setTimeout()</code> as suggested by another answer won't do what you want - that only waits and then calls your function once. You need to use <code>window.setInterval()</code> instead, which will call your function periodically until you cancel it.</p>\n\n<p>So, in summary:</p>\n\n<pre><code>var interval = 500; /* Milliseconds between requests. */\nwindow.setInterval(function() {\n var val = $(\"#key\").val();\n $(\"#keypressed\").val(val);\n $.get(\"/My_Servlet/response\", { \"key\": val }, function(data, textStatus) {\n $(\"#decimal\").val(data);\n });\n}), interval);\n</code></pre>\n"
},
{
"answer_id": 104452,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 2,
"selected": false,
"text": "<p>There's no need to set the GET parameters on the URL, jQuery will set them automatically. Try this code:</p>\n\n<pre><code>var key = document.getElementById(\"key\");\n[...]\nvar url = \"/My_Servlet/response\";\n$.get (url, {'key': key}, function (responseText)\n{\n var decimal = document.getElementById ('decimal'); \n decimal.value = responseText;\n});\n</code></pre>\n"
},
{
"answer_id": 105635,
"author": "Bernie Perez",
"author_id": 1992,
"author_profile": "https://Stackoverflow.com/users/1992",
"pm_score": 0,
"selected": false,
"text": "<p>In the end I guess it was added the type. This seems to work for me.</p>\n\n<pre><code> function convertToDecimal(){ \n var key = document.getElementById(\"key\"); \n var keypressed = document.getElementById(\"keypressed\"); \n keypressed.value = key.value; \n var url = \"/My_Servlet/response?key=\"+ escape(key.value);\n jQuery.get(url, {}, function(data){\n callback(data);}\n , \"text\" );\n }\n\n function callback(data){\n var decimal = document.getElementById('decimal');\n decimal.value = data;\n clear();\n }\n</code></pre>\n\n<p>Thanks Everyone for the help. I'll vote you up.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I am quite new to JavaScript libraries. I wanted to replace my current code with jQuery. My current code looks like this:
```
var req;
function createRequest() {
var key = document.getElementById("key");
var keypressed = document.getElementById("keypressed");
keypressed.value = key.value;
var url = "/My_Servlet/response?key=" + escape(key.value);
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("Get", url, true);
req.onreadystatechange = callback;
req.send(null);
}
function callback() {
if (req.readyState == 4) {
if (req.status == 200) {
var decimal = document.getElementById('decimal');
decimal.value = req.responseText;
}
}
clear();
}
```
I wanted to replace my code with something a little friendlier like jQuery's
```
$.get(url, callback);
```
However it doesn't call my callback function.
Also I would like to call a function called `createRequest` continuously. Does jQuery have a nice way of doing that?
| ```
$.get(url, {}, callback);
```
should do the trick. Your callback could be simplified like this:
```
function callback(content){
$('#decimal').val(content);
}
```
Or even shorter:
```
$.get(url, {}, function(content){
$('#decimal').val(content);
});
```
And all in all I think this should work:
```
function createRequest() {
var keyValue = $('#key').val();
$('#keypressed').val(keyValue);
var url = "/My_Servlet/response";
$.get(url, {key: keyValue}, function(content){
$('#decimal').val(content);
});
}
``` |
104,330 | <p>I have a table with a "Date" column, and I would like to do a query that does the following:</p>
<p>If the date is a <strong>Monday</strong>, <strong>Tuesday</strong>, <strong>Wednesday</strong>, or <strong>Thursday</strong>, the displayed date should be shifted up by 1 day, as in <pre>DATEADD(day, 1, [Date])</pre> On the other hand, if it is a <strong>Friday</strong>, the displayed date should be incremented by 3 days (i.e. so it becomes the following <em>Monday</em>).</p>
<p>How do I do this in my SELECT statement? As in,</p>
<pre>SELECT somewayofdoingthis([Date]) FROM myTable</pre>
<p>(This is SQL Server 2000.)</p>
| [
{
"answer_id": 104357,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>you need to create a SQL Function that does this transformation for you. </p>\n"
},
{
"answer_id": 104362,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 1,
"selected": false,
"text": "<p>Sounds like a CASE expression. I don't know the proper data manipulations for SQL Server, but basically it would look like this:</p>\n\n<pre><code>CASE\n WHEN [Date] is a Friday THEN DATEADD( day, 3, [Date] )\n ELSE DATEADD( day, 1, [Date] )\nEND\n</code></pre>\n\n<p>If you wanted to check for weekend days you could add additional WHEN clauses before the ELSE.</p>\n"
},
{
"answer_id": 104384,
"author": "Rob Allen",
"author_id": 149,
"author_profile": "https://Stackoverflow.com/users/149",
"pm_score": 1,
"selected": false,
"text": "<p>This is off the top of my head and can be clearly cleaned up but use it as a starting point:</p>\n\n<pre><code>select case when DATENAME(dw, [date]) = 'Monday' then DATEADD(dw, 1, [Date])\n when DATENAME(dw, [date]) = 'Tuesday' then DATEADD(dw, 1, [Date])\n when DATENAME(dw, [date]) = 'Wednesday' then DATEADD(dw, 1, [Date])\n when DATENAME(dw, [date]) = 'Thursday' then DATEADD(dw, 1, [Date])\n when DATENAME(dw, [date]) = 'Friday' then DATEADD(dw, 3, [Date])\n end as nextDay\n ...\n</code></pre>\n"
},
{
"answer_id": 104385,
"author": "JustinD",
"author_id": 12063,
"author_profile": "https://Stackoverflow.com/users/12063",
"pm_score": 1,
"selected": false,
"text": "<p>you could use this:</p>\n\n<pre><code>select dayname,newdayname =\n CASE dayname\n WHEN 'Monday' THEN 'Tuesday'\n WHEN 'Tuesday' THEN 'Wednesday'\n WHEN 'Wednesday' THEN 'Thursday'\n WHEN 'Thursday' THEN 'Friday'\n WHEN 'Friday' THEN 'Monday'\n WHEN 'Saturday' THEN 'Monday'\n WHEN 'Sunday' THEN 'Monday'\nEND\nFROM UDO_DAYS\n</code></pre>\n\n<pre>\nresults:\nMonday Tuesday\nTuesday Wednesday\nWednesday Thursday\nThursday Friday\nFriday Monday\nSaturday Monday\nSunday Monday\n\ntable data:\nMonday\nTuesday\nWednesday\nThursday\nFriday\nSaturday\nSunday\n</pre>\n"
},
{
"answer_id": 104386,
"author": "K Richard",
"author_id": 16771,
"author_profile": "https://Stackoverflow.com/users/16771",
"pm_score": 4,
"selected": true,
"text": "<p>Here is how I would do it. I do recommend a function like above if you will be using this in other places.</p>\n\n<pre><code>CASE\nWHEN\n DATEPART(dw, [Date]) IN (2,3,4,5)\nTHEN\n DATEADD(d, 1, [Date])\nWHEN\n DATEPART(dw, [Date]) = 6\nTHEN\n DATEADD(d, 3, [Date])\nELSE\n [Date]\nEND AS [ConvertedDate]\n</code></pre>\n"
},
{
"answer_id": 104390,
"author": "Brian",
"author_id": 2831,
"author_profile": "https://Stackoverflow.com/users/2831",
"pm_score": 2,
"selected": false,
"text": "<pre><code>CREATE FUNCTION dbo.GetNextWDay(@Day datetime)\nRETURNS DATETIME\nAS\nBEGIN \n DECLARE @ReturnDate DateTime\n\n set @ReturnDate = dateadd(dd, 1, @Day)\n\n if (select datename(@ReturnDate))) = 'Saturday'\n set @ReturnDate = dateadd(dd, 2, @ReturnDate)\n\n if (select datename(@ReturnDate) = 'Sunday'\n set @ReturnDate = dateadd(dd, 1, @ReturnDate)\n\n RETURN @ReturnDate\nEND\n</code></pre>\n"
},
{
"answer_id": 104397,
"author": "Mark",
"author_id": 9303,
"author_profile": "https://Stackoverflow.com/users/9303",
"pm_score": 1,
"selected": false,
"text": "<p>Look up the CASE statement and the DATEPART statement. You will want to use the dw argument with DATEPART to get back an integer that represents the day of week.</p>\n"
},
{
"answer_id": 104399,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 2,
"selected": false,
"text": "<p>Try</p>\n\n<pre><code>select case when datepart(dw,[Date]) between 2 and 5 then DATEADD(dd, 1, [Date])\nwhen datepart(dw,[Date]) = 6 then DATEADD(dd, 3, [Date]) else [Date] end as [Date] \n</code></pre>\n"
},
{
"answer_id": 104428,
"author": "LeppyR64",
"author_id": 16592,
"author_profile": "https://Stackoverflow.com/users/16592",
"pm_score": -1,
"selected": false,
"text": "<pre><code>create table #dates (dt datetime)\ninsert into #dates (dt) values ('1/1/2001')\ninsert into #dates (dt) values ('1/2/2001')\ninsert into #dates (dt) values ('1/3/2001')\ninsert into #dates (dt) values ('1/4/2001')\ninsert into #dates (dt) values ('1/5/2001')\n\n select\n dt, day(dt), dateadd(dd,1,dt)\n from\n #dates\n where\n day(dt) between 1 and 4\n\n union all\n\n select\n dt, day(dt), dateadd(dd,3,dt)\n from\n #dates\n where\n day(dt) = 5\n\n drop table #dates\n</code></pre>\n"
},
{
"answer_id": 104450,
"author": "user19164",
"author_id": 19164,
"author_profile": "https://Stackoverflow.com/users/19164",
"pm_score": 2,
"selected": false,
"text": "<p>I'm assuming that you also want Saturday and Sunday to shift forward to the following Monday. If that is not the case, take the 1 out of (1,2,3,4,5) and remove the last when clause.</p>\n\n<pre><code>case\n --Sunday thru Thursday are shifted forward 1 day\n when datepart(weekday, [Date]) in (1,2,3,4,5) then dateadd(day, 1, [Date]) \n --Friday is shifted forward to Monday\n when datepart(weekday, [Date]) = 6 then dateadd(day, 3, [Date])\n --Saturday is shifted forward to Monday\n when datepart(weekday, [Date]) = 7 then dateadd(day, 2, [Date])\nend\n</code></pre>\n\n<p>You can also do it in one line:<BR></p>\n\n<pre><code>select dateadd(day, 1 + (datepart(weekday, [Date])/6) * (8-datepart(weekday, [Date])), [Date])\n</code></pre>\n"
},
{
"answer_id": 105029,
"author": "CindyH",
"author_id": 12897,
"author_profile": "https://Stackoverflow.com/users/12897",
"pm_score": 0,
"selected": false,
"text": "<p>This is mostly like Brian's except it didn't compile due to mismatched parens and I changed the IF to not have the select in it. It is important to note that we use DateNAME here rather than datePART because datePART is dependent on the value set by SET DATEFIRST, which sets the first day of the week.</p>\n\n<pre><code>CREATE FUNCTION dbo.GetNextWDay(@Day datetime)\nRETURNS DATETIME\nAS\nBEGIN\n DECLARE @ReturnDate DateTime\n\n set @ReturnDate = dateadd(dd, 1, @Day)\n if datename(dw, @ReturnDate) = 'Saturday'\n set @ReturnDate = dateadd(dd, 2, @ReturnDate)\n if datename(dw, @ReturnDate) = 'Sunday'\n set @ReturnDate = dateadd(dd, 1, @ReturnDate)\n RETURN @ReturnDate\nEND\n</code></pre>\n"
},
{
"answer_id": 105098,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>How about taking a page from the <a href=\"http://en.wikipedia.org/wiki/Data_warehouse\" rel=\"nofollow noreferrer\">Data Warehouse</a> guys and make a table. In DW terms, this would be a date dimension. A <a href=\"http://www.ipcdesigns.com/dim_date/\" rel=\"nofollow noreferrer\">standard date dimension</a> would have things like various names for a date (\"MON\", \"Monday\", \"August 22, 1998\"), or indicators like end-of-month and start-of-month. However, you can also have columns that only make sense in your environment.</p>\n\n<p>For instance, based on the question, yours might have a next-work-day column that would point to the key for the day in question. That way you can customize it further to take into account holidays or other non-working days. </p>\n\n<p>The DW folks are adamant about using meaningless keys (that is, don't just use a truncated date as the key, use a generated key), but you can decide that for yourself. </p>\n\n<p>The <a href=\"http://www.ipcdesigns.com/dim_date/\" rel=\"nofollow noreferrer\">Date Dimension Toolkit</a> has code to generate your own tables in various DBMS and it has CSV data for several years worth of dates.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104330",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10675/"
]
| I have a table with a "Date" column, and I would like to do a query that does the following:
If the date is a **Monday**, **Tuesday**, **Wednesday**, or **Thursday**, the displayed date should be shifted up by 1 day, as in
```
DATEADD(day, 1, [Date])
```
On the other hand, if it is a **Friday**, the displayed date should be incremented by 3 days (i.e. so it becomes the following *Monday*).
How do I do this in my SELECT statement? As in,
```
SELECT somewayofdoingthis([Date]) FROM myTable
```
(This is SQL Server 2000.) | Here is how I would do it. I do recommend a function like above if you will be using this in other places.
```
CASE
WHEN
DATEPART(dw, [Date]) IN (2,3,4,5)
THEN
DATEADD(d, 1, [Date])
WHEN
DATEPART(dw, [Date]) = 6
THEN
DATEADD(d, 3, [Date])
ELSE
[Date]
END AS [ConvertedDate]
``` |
104,339 | <p>I'm doing some Objective-C programming that involves parsing an NSXmlDocument and populating an objects properties from the result.</p>
<p>First version looked like this:</p>
<pre><code>if([elementName compare:@"companyName"] == 0)
[character setCorporationName:currentElementText];
else if([elementName compare:@"corporationID"] == 0)
[character setCorporationID:currentElementText];
else if([elementName compare:@"name"] == 0)
...
</code></pre>
<p>But I don't like the <code>if-else-if-else</code> pattern this produces. Looking at the <code>switch</code> statement I see that i can only handle <code>ints</code>, <code>chars</code> etc and not objects... so is there a better implementation pattern I'm not aware of?</p>
<p>BTW I did actually come up with a better solution for setting the object's properties, but I want to know specifically about the <code>if</code>-<code>else</code> vs <code>switch</code> pattern in Objective-C</p>
| [
{
"answer_id": 104584,
"author": "Bradley Harris",
"author_id": 10503,
"author_profile": "https://Stackoverflow.com/users/10503",
"pm_score": 2,
"selected": false,
"text": "<p>The most common refactoring suggested for eliminating if-else or switch statements is introducing polymorphism (see <a href=\"http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html\" rel=\"nofollow noreferrer\">http://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html</a>). Eliminating such conditionals is most important when they are duplicated. In the case of XML parsing like your sample you are essentially moving the data to a more natural structure so that you won't have to duplicate the conditional elsewhere. In this case the if-else or switch statement is probably good enough. </p>\n"
},
{
"answer_id": 104610,
"author": "Palmin",
"author_id": 5949,
"author_profile": "https://Stackoverflow.com/users/5949",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>if-else</code> implementation you have is the right way to do this, since <code>switch</code> won't work with objects. Apart from maybe being a bit harder to read (which is subjective), there is no real downside in using <code>if-else</code> statements this way. </p>\n"
},
{
"answer_id": 109702,
"author": "Barry Wark",
"author_id": 2140,
"author_profile": "https://Stackoverflow.com/users/2140",
"pm_score": 1,
"selected": false,
"text": "<p>In this case, I'm not sure if you can easily refactor the class to introduce polymorphism as Bradley suggests, since it's a Cocoa-native class. Instead, the Objective-C way to do it is to use a class category to add an <code>elementNameCode</code> method to NSSting:</p>\n\n<pre><code> typedef enum { \n companyName = 0,\n companyID, \n ...,\n Unknown\n } ElementCode;\n\n @interface NSString (ElementNameCodeAdditions)\n - (ElementCode)elementNameCode; \n @end\n\n @implementation NSString (ElementNameCodeAdditions)\n - (ElementCode)elementNameCode {\n if([self compare:@\"companyName\"]==0) {\n return companyName;\n } else if([self compare:@\"companyID\"]==0) {\n return companyID;\n } ... {\n\n }\n\n return Unknown;\n }\n @end\n</code></pre>\n\n<p>In your code, you could now use a switch on <code>[elementName elementNameCode]</code> (and gain the associated compiler warnings if you forget to test for one of the enum members etc.).</p>\n\n<p>As Bradley points out, this may not be worth it if the logic is only used in one place.</p>\n"
},
{
"answer_id": 110244,
"author": "Kendall Helmstetter Gelner",
"author_id": 6330,
"author_profile": "https://Stackoverflow.com/users/6330",
"pm_score": 2,
"selected": false,
"text": "<p>Although there's not necessarily a better way to do something like that for one time use, why use \"compare\" when you can use \"isEqualToString\"? That would seem to be more performant since the comparison would halt at the first non-matching character, rather than going through the whole thing to calculate a valid comparison result (though come to think of it the comparison might be clear at the same point) - also though it would look a little cleaner because that call returns a BOOL.</p>\n\n<pre><code>if([elementName isEqualToString:@\"companyName\"] ) \n [character setCorporationName:currentElementText]; \nelse if([elementName isEqualToString:@\"corporationID\"] ) \n [character setCorporationID:currentElementText]; \nelse if([elementName isEqualToString:@\"name\"] ) \n</code></pre>\n"
},
{
"answer_id": 110254,
"author": "jmah",
"author_id": 3948,
"author_profile": "https://Stackoverflow.com/users/3948",
"pm_score": 4,
"selected": false,
"text": "<p>You should take advantage of Key-Value Coding:</p>\n\n<pre><code>[character setValue:currentElementText forKey:elementName];\n</code></pre>\n\n<p>If the data is untrusted, you might want to check that the key is valid:</p>\n\n<pre><code>if (![validKeysCollection containsObject:elementName])\n // Exception or error\n</code></pre>\n"
},
{
"answer_id": 118361,
"author": "Brad Larson",
"author_id": 19679,
"author_profile": "https://Stackoverflow.com/users/19679",
"pm_score": 2,
"selected": false,
"text": "<p>One way I've done this with NSStrings is by using an NSDictionary and enums. It may not be the most elegant, but I think it makes the code a little more readable. The following pseudocode is extracted from <a href=\"http://sunsetlakesoftware.com/molecules\" rel=\"nofollow noreferrer\">one of my projects</a>:</p>\n\n<pre><code>typedef enum { UNKNOWNRESIDUE, DEOXYADENINE, DEOXYCYTOSINE, DEOXYGUANINE, DEOXYTHYMINE } SLSResidueType;\n\nstatic NSDictionary *pdbResidueLookupTable;\n...\n\nif (pdbResidueLookupTable == nil)\n{\n pdbResidueLookupTable = [[NSDictionary alloc] initWithObjectsAndKeys:\n [NSNumber numberWithInteger:DEOXYADENINE], @\"DA\", \n [NSNumber numberWithInteger:DEOXYCYTOSINE], @\"DC\",\n [NSNumber numberWithInteger:DEOXYGUANINE], @\"DG\",\n [NSNumber numberWithInteger:DEOXYTHYMINE], @\"DT\",\n nil]; \n}\n\nSLSResidueType residueIdentifier = [[pdbResidueLookupTable objectForKey:residueType] intValue];\nswitch (residueIdentifier)\n{\n case DEOXYADENINE: do something; break;\n case DEOXYCYTOSINE: do something; break;\n case DEOXYGUANINE: do something; break;\n case DEOXYTHYMINE: do something; break;\n}\n</code></pre>\n"
},
{
"answer_id": 138452,
"author": "Michael Buckley",
"author_id": 22540,
"author_profile": "https://Stackoverflow.com/users/22540",
"pm_score": 5,
"selected": true,
"text": "<p>I hope you'll all forgive me for going out on a limb here, but I would like to address the more general question of parsing XML documents in Cocoa without the need of if-else statements. The question as originally stated assigns the current element text to an instance variable of the character object. As jmah pointed out, this can be solved using key-value coding. However, in a more complex XML document this might not be possible. Consider for example the following.</p>\n\n<pre><code><xmlroot>\n <corporationID>\n <stockSymbol>EXAM</stockSymbol>\n <uuid>31337</uuid>\n </corporationID>\n <companyName>Example Inc.</companyName>\n</xmlroot>\n</code></pre>\n\n<p>There are multiple approaches to dealing with this. Off of the top of my head, I can think of two using NSXMLDocument. The first uses NSXMLElement. It is fairly straightforward and does not involve the if-else issue at all. You simply get the root element and go through its named elements one by one.</p>\n\n<pre><code>NSXMLElement* root = [xmlDocument rootElement];\n\n// Assuming that we only have one of each element.\n[character setCorperationName:[[[root elementsForName:@\"companyName\"] objectAtIndex:0] stringValue]];\n\nNSXMLElement* corperationId = [root elementsForName:@\"corporationID\"];\n[character setCorperationStockSymbol:[[[corperationId elementsForName:@\"stockSymbol\"] objectAtIndex:0] stringValue]];\n[character setCorperationUUID:[[[corperationId elementsForName:@\"uuid\"] objectAtIndex:0] stringValue]];\n</code></pre>\n\n<p>The next one uses the more general NSXMLNode, walks through the tree, and directly uses the if-else structure.</p>\n\n<pre><code>// The first line is the same as the last example, because NSXMLElement inherits from NSXMLNode\nNSXMLNode* aNode = [xmlDocument rootElement];\nwhile(aNode = [aNode nextNode]){\n if([[aNode name] isEqualToString:@\"companyName\"]){\n [character setCorperationName:[aNode stringValue]];\n }else if([[aNode name] isEqualToString:@\"corporationID\"]){\n NSXMLNode* correctParent = aNode;\n while((aNode = [aNode nextNode]) == nil && [aNode parent != correctParent){\n if([[aNode name] isEqualToString:@\"stockSymbol\"]){\n [character setCorperationStockSymbol:[aNode stringValue]];\n }else if([[aNode name] isEqualToString:@\"uuid\"]){\n [character setCorperationUUID:[aNode stringValue]];\n }\n }\n }\n}\n</code></pre>\n\n<p>This is a good candidate for eliminating the if-else structure, but like the original problem, we can't simply use switch-case here. However, we can still eliminate if-else by using performSelector. The first step is to define the a method for each element.</p>\n\n<pre><code>- (NSNode*)parse_companyName:(NSNode*)aNode\n{\n [character setCorperationName:[aNode stringValue]];\n return aNode;\n}\n\n- (NSNode*)parse_corporationID:(NSNode*)aNode\n{\n NSXMLNode* correctParent = aNode;\n while((aNode = [aNode nextNode]) == nil && [aNode parent != correctParent){\n [self invokeMethodForNode:aNode prefix:@\"parse_corporationID_\"];\n }\n return [aNode previousNode];\n}\n\n- (NSNode*)parse_corporationID_stockSymbol:(NSNode*)aNode\n{\n [character setCorperationStockSymbol:[aNode stringValue]];\n return aNode;\n}\n\n- (NSNode*)parse_corporationID_uuid:(NSNode*)aNode\n{\n [character setCorperationUUID:[aNode stringValue]];\n return aNode;\n}\n</code></pre>\n\n<p>The magic happens in the invokeMethodForNode:prefix: method. We generate the selector based on the name of the element, and perform that selector with aNode as the only parameter. Presto bango, we've eliminated the need for an if-else statement. Here's the code for that method.</p>\n\n<pre><code>- (NSNode*)invokeMethodForNode:(NSNode*)aNode prefix:(NSString*)aPrefix\n{\n NSNode* ret = nil;\n NSString* methodName = [NSString stringWithFormat:@\"%@%@:\", prefix, [aNode name]];\n SEL selector = NSSelectorFromString(methodName);\n if([self respondsToSelector:selector])\n ret = [self performSelector:selector withObject:aNode];\n return ret;\n}\n</code></pre>\n\n<p>Now, instead of our larger if-else statement (the one that differentiated between companyName and corporationID), we can simply write one line of code</p>\n\n<pre><code>NSXMLNode* aNode = [xmlDocument rootElement];\nwhile(aNode = [aNode nextNode]){\n aNode = [self invokeMethodForNode:aNode prefix:@\"parse_\"];\n}\n</code></pre>\n\n<p>Now I apologize if I got any of this wrong, it's been a while since I've written anything with NSXMLDocument, it's late at night and I didn't actually test this code. So if you see anything wrong, please leave a comment or edit this answer.</p>\n\n<p>However, I believe I have just shown how properly-named selectors can be used in Cocoa to completely eliminate if-else statements in cases like this. There are a few gotchas and corner cases. The performSelector: family of methods only takes 0, 1, or 2 argument methods whose arguments and return types are objects, so if the types of the arguments and return type are not objects, or if there are more than two arguments, then you would have to use an NSInvocation to invoke it. You have to make sure that the method names you generate aren't going to call other methods, especially if the target of the call is another object, and this particular method naming scheme won't work on elements with non-alphanumeric characters. You could get around that by escaping the XML element names in your method names somehow, or by building an NSDictionary using the method names as the keys and the selectors as the values. This can get pretty memory intensive and end up taking a longer time. performSelector dispatch like I described is pretty fast. For very large if-else statements, this method may even be faster than an if-else statement.</p>\n"
},
{
"answer_id": 141544,
"author": "epatel",
"author_id": 842,
"author_profile": "https://Stackoverflow.com/users/842",
"pm_score": 3,
"selected": false,
"text": "<p>Dare I suggest using a macro?</p>\n\n<pre><code>#define TEST( _name, _method ) \\\n if ([elementName isEqualToString:@ _name] ) \\\n [character _method:currentElementText]; else\n#define ENDTEST { /* empty */ }\n\nTEST( \"companyName\", setCorporationName )\nTEST( \"setCorporationID\", setCorporationID )\nTEST( \"name\", setName )\n:\n:\nENDTEST\n</code></pre>\n"
},
{
"answer_id": 142128,
"author": "Wevah",
"author_id": 14256,
"author_profile": "https://Stackoverflow.com/users/14256",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to use as little code as possible, and your element names and setters are all named so that if elementName is @\"foo\" then setter is setFoo:, you could do something like:</p>\n\n<pre><code>SEL selector = NSSelectorFromString([NSString stringWithFormat:@\"set%@:\", [elementName capitalizedString]]);\n\n[character performSelector:selector withObject:currentElementText];\n</code></pre>\n\n<p>or possibly even:</p>\n\n<pre><code>[character setValue:currentElementText forKey:elementName]; // KVC-style\n</code></pre>\n\n<p>Though these will of course be a bit slower than using a bunch of if statements.</p>\n\n<p>[Edit: The second option was already mentioned by someone; oops!]</p>\n"
},
{
"answer_id": 143203,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>There is actually a fairly simple way to deal with cascading if-else statements in a language like Objective-C. Yes, you can use subclassing and overriding, creating a group of subclasses that implement the same method differently, invoking the correct implementation at runtime using a common message. This works well if you wish to choose one of a few implementations, but it can result in a needless proliferation of subclasses if you have many small, slightly different implementations like you tend to have in long if-else or switch statements.</p>\n\n<p>Instead, factor out the body of each if/else-if clause into its own method, all in the same class. Name the messages that invoke them in a similar fashion. Now create an NSArray containing the selectors of those messages (obtained using @selector()). Coerce the string you were testing in the conditionals into a selector using NSSelectorFromString() (you may need to concatenate additional words or colons to it first depending on how you named those messages, and whether or not they take arguments). Now have self perform the selector using performSelector:.</p>\n\n<p>This approach has the downside that it can clutter-up the class with many new messages, but it's probably better to clutter-up a single class than the entire class hierarchy with new subclasses.</p>\n"
},
{
"answer_id": 262687,
"author": "Mike Shields",
"author_id": 29030,
"author_profile": "https://Stackoverflow.com/users/29030",
"pm_score": 1,
"selected": false,
"text": "<p>What we've done in our projects where we need to so this sort of thing over and over, is to set up a static CFDictionary mapping the strings/objects to check against to a simple integer value. It leads to code that looks like this:</p>\n\n<pre><code>static CFDictionaryRef map = NULL;\nint count = 3;\nconst void *keys[count] = { @\"key1\", @\"key2\", @\"key3\" };\nconst void *values[count] = { (uintptr_t)1, (uintptr_t)2, (uintptr_t)3 };\n\nif (map == NULL)\n map = CFDictionaryCreate(NULL,keys,values,count,&kCFTypeDictionaryKeyCallBacks,NULL);\n\n\nswitch((uintptr_t)CFDictionaryGetValue(map,[node name]))\n{\n case 1:\n // do something\n break;\n case 2:\n // do something else\n break;\n case 3:\n // this other thing too\n break;\n}\n</code></pre>\n\n<p>If you're targeting Leopard only, you could use an NSMapTable instead of a CFDictionary.</p>\n"
},
{
"answer_id": 1215783,
"author": "Dennis Munsie",
"author_id": 8728,
"author_profile": "https://Stackoverflow.com/users/8728",
"pm_score": 2,
"selected": false,
"text": "<p>Posting this as a response to Wevah's answer above -- I would've edited, but I don't have high enough reputation yet:</p>\n\n<p>unfortunately the first method breaks for fields with more than one word in them -- like xPosition. capitalizedString will convert that to Xposition, which when combined with the format give you setXposition: . Definitely not what was wanted here. Here is what I'm using in my code:</p>\n\n<pre><code>NSString *capName = [elementName stringByReplacingCharactersInRange:NSMakeRange(0, 1) withString:[[elementName substringToIndex:1] uppercaseString]];\nSEL selector = NSSelectorFromString([NSString stringWithFormat:@\"set%@:\", capName]);\n</code></pre>\n\n<p>Not as pretty as the first method, but it works.</p>\n"
},
{
"answer_id": 10124375,
"author": "Lvsti",
"author_id": 1117912,
"author_profile": "https://Stackoverflow.com/users/1117912",
"pm_score": 2,
"selected": false,
"text": "<p>I have come up with a solution that uses blocks to create a switch-like structure for objects. There it goes:</p>\n\n<pre><code>BOOL switch_object(id aObject, ...)\n{\n va_list args;\n va_start(args, aObject);\n\n id value = nil;\n BOOL matchFound = NO;\n\n while ( (value = va_arg(args,id)) )\n {\n void (^block)(void) = va_arg(args,id);\n if ( [aObject isEqual:value] )\n {\n block();\n matchFound = YES;\n break;\n }\n }\n\n va_end(args);\n return matchFound;\n}\n</code></pre>\n\n<p>As you can see, this is an oldschool C function with variable argument list. I pass the object to be tested in the first argument, followed by the case_value-case_block pairs. (Recall that Objective-C blocks are just objects.) The <code>while</code> loop keeps extracting these pairs until the object value is matched or there are no cases left (see notes below).</p>\n\n<p>Usage:</p>\n\n<pre><code>NSString* str = @\"stuff\";\nswitch_object(str,\n @\"blah\", ^{\n NSLog(@\"blah\");\n },\n @\"foobar\", ^{\n NSLog(@\"foobar\");\n },\n @\"stuff\", ^{\n NSLog(@\"stuff\");\n },\n @\"poing\", ^{\n NSLog(@\"poing\");\n },\n nil); // <-- sentinel\n\n// will print \"stuff\"\n</code></pre>\n\n<p>Notes:</p>\n\n<ul>\n<li>this is a first approximation without any error checking</li>\n<li>the fact that the case handlers are blocks, requires additional care when it comes to visibility, scope and memory management of variables referenced from within</li>\n<li>if you forget the sentinel, you are doomed :P</li>\n<li>you can use the boolean return value to trigger a \"default\" case when none of the cases have been matched</li>\n</ul>\n"
},
{
"answer_id": 14789501,
"author": "vikingosegundo",
"author_id": 106435,
"author_profile": "https://Stackoverflow.com/users/106435",
"pm_score": 0,
"selected": false,
"text": "<p>Similar to Lvsti I am using blocks to perform a switching pattern on objects.</p>\n\n<p>I wrote a very simple filter block based chain, that takes n filter blocks and performs each filter on the object.<br>\nEach filter can alter the object, but must return it. No matter what.</p>\n\n<p>NSObject+Functional.h</p>\n\n<pre><code>#import <Foundation/Foundation.h>\ntypedef id(^FilterBlock)(id element, NSUInteger idx, BOOL *stop);\n\n@interface NSObject (Functional)\n-(id)processByPerformingFilterBlocks:(NSArray *)filterBlocks;\n@end\n</code></pre>\n\n<p>NSObject+Functional.m</p>\n\n<pre><code>@implementation NSObject (Functional)\n-(id)processByPerformingFilterBlocks:(NSArray *)filterBlocks\n{\n __block id blockSelf = self;\n [filterBlocks enumerateObjectsUsingBlock:^( id (^block)(id,NSUInteger idx, BOOL*) , NSUInteger idx, BOOL *stop) {\n blockSelf = block(blockSelf, idx, stop);\n }];\n\n return blockSelf;\n}\n@end\n</code></pre>\n\n<p>Now we can set up <code>n</code> FilterBlocks to test for the different cases.</p>\n\n<pre><code>FilterBlock caseYES = ^id(id element, NSUInteger idx, BOOL *breakAfter){ \n if ([element isEqualToString:@\"YES\"]) { \n NSLog(@\"You did it\"); \n *breakAfter = YES;\n } \n return element;\n};\n\nFilterBlock caseNO = ^id(id element, NSUInteger idx, BOOL *breakAfter){ \n if ([element isEqualToString:@\"NO\"] ) { \n NSLog(@\"Nope\");\n *breakAfter = YES;\n }\n return element;\n};\n</code></pre>\n\n<p>Now we stick those block we want to test as a filter chain in an array:</p>\n\n<pre><code>NSArray *filters = @[caseYES, caseNO];\n</code></pre>\n\n<p>and can perform it on an object</p>\n\n<pre><code>id obj1 = @\"YES\";\nid obj2 = @\"NO\";\n[obj1 processByPerformingFilterBlocks:filters];\n[obj2 processByPerformingFilterBlocks:filters];\n</code></pre>\n\n<p>This approach can be used for switching but also for any (conditional) filter chain application, as the blocks can edit the element and pass it on.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104339",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18590/"
]
| I'm doing some Objective-C programming that involves parsing an NSXmlDocument and populating an objects properties from the result.
First version looked like this:
```
if([elementName compare:@"companyName"] == 0)
[character setCorporationName:currentElementText];
else if([elementName compare:@"corporationID"] == 0)
[character setCorporationID:currentElementText];
else if([elementName compare:@"name"] == 0)
...
```
But I don't like the `if-else-if-else` pattern this produces. Looking at the `switch` statement I see that i can only handle `ints`, `chars` etc and not objects... so is there a better implementation pattern I'm not aware of?
BTW I did actually come up with a better solution for setting the object's properties, but I want to know specifically about the `if`-`else` vs `switch` pattern in Objective-C | I hope you'll all forgive me for going out on a limb here, but I would like to address the more general question of parsing XML documents in Cocoa without the need of if-else statements. The question as originally stated assigns the current element text to an instance variable of the character object. As jmah pointed out, this can be solved using key-value coding. However, in a more complex XML document this might not be possible. Consider for example the following.
```
<xmlroot>
<corporationID>
<stockSymbol>EXAM</stockSymbol>
<uuid>31337</uuid>
</corporationID>
<companyName>Example Inc.</companyName>
</xmlroot>
```
There are multiple approaches to dealing with this. Off of the top of my head, I can think of two using NSXMLDocument. The first uses NSXMLElement. It is fairly straightforward and does not involve the if-else issue at all. You simply get the root element and go through its named elements one by one.
```
NSXMLElement* root = [xmlDocument rootElement];
// Assuming that we only have one of each element.
[character setCorperationName:[[[root elementsForName:@"companyName"] objectAtIndex:0] stringValue]];
NSXMLElement* corperationId = [root elementsForName:@"corporationID"];
[character setCorperationStockSymbol:[[[corperationId elementsForName:@"stockSymbol"] objectAtIndex:0] stringValue]];
[character setCorperationUUID:[[[corperationId elementsForName:@"uuid"] objectAtIndex:0] stringValue]];
```
The next one uses the more general NSXMLNode, walks through the tree, and directly uses the if-else structure.
```
// The first line is the same as the last example, because NSXMLElement inherits from NSXMLNode
NSXMLNode* aNode = [xmlDocument rootElement];
while(aNode = [aNode nextNode]){
if([[aNode name] isEqualToString:@"companyName"]){
[character setCorperationName:[aNode stringValue]];
}else if([[aNode name] isEqualToString:@"corporationID"]){
NSXMLNode* correctParent = aNode;
while((aNode = [aNode nextNode]) == nil && [aNode parent != correctParent){
if([[aNode name] isEqualToString:@"stockSymbol"]){
[character setCorperationStockSymbol:[aNode stringValue]];
}else if([[aNode name] isEqualToString:@"uuid"]){
[character setCorperationUUID:[aNode stringValue]];
}
}
}
}
```
This is a good candidate for eliminating the if-else structure, but like the original problem, we can't simply use switch-case here. However, we can still eliminate if-else by using performSelector. The first step is to define the a method for each element.
```
- (NSNode*)parse_companyName:(NSNode*)aNode
{
[character setCorperationName:[aNode stringValue]];
return aNode;
}
- (NSNode*)parse_corporationID:(NSNode*)aNode
{
NSXMLNode* correctParent = aNode;
while((aNode = [aNode nextNode]) == nil && [aNode parent != correctParent){
[self invokeMethodForNode:aNode prefix:@"parse_corporationID_"];
}
return [aNode previousNode];
}
- (NSNode*)parse_corporationID_stockSymbol:(NSNode*)aNode
{
[character setCorperationStockSymbol:[aNode stringValue]];
return aNode;
}
- (NSNode*)parse_corporationID_uuid:(NSNode*)aNode
{
[character setCorperationUUID:[aNode stringValue]];
return aNode;
}
```
The magic happens in the invokeMethodForNode:prefix: method. We generate the selector based on the name of the element, and perform that selector with aNode as the only parameter. Presto bango, we've eliminated the need for an if-else statement. Here's the code for that method.
```
- (NSNode*)invokeMethodForNode:(NSNode*)aNode prefix:(NSString*)aPrefix
{
NSNode* ret = nil;
NSString* methodName = [NSString stringWithFormat:@"%@%@:", prefix, [aNode name]];
SEL selector = NSSelectorFromString(methodName);
if([self respondsToSelector:selector])
ret = [self performSelector:selector withObject:aNode];
return ret;
}
```
Now, instead of our larger if-else statement (the one that differentiated between companyName and corporationID), we can simply write one line of code
```
NSXMLNode* aNode = [xmlDocument rootElement];
while(aNode = [aNode nextNode]){
aNode = [self invokeMethodForNode:aNode prefix:@"parse_"];
}
```
Now I apologize if I got any of this wrong, it's been a while since I've written anything with NSXMLDocument, it's late at night and I didn't actually test this code. So if you see anything wrong, please leave a comment or edit this answer.
However, I believe I have just shown how properly-named selectors can be used in Cocoa to completely eliminate if-else statements in cases like this. There are a few gotchas and corner cases. The performSelector: family of methods only takes 0, 1, or 2 argument methods whose arguments and return types are objects, so if the types of the arguments and return type are not objects, or if there are more than two arguments, then you would have to use an NSInvocation to invoke it. You have to make sure that the method names you generate aren't going to call other methods, especially if the target of the call is another object, and this particular method naming scheme won't work on elements with non-alphanumeric characters. You could get around that by escaping the XML element names in your method names somehow, or by building an NSDictionary using the method names as the keys and the selectors as the values. This can get pretty memory intensive and end up taking a longer time. performSelector dispatch like I described is pretty fast. For very large if-else statements, this method may even be faster than an if-else statement. |
104,363 | <p>I'm trying to upgrade a package using yum on Fedora 8. The package is <code>elfutils</code>. Here's what I have installed locally:</p>
<pre><code>$ yum info elfutils
Installed Packages
Name : elfutils
Arch : x86_64
Version: 0.130
Release: 3.fc8
Size : 436 k
Repo : installed
Summary: A collection of utilities and DSOs to handle compiled objects
</code></pre>
<p>There's a bug in this version, and according to the <a href="https://bugzilla.redhat.com/show_bug.cgi?id=377241" rel="nofollow noreferrer">bug report</a>, a newer version has been pushed to the Fedora 8 stable repository. But, if I try to update:</p>
<pre><code>$ yum update elfutils
Setting up Update Process
Could not find update match for elfutils
No Packages marked for Update
</code></pre>
<p>Here are my repositories:</p>
<pre><code>$ yum repolist enabled
repo id repo name status
InstallMedia Fedora 8 enabled
fedora Fedora 8 - x86_64 enabled
updates Fedora 8 - x86_64 - Updates enabled
</code></pre>
<p>What am I missing?</p>
| [
{
"answer_id": 104479,
"author": "ethyreal",
"author_id": 18159,
"author_profile": "https://Stackoverflow.com/users/18159",
"pm_score": 1,
"selected": false,
"text": "<p>i know this seems silly but did you try removing it and reinstalling?</p>\n\n<pre><code>yum remove elfutils\n</code></pre>\n\n<p>then</p>\n\n<pre><code>yum install elfutils\n</code></pre>\n\n<p>alternatively you could try updating everything:</p>\n\n<pre><code>yum update\n</code></pre>\n\n<p>...if their is no update marked in the repository you might try:</p>\n\n<pre><code>yum upgrade\n</code></pre>\n"
},
{
"answer_id": 104672,
"author": "Loren Charnley",
"author_id": 2346,
"author_profile": "https://Stackoverflow.com/users/2346",
"pm_score": 1,
"selected": false,
"text": "<p>If you look at the listing of the repository packages directory at</p>\n\n<p><a href=\"http://download.fedora.redhat.com/pub/fedora/linux/releases/8/Everything/x86_64/os/Packages/%22Fedora%20x86_64%20Repository\" rel=\"nofollow noreferrer\">Link to Fedora Repository</a></p>\n\n<p>You will see that you have the latest version in that directory, which is why yum is not upgrading your package. This is the same in both the i386 and x86_64 package directories. So the reason that you are not seeing an update is that there is not a more current version in the repository yet. The notification in the bug report that a new version is in the repository is incorrect.</p>\n"
},
{
"answer_id": 104801,
"author": "Lorin Hochstein",
"author_id": 742,
"author_profile": "https://Stackoverflow.com/users/742",
"pm_score": 2,
"selected": false,
"text": "<p>OK, I figured it out. I needed to upgrade the <code>fedora-release</code> package. That allowed me to see all of the updated packages. Thanks to ethyreal for pointing me to the Yum upgrade FAQ.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
]
| I'm trying to upgrade a package using yum on Fedora 8. The package is `elfutils`. Here's what I have installed locally:
```
$ yum info elfutils
Installed Packages
Name : elfutils
Arch : x86_64
Version: 0.130
Release: 3.fc8
Size : 436 k
Repo : installed
Summary: A collection of utilities and DSOs to handle compiled objects
```
There's a bug in this version, and according to the [bug report](https://bugzilla.redhat.com/show_bug.cgi?id=377241), a newer version has been pushed to the Fedora 8 stable repository. But, if I try to update:
```
$ yum update elfutils
Setting up Update Process
Could not find update match for elfutils
No Packages marked for Update
```
Here are my repositories:
```
$ yum repolist enabled
repo id repo name status
InstallMedia Fedora 8 enabled
fedora Fedora 8 - x86_64 enabled
updates Fedora 8 - x86_64 - Updates enabled
```
What am I missing? | OK, I figured it out. I needed to upgrade the `fedora-release` package. That allowed me to see all of the updated packages. Thanks to ethyreal for pointing me to the Yum upgrade FAQ. |
104,420 | <p>How do I generate all the permutations of a list? For example:</p>
<pre><code>permutations([])
[]
permutations([1])
[1]
permutations([1, 2])
[1, 2]
[2, 1]
permutations([1, 2, 3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
</code></pre>
| [
{
"answer_id": 104426,
"author": "Ricardo Reyes",
"author_id": 3399,
"author_profile": "https://Stackoverflow.com/users/3399",
"pm_score": 5,
"selected": false,
"text": "<p>This solution implements a generator, to avoid holding all the permutations on memory:</p>\n\n<pre><code>def permutations (orig_list):\n if not isinstance(orig_list, list):\n orig_list = list(orig_list)\n\n yield orig_list\n\n if len(orig_list) == 1:\n return\n\n for n in sorted(orig_list):\n new_list = orig_list[:]\n pos = new_list.index(n)\n del(new_list[pos])\n new_list.insert(0, n)\n for resto in permutations(new_list[1:]):\n if new_list[:1] + resto <> orig_list:\n yield new_list[:1] + resto\n</code></pre>\n"
},
{
"answer_id": 104436,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 10,
"selected": true,
"text": "<p>Use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.permutations\" rel=\"noreferrer\"><code>itertools.permutations</code></a> from the <strong>standard library</strong>:</p>\n<pre><code>import itertools\nlist(itertools.permutations([1, 2, 3]))\n</code></pre>\n<hr />\n<p>Adapted from <a href=\"http://code.activestate.com/recipes/252178/\" rel=\"noreferrer\">here</a> is a demonstration of how <code>itertools.permutations</code> might be implemented:</p>\n<pre><code>def permutations(elements):\n if len(elements) <= 1:\n yield elements\n return\n for perm in permutations(elements[1:]):\n for i in range(len(elements)):\n # nb elements[0:1] works in both string and list contexts\n yield perm[:i] + elements[0:1] + perm[i:]\n</code></pre>\n<p>A couple of alternative approaches are listed in the documentation of <code>itertools.permutations</code>. Here's one:</p>\n<pre><code>def permutations(iterable, r=None):\n # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC\n # permutations(range(3)) --> 012 021 102 120 201 210\n pool = tuple(iterable)\n n = len(pool)\n r = n if r is None else r\n if r > n:\n return\n indices = range(n)\n cycles = range(n, n-r, -1)\n yield tuple(pool[i] for i in indices[:r])\n while n:\n for i in reversed(range(r)):\n cycles[i] -= 1\n if cycles[i] == 0:\n indices[i:] = indices[i+1:] + indices[i:i+1]\n cycles[i] = n - i\n else:\n j = cycles[i]\n indices[i], indices[-j] = indices[-j], indices[i]\n yield tuple(pool[i] for i in indices[:r])\n break\n else:\n return\n</code></pre>\n<p>And another, based on <code>itertools.product</code>:</p>\n<pre><code>def permutations(iterable, r=None):\n pool = tuple(iterable)\n n = len(pool)\n r = n if r is None else r\n for indices in product(range(n), repeat=r):\n if len(set(indices)) == r:\n yield tuple(pool[i] for i in indices)\n</code></pre>\n"
},
{
"answer_id": 104471,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 8,
"selected": false,
"text": "<p>For <a href=\"http://docs.python.org/dev/whatsnew/2.6.html\" rel=\"noreferrer\">Python 2.6</a> onwards:</p>\n<pre><code>import itertools\nitertools.permutations([1, 2, 3])\n</code></pre>\n<p>This returns as a generator. Use <code>list(permutations(xs))</code> to return as a list.</p>\n"
},
{
"answer_id": 108651,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 4,
"selected": false,
"text": "<p>The following code is an in-place permutation of a given list, implemented as a generator. Since it only returns references to the list, the list should not be modified outside the generator.\nThe solution is non-recursive, so uses low memory. Work well also with multiple copies of elements in the input list.</p>\n\n<pre><code>def permute_in_place(a):\n a.sort()\n yield list(a)\n\n if len(a) <= 1:\n return\n\n first = 0\n last = len(a)\n while 1:\n i = last - 1\n\n while 1:\n i = i - 1\n if a[i] < a[i+1]:\n j = last - 1\n while not (a[i] < a[j]):\n j = j - 1\n a[i], a[j] = a[j], a[i] # swap the values\n r = a[i+1:last]\n r.reverse()\n a[i+1:last] = r\n yield list(a)\n break\n if i == first:\n a.reverse()\n return\n\nif __name__ == '__main__':\n for n in range(5):\n for a in permute_in_place(range(1, n+1)):\n print a\n print\n\n for a in permute_in_place([0, 0, 1, 1, 1]):\n print a\n print\n</code></pre>\n"
},
{
"answer_id": 170248,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 8,
"selected": false,
"text": "<p>First, import <code>itertools</code>:</p>\n<pre><code>import itertools\n</code></pre>\n<h3>Permutation (order matters):</h3>\n<pre><code>print(list(itertools.permutations([1,2,3,4], 2)))\n\n[(1, 2), (1, 3), (1, 4),\n(2, 1), (2, 3), (2, 4),\n(3, 1), (3, 2), (3, 4),\n(4, 1), (4, 2), (4, 3)]\n</code></pre>\n<h3>Combination (order does NOT matter):</h3>\n<pre><code>print(list(itertools.combinations('123', 2)))\n\n[('1', '2'), ('1', '3'), ('2', '3')]\n</code></pre>\n<h3>Cartesian product (with several iterables):</h3>\n<pre><code>print(list(itertools.product([1,2,3], [4,5,6])))\n\n[(1, 4), (1, 5), (1, 6),\n(2, 4), (2, 5), (2, 6),\n(3, 4), (3, 5), (3, 6)]\n</code></pre>\n<h3>Cartesian product (with one iterable and itself):</h3>\n<pre><code>print(list(itertools.product([1,2], repeat=3)))\n\n[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),\n(2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]\n</code></pre>\n"
},
{
"answer_id": 5501066,
"author": "tzwenn",
"author_id": 522943,
"author_profile": "https://Stackoverflow.com/users/522943",
"pm_score": 4,
"selected": false,
"text": "<p>A quite obvious way in my opinion might be also:</p>\n\n<pre><code>def permutList(l):\n if not l:\n return [[]]\n res = []\n for e in l:\n temp = l[:]\n temp.remove(e)\n res.extend([[e] + r for r in permutList(temp)])\n\n return res\n</code></pre>\n"
},
{
"answer_id": 7140205,
"author": "zmk",
"author_id": 891004,
"author_profile": "https://Stackoverflow.com/users/891004",
"pm_score": 4,
"selected": false,
"text": "<pre><code>list2Perm = [1, 2.0, 'three']\nlistPerm = [[a, b, c]\n for a in list2Perm\n for b in list2Perm\n for c in list2Perm\n if ( a != b and b != c and a != c )\n ]\nprint listPerm\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>[\n [1, 2.0, 'three'], \n [1, 'three', 2.0], \n [2.0, 1, 'three'], \n [2.0, 'three', 1], \n ['three', 1, 2.0], \n ['three', 2.0, 1]\n]\n</code></pre>\n"
},
{
"answer_id": 7733966,
"author": "kx2k",
"author_id": 990523,
"author_profile": "https://Stackoverflow.com/users/990523",
"pm_score": 6,
"selected": false,
"text": "<pre><code>def permutations(head, tail=''):\n if len(head) == 0:\n print(tail)\n else:\n for i in range(len(head)):\n permutations(head[:i] + head[i+1:], tail + head[i])\n</code></pre>\n<p>called as:</p>\n<pre><code>permutations('abc')\n</code></pre>\n"
},
{
"answer_id": 10799849,
"author": "Eric O Lebigot",
"author_id": 42973,
"author_profile": "https://Stackoverflow.com/users/42973",
"pm_score": 3,
"selected": false,
"text": "<p>One can indeed iterate over the first element of each permutation, as in tzwenn's answer. It is however more efficient to write this solution this way:</p>\n\n<pre><code>def all_perms(elements):\n if len(elements) <= 1:\n yield elements # Only permutation possible = no permutation\n else:\n # Iteration over the first element in the result permutation:\n for (index, first_elmt) in enumerate(elements):\n other_elmts = elements[:index]+elements[index+1:]\n for permutation in all_perms(other_elmts): \n yield [first_elmt] + permutation\n</code></pre>\n\n<p>This solution is about 30 % faster, apparently thanks to the recursion ending at <code>len(elements) <= 1</code> instead of <code>0</code>.\nIt is also much more memory-efficient, as it uses a generator function (through <code>yield</code>), like in Riccardo Reyes's solution.</p>\n"
},
{
"answer_id": 11962517,
"author": "Silveira Neto",
"author_id": 914818,
"author_profile": "https://Stackoverflow.com/users/914818",
"pm_score": 5,
"selected": false,
"text": "<pre><code>#!/usr/bin/env python\n\ndef perm(a, k=0):\n if k == len(a):\n print a\n else:\n for i in xrange(k, len(a)):\n a[k], a[i] = a[i] ,a[k]\n perm(a, k+1)\n a[k], a[i] = a[i], a[k]\n\nperm([1,2,3])\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>[1, 2, 3]\n[1, 3, 2]\n[2, 1, 3]\n[2, 3, 1]\n[3, 2, 1]\n[3, 1, 2]\n</code></pre>\n\n<p>As I'm swapping the content of the list it's required a mutable sequence type as input. E.g. <code>perm(list(\"ball\"))</code> will work and <code>perm(\"ball\")</code> won't because you can't change a string. </p>\n\n<p>This Python implementation is inspired by the algorithm presented in the book <em>Computer Algorithms by Horowitz, Sahni and Rajasekeran</em>.</p>\n"
},
{
"answer_id": 14470271,
"author": "Chen Xie",
"author_id": 1234376,
"author_profile": "https://Stackoverflow.com/users/1234376",
"pm_score": 3,
"selected": false,
"text": "<p>Note that this algorithm has an <code>n factorial</code> time complexity, where <code>n</code> is the length of the input list</p>\n\n<p>Print the results on the run:</p>\n\n<pre><code>global result\nresult = [] \n\ndef permutation(li):\nif li == [] or li == None:\n return\n\nif len(li) == 1:\n result.append(li[0])\n print result\n result.pop()\n return\n\nfor i in range(0,len(li)):\n result.append(li[i])\n permutation(li[:i] + li[i+1:])\n result.pop() \n</code></pre>\n\n<p>Example: </p>\n\n<pre><code>permutation([1,2,3])\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>[1, 2, 3]\n[1, 3, 2]\n[2, 1, 3]\n[2, 3, 1]\n[3, 1, 2]\n[3, 2, 1]\n</code></pre>\n"
},
{
"answer_id": 16446022,
"author": "Adrian Statescu",
"author_id": 633040,
"author_profile": "https://Stackoverflow.com/users/633040",
"pm_score": 2,
"selected": false,
"text": "<pre><code>from __future__ import print_function\n\ndef perm(n):\n p = []\n for i in range(0,n+1):\n p.append(i)\n while True:\n for i in range(1,n+1):\n print(p[i], end=' ')\n print(\"\")\n i = n - 1\n found = 0\n while (not found and i>0):\n if p[i]<p[i+1]:\n found = 1\n else:\n i = i - 1\n k = n\n while p[i]>p[k]:\n k = k - 1\n aux = p[i]\n p[i] = p[k]\n p[k] = aux\n for j in range(1,(n-i)/2+1):\n aux = p[i+j]\n p[i+j] = p[n-j+1]\n p[n-j+1] = aux\n if not found:\n break\n\nperm(5)\n</code></pre>\n"
},
{
"answer_id": 17391851,
"author": "Paolo",
"author_id": 2536705,
"author_profile": "https://Stackoverflow.com/users/2536705",
"pm_score": 4,
"selected": false,
"text": "<p>In a functional style</p>\n\n<pre><code>def addperm(x,l):\n return [ l[0:i] + [x] + l[i:] for i in range(len(l)+1) ]\n\ndef perm(l):\n if len(l) == 0:\n return [[]]\n return [x for y in perm(l[1:]) for x in addperm(l[0],y) ]\n\nprint perm([ i for i in range(3)])\n</code></pre>\n\n<p>The result:</p>\n\n<pre><code>[[0, 1, 2], [1, 0, 2], [1, 2, 0], [0, 2, 1], [2, 0, 1], [2, 1, 0]]\n</code></pre>\n"
},
{
"answer_id": 17504089,
"author": "cdiggins",
"author_id": 184528,
"author_profile": "https://Stackoverflow.com/users/184528",
"pm_score": 2,
"selected": false,
"text": "<p>Here is an algorithm that works on a list without creating new intermediate lists similar to Ber's solution at <a href=\"https://stackoverflow.com/a/108651/184528\">https://stackoverflow.com/a/108651/184528</a>. </p>\n\n<pre><code>def permute(xs, low=0):\n if low + 1 >= len(xs):\n yield xs\n else:\n for p in permute(xs, low + 1):\n yield p \n for i in range(low + 1, len(xs)): \n xs[low], xs[i] = xs[i], xs[low]\n for p in permute(xs, low + 1):\n yield p \n xs[low], xs[i] = xs[i], xs[low]\n\nfor p in permute([1, 2, 3, 4]):\n print p\n</code></pre>\n\n<p>You can try the code out for yourself here: <a href=\"http://repl.it/J9v\" rel=\"nofollow noreferrer\">http://repl.it/J9v</a></p>\n"
},
{
"answer_id": 18135428,
"author": "timeeeee",
"author_id": 1478340,
"author_profile": "https://Stackoverflow.com/users/1478340",
"pm_score": 4,
"selected": false,
"text": "<p>I used an algorithm based on the <a href=\"http://en.wikipedia.org/wiki/Factorial_number_system\" rel=\"noreferrer\">factorial number system</a>- For a list of length n, you can assemble each permutation item by item, selecting from the items left at each stage. You have n choices for the first item, n-1 for the second, and only one for the last, so you can use the digits of a number in the factorial number system as the indices. This way the numbers 0 through n!-1 correspond to all possible permutations in lexicographic order.</p>\n\n<pre><code>from math import factorial\ndef permutations(l):\n permutations=[]\n length=len(l)\n for x in xrange(factorial(length)):\n available=list(l)\n newPermutation=[]\n for radix in xrange(length, 0, -1):\n placeValue=factorial(radix-1)\n index=x/placeValue\n newPermutation.append(available.pop(index))\n x-=index*placeValue\n permutations.append(newPermutation)\n return permutations\n\npermutations(range(3))\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>[[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]\n</code></pre>\n\n<p>This method is non-recursive, but it is slightly slower on my computer and xrange raises an error when n! is too large to be converted to a C long integer (n=13 for me). It was enough when I needed it, but it's no itertools.permutations by a long shot.</p>\n"
},
{
"answer_id": 20014561,
"author": "piggybox",
"author_id": 2102764,
"author_profile": "https://Stackoverflow.com/users/2102764",
"pm_score": 3,
"selected": false,
"text": "<p>This is inspired by the Haskell implementation using list comprehension: </p>\n\n<pre><code>def permutation(list):\n if len(list) == 0:\n return [[]]\n else:\n return [[x] + ys for x in list for ys in permutation(delete(list, x))]\n\ndef delete(list, item):\n lc = list[:]\n lc.remove(item)\n return lc\n</code></pre>\n"
},
{
"answer_id": 23732953,
"author": "darxtrix",
"author_id": 2679770,
"author_profile": "https://Stackoverflow.com/users/2679770",
"pm_score": 2,
"selected": false,
"text": "<p>The beauty of recursion:</p>\n\n<pre><code>>>> import copy\n>>> def perm(prefix,rest):\n... for e in rest:\n... new_rest=copy.copy(rest)\n... new_prefix=copy.copy(prefix)\n... new_prefix.append(e)\n... new_rest.remove(e)\n... if len(new_rest) == 0:\n... print new_prefix + new_rest\n... continue\n... perm(new_prefix,new_rest)\n... \n>>> perm([],['a','b','c','d'])\n['a', 'b', 'c', 'd']\n['a', 'b', 'd', 'c']\n['a', 'c', 'b', 'd']\n['a', 'c', 'd', 'b']\n['a', 'd', 'b', 'c']\n['a', 'd', 'c', 'b']\n['b', 'a', 'c', 'd']\n['b', 'a', 'd', 'c']\n['b', 'c', 'a', 'd']\n['b', 'c', 'd', 'a']\n['b', 'd', 'a', 'c']\n['b', 'd', 'c', 'a']\n['c', 'a', 'b', 'd']\n['c', 'a', 'd', 'b']\n['c', 'b', 'a', 'd']\n['c', 'b', 'd', 'a']\n['c', 'd', 'a', 'b']\n['c', 'd', 'b', 'a']\n['d', 'a', 'b', 'c']\n['d', 'a', 'c', 'b']\n['d', 'b', 'a', 'c']\n['d', 'b', 'c', 'a']\n['d', 'c', 'a', 'b']\n['d', 'c', 'b', 'a']\n</code></pre>\n"
},
{
"answer_id": 28256360,
"author": "Cmyker",
"author_id": 1079659,
"author_profile": "https://Stackoverflow.com/users/1079659",
"pm_score": 2,
"selected": false,
"text": "<p>This algorithm is the most effective one, it avoids of array passing and manipulation in recursive calls, works in Python 2, 3:</p>\n\n<pre><code>def permute(items):\n length = len(items)\n def inner(ix=[]):\n do_yield = len(ix) == length - 1\n for i in range(0, length):\n if i in ix: #avoid duplicates\n continue\n if do_yield:\n yield tuple([items[y] for y in ix + [i]])\n else:\n for p in inner(ix + [i]):\n yield p\n return inner()\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>for p in permute((1,2,3)):\n print(p)\n\n(1, 2, 3)\n(1, 3, 2)\n(2, 1, 3)\n(2, 3, 1)\n(3, 1, 2)\n(3, 2, 1)\n</code></pre>\n"
},
{
"answer_id": 30112080,
"author": "manish kumar",
"author_id": 4166033,
"author_profile": "https://Stackoverflow.com/users/4166033",
"pm_score": 2,
"selected": false,
"text": "<pre><code>def pzip(c, seq):\n result = []\n for item in seq:\n for i in range(len(item)+1):\n result.append(item[i:]+c+item[:i])\n return result\n\n\ndef perm(line):\n seq = [c for c in line]\n if len(seq) <=1 :\n return seq\n else:\n return pzip(seq[0], perm(seq[1:]))\n</code></pre>\n"
},
{
"answer_id": 30428753,
"author": "B. M.",
"author_id": 4016285,
"author_profile": "https://Stackoverflow.com/users/4016285",
"pm_score": 3,
"selected": false,
"text": "<p>For performance, a numpy solution inspired by <a href=\"http://www.kcats.org/csci/464/doc/knuth/fascicles/fasc2b.pdf\" rel=\"noreferrer\">Knuth</a>, (p22) :</p>\n\n<pre><code>from numpy import empty, uint8\nfrom math import factorial\n\ndef perms(n):\n f = 1\n p = empty((2*n-1, factorial(n)), uint8)\n for i in range(n):\n p[i, :f] = i\n p[i+1:2*i+1, :f] = p[:i, :f] # constitution de blocs\n for j in range(i):\n p[:i+1, f*(j+1):f*(j+2)] = p[j+1:j+i+2, :f] # copie de blocs\n f = f*(i+1)\n return p[:n, :]\n</code></pre>\n\n<p>Copying large blocs of memory saves time - \nit's 20x faster than <code>list(itertools.permutations(range(n))</code> :</p>\n\n<pre><code>In [1]: %timeit -n10 list(permutations(range(10)))\n10 loops, best of 3: 815 ms per loop\n\nIn [2]: %timeit -n100 perms(10) \n100 loops, best of 3: 40 ms per loop\n</code></pre>\n"
},
{
"answer_id": 32448587,
"author": "Bharatwaja",
"author_id": 3944755,
"author_profile": "https://Stackoverflow.com/users/3944755",
"pm_score": -1,
"selected": false,
"text": "<p>for Python we can use itertools and import both permutations and combinations to solve your problem</p>\n\n<pre><code>from itertools import product, permutations\nA = ([1,2,3])\nprint (list(permutations(sorted(A),2)))\n</code></pre>\n"
},
{
"answer_id": 36102351,
"author": "Miled Louis Rizk",
"author_id": 6023433,
"author_profile": "https://Stackoverflow.com/users/6023433",
"pm_score": 2,
"selected": false,
"text": "<p>Generate all possible permutations</p>\n\n<p>I'm using python3.4:</p>\n\n<pre><code>def calcperm(arr, size):\n result = set([()])\n for dummy_idx in range(size):\n temp = set()\n for dummy_lst in result:\n for dummy_outcome in arr:\n if dummy_outcome not in dummy_lst:\n new_seq = list(dummy_lst)\n new_seq.append(dummy_outcome)\n temp.add(tuple(new_seq))\n result = temp\n return result\n</code></pre>\n\n<p>Test Cases:</p>\n\n<pre><code>lst = [1, 2, 3, 4]\n#lst = [\"yellow\", \"magenta\", \"white\", \"blue\"]\nseq = 2\nfinal = calcperm(lst, seq)\nprint(len(final))\nprint(final)\n</code></pre>\n"
},
{
"answer_id": 38793421,
"author": "Karo Castro-Wunsch",
"author_id": 4725204,
"author_profile": "https://Stackoverflow.com/users/4725204",
"pm_score": 2,
"selected": false,
"text": "<p>I see a <em>lot</em> of iteration going on inside these recursive functions, not exactly <em>pure</em> recursion...</p>\n\n<p>so for those of you who cannot abide by even a single loop, here's a gross, totally unnecessary fully recursive solution</p>\n\n<pre><code>def all_insert(x, e, i=0):\n return [x[0:i]+[e]+x[i:]] + all_insert(x,e,i+1) if i<len(x)+1 else []\n\ndef for_each(X, e):\n return all_insert(X[0], e) + for_each(X[1:],e) if X else []\n\ndef permute(x):\n return [x] if len(x) < 2 else for_each( permute(x[1:]) , x[0])\n\n\nperms = permute([1,2,3])\n</code></pre>\n"
},
{
"answer_id": 43018229,
"author": "anhldbk",
"author_id": 197896,
"author_profile": "https://Stackoverflow.com/users/197896",
"pm_score": 1,
"selected": false,
"text": "<p>Another solution:</p>\n\n<pre><code>def permutation(flag, k =1 ):\n N = len(flag)\n for i in xrange(0, N):\n if flag[i] != 0:\n continue\n flag[i] = k \n if k == N:\n print flag\n permutation(flag, k+1)\n flag[i] = 0\n\npermutation([0, 0, 0])\n</code></pre>\n"
},
{
"answer_id": 49072115,
"author": "abelenky",
"author_id": 34824,
"author_profile": "https://Stackoverflow.com/users/34824",
"pm_score": 0,
"selected": false,
"text": "<p>My Python Solution:</p>\n\n<pre><code>def permutes(input,offset):\n if( len(input) == offset ):\n return [''.join(input)]\n\n result=[] \n for i in range( offset, len(input) ):\n input[offset], input[i] = input[i], input[offset]\n result = result + permutes(input,offset+1)\n input[offset], input[i] = input[i], input[offset]\n return result\n\n# input is a \"string\"\n# return value is a list of strings\ndef permutations(input):\n return permutes( list(input), 0 )\n\n# Main Program\nprint( permutations(\"wxyz\") )\n</code></pre>\n"
},
{
"answer_id": 50311529,
"author": "Ilgorbek Kuchkarov",
"author_id": 6283828,
"author_profile": "https://Stackoverflow.com/users/6283828",
"pm_score": 0,
"selected": false,
"text": "<pre><code>def permutation(word, first_char=None):\n if word == None or len(word) == 0: return []\n if len(word) == 1: return [word]\n\n result = []\n first_char = word[0]\n for sub_word in permutation(word[1:], first_char):\n result += insert(first_char, sub_word)\n return sorted(result)\n\ndef insert(ch, sub_word):\n arr = [ch + sub_word]\n for i in range(len(sub_word)):\n arr.append(sub_word[i:] + ch + sub_word[:i])\n return arr\n\n\nassert permutation(None) == []\nassert permutation('') == []\nassert permutation('1') == ['1']\nassert permutation('12') == ['12', '21']\n\nprint permutation('abc')\n</code></pre>\n\n<p>Output: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']</p>\n"
},
{
"answer_id": 53785851,
"author": "Anatoly Alekseev",
"author_id": 4334120,
"author_profile": "https://Stackoverflow.com/users/4334120",
"pm_score": 2,
"selected": false,
"text": "<p>To save you folks possible hours of searching and experimenting, here's the non-recursive permutaions solution in Python which also works with Numba (as of v. 0.41):</p>\n\n<pre><code>@numba.njit()\ndef permutations(A, k):\n r = [[i for i in range(0)]]\n for i in range(k):\n r = [[a] + b for a in A for b in r if (a in b)==False]\n return r\npermutations([1,2,3],3)\n[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n</code></pre>\n\n<p>To give an impression about performance:</p>\n\n<pre><code>%timeit permutations(np.arange(5),5)\n\n243 µs ± 11.1 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)\ntime: 406 ms\n\n%timeit list(itertools.permutations(np.arange(5),5))\n15.9 µs ± 8.61 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\ntime: 12.9 s\n</code></pre>\n\n<p>So use this version only if you have to call it from njitted function, otherwise prefer itertools implementation.</p>\n"
},
{
"answer_id": 55070316,
"author": "Hello.World",
"author_id": 8850552,
"author_profile": "https://Stackoverflow.com/users/8850552",
"pm_score": 0,
"selected": false,
"text": "<p>Using <code>Counter</code></p>\n\n<pre><code>from collections import Counter\n\ndef permutations(nums):\n ans = [[]]\n cache = Counter(nums)\n\n for idx, x in enumerate(nums):\n result = []\n for items in ans:\n cache1 = Counter(items)\n for id, n in enumerate(nums):\n if cache[n] != cache1[n] and items + [n] not in result:\n result.append(items + [n])\n\n ans = result\n return ans\npermutations([1, 2, 2])\n> [[1, 2, 2], [2, 1, 2], [2, 2, 1]]\n\n</code></pre>\n"
},
{
"answer_id": 55421084,
"author": "Tatsu",
"author_id": 5938224,
"author_profile": "https://Stackoverflow.com/users/5938224",
"pm_score": 2,
"selected": false,
"text": "<p><strong>ANOTHER APPROACH (without libs)</strong></p>\n\n<pre><code>def permutation(input):\n if len(input) == 1:\n return input if isinstance(input, list) else [input]\n\n result = []\n for i in range(len(input)):\n first = input[i]\n rest = input[:i] + input[i + 1:]\n rest_permutation = permutation(rest)\n for p in rest_permutation:\n result.append(first + p)\n return result\n</code></pre>\n\n<p><strong>Input can be a string or a list</strong></p>\n\n<pre><code>print(permutation('abcd'))\nprint(permutation(['a', 'b', 'c', 'd']))\n</code></pre>\n"
},
{
"answer_id": 59433823,
"author": "Richard Ambler",
"author_id": 1340742,
"author_profile": "https://Stackoverflow.com/users/1340742",
"pm_score": 3,
"selected": false,
"text": "<p>Disclaimer: shameless plug by package author. :)</p>\n<p>The <a href=\"https://pypi.org/project/trotter/\" rel=\"nofollow noreferrer\">trotter</a> package is different from most implementations in that it generates pseudo lists that don't actually contain permutations but rather describe mappings between permutations and respective positions in an ordering, making it possible to work with very large 'lists' of permutations, as shown in <a href=\"https://permutation-products.netlify.com/\" rel=\"nofollow noreferrer\">this demo</a> which performs pretty instantaneous operations and look-ups in a pseudo-list 'containing' all the permutations of the letters in the alphabet, without using more memory or processing than a typical web page.</p>\n<p>In any case, to generate a list of permutations, we can do the following.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import trotter\n\nmy_permutations = trotter.Permutations(3, [1, 2, 3])\n\nprint(my_permutations)\n\nfor p in my_permutations:\n print(p)\n</code></pre>\n<p>Output:</p>\n<pre>\nA pseudo-list containing 6 3-permutations of [1, 2, 3].\n[1, 2, 3]\n[1, 3, 2]\n[3, 1, 2]\n[3, 2, 1]\n[2, 3, 1]\n[2, 1, 3]\n</pre>\n"
},
{
"answer_id": 59593816,
"author": "Maverick Meerkat",
"author_id": 6296435,
"author_profile": "https://Stackoverflow.com/users/6296435",
"pm_score": 4,
"selected": false,
"text": "<p>Regular implementation (no yield - will do everything in memory):</p>\n\n<pre><code>def getPermutations(array):\n if len(array) == 1:\n return [array]\n permutations = []\n for i in range(len(array)): \n # get all perm's of subarray w/o current item\n perms = getPermutations(array[:i] + array[i+1:]) \n for p in perms:\n permutations.append([array[i], *p])\n return permutations\n</code></pre>\n\n<p>Yield implementation:</p>\n\n<pre><code>def getPermutations(array):\n if len(array) == 1:\n yield array\n else:\n for i in range(len(array)):\n perms = getPermutations(array[:i] + array[i+1:])\n for p in perms:\n yield [array[i], *p]\n</code></pre>\n\n<p>The basic idea is to go over all the elements in the array for the 1st position, and then in 2nd position go over all the rest of the elements without the chosen element for the 1st, etc. You can do this with <strong>recursion</strong>, where the stop criteria is getting to an array of 1 element - in which case you return that array.</p>\n\n<p><a href=\"https://i.stack.imgur.com/eX3df.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/eX3df.jpg\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 62189160,
"author": "Dritte Saskaita",
"author_id": 12278470,
"author_profile": "https://Stackoverflow.com/users/12278470",
"pm_score": 0,
"selected": false,
"text": "<pre><code>def permuteArray (arr):\n\n arraySize = len(arr)\n\n permutedList = []\n\n if arraySize == 1:\n return [arr]\n\n i = 0\n\n for item in arr:\n\n for elem in permuteArray(arr[:i] + arr[i + 1:]):\n permutedList.append([item] + elem)\n\n i = i + 1 \n\n return permutedList\n</code></pre>\n\n<p>I intended to not exhaust every possibility in a new line to make it somewhat unique.</p>\n"
},
{
"answer_id": 62770287,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Anyway we could use <a href=\"https://docs.sympy.org/latest/\" rel=\"nofollow noreferrer\">sympy</a> library , also support for multiset permutations</p>\n<pre><code>import sympy\nfrom sympy.utilities.iterables import multiset_permutations\nt = [1,2,3]\np = list(multiset_permutations(t))\nprint(p)\n\n# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n</code></pre>\n<p>Answer is highly inspired by <a href=\"https://stackoverflow.com/questions/41210142/get-all-permutations-of-a-numpy-array/41210450\">Get all permutations of a numpy array</a></p>\n"
},
{
"answer_id": 64471115,
"author": "Harvey Mao",
"author_id": 10665136,
"author_profile": "https://Stackoverflow.com/users/10665136",
"pm_score": 0,
"selected": false,
"text": "<pre><code>from typing import List\nimport time, random\n\ndef measure_time(func):\n def wrapper_time(*args, **kwargs):\n start_time = time.perf_counter()\n res = func(*args, **kwargs)\n end_time = time.perf_counter()\n return res, end_time - start_time\n\n return wrapper_time\n\n\nclass Solution:\n def permute(self, nums: List[int], method: int = 1) -> List[List[int]]:\n perms = []\n perm = []\n if method == 1:\n _, time_perm = self._permute_recur(nums, 0, len(nums) - 1, perms)\n elif method == 2:\n _, time_perm = self._permute_recur_agian(nums, perm, perms)\n print(perm)\n return perms, time_perm\n\n @measure_time\n def _permute_recur(self, nums: List[int], l: int, r: int, perms: List[List[int]]):\n # base case\n if l == r:\n perms.append(nums.copy())\n\n for i in range(l, r + 1):\n nums[l], nums[i] = nums[i], nums[l]\n self._permute_recur(nums, l + 1, r , perms)\n nums[l], nums[i] = nums[i], nums[l]\n\n @measure_time\n def _permute_recur_agian(self, nums: List[int], perm: List[int], perms_list: List[List[int]]):\n """\n The idea is similar to nestedForLoops visualized as a recursion tree.\n """\n if nums:\n for i in range(len(nums)):\n # perm.append(nums[i]) mistake, perm will be filled with all nums's elements.\n # Method1 perm_copy = copy.deepcopy(perm)\n # Method2 add in the parameter list using + (not in place)\n # caveat: list.append is in-place , which is useful for operating on global element perms_list\n # Note that:\n # perms_list pass by reference. shallow copy\n # perm + [nums[i]] pass by value instead of reference.\n self._permute_recur_agian(nums[:i] + nums[i+1:], perm + [nums[i]], perms_list)\n else:\n # Arrive at the last loop, i.e. leaf of the recursion tree.\n perms_list.append(perm)\n\n\n\nif __name__ == "__main__":\n array = [random.randint(-10, 10) for _ in range(3)]\n sol = Solution()\n # perms, time_perm = sol.permute(array, 1)\n perms2, time_perm2 = sol.permute(array, 2)\n print(perms2)\n # print(perms, perms2)\n # print(time_perm, time_perm2)\n```\n</code></pre>\n"
},
{
"answer_id": 65241289,
"author": "Michael Hodel",
"author_id": 12363750,
"author_profile": "https://Stackoverflow.com/users/12363750",
"pm_score": 0,
"selected": false,
"text": "<p>in case anyone fancies this ugly one-liner (works only for strings though):</p>\n<pre><code>def p(a):\n return a if len(a) == 1 else [[a[i], *j] for i in range(len(a)) for j in p(a[:i] + a[i + 1:])]\n</code></pre>\n"
},
{
"answer_id": 65542989,
"author": "Bhaskar13",
"author_id": 11930483,
"author_profile": "https://Stackoverflow.com/users/11930483",
"pm_score": 1,
"selected": false,
"text": "<p>This is the asymptotically optimal way O(n*n!) of generating permutations after initial sorting.</p>\n<p>There are n! permutations at most and hasNextPermutation(..) runs in O(n) time complexity</p>\n<p>In 3 steps, <br></p>\n<ol>\n<li>Find largest j such that a[j] can be increased</li>\n<li>Increase a[j] by smallest feasible amount</li>\n<li>Find lexicogrpahically least way to extend the new a[0..j]</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>'''\nLexicographic permutation generation\n\nconsider example array state of [1,5,6,4,3,2] for sorted [1,2,3,4,5,6]\nafter 56432(treat as number) ->nothing larger than 6432(using 6,4,3,2) beginning with 5\nso 6 is next larger and 2345(least using numbers other than 6)\nso [1, 6,2,3,4,5]\n'''\ndef hasNextPermutation(array, len):\n ' Base Condition '\n if(len ==1):\n return False\n '''\n Set j = last-2 and find first j such that a[j] < a[j+1]\n If no such j(j==-1) then we have visited all permutations\n after this step a[j+1]>=..>=a[len-1] and a[j]<a[j+1]\n\n a[j]=5 or j=1, 6>5>4>3>2\n '''\n j = len -2\n while (j >= 0 and array[j] >= array[j + 1]):\n j= j-1\n if(j==-1):\n return False\n # print(f"After step 2 for j {j} {array}")\n '''\n decrease l (from n-1 to j) repeatedly until a[j]<a[l]\n Then swap a[j], a[l]\n a[l] is the smallest element > a[j] that can follow a[l]...a[j-1] in permutation\n before swap we have a[j+1]>=..>=a[l-1]>=a[l]>a[j]>=a[l+1]>=..>=a[len-1]\n after swap -> a[j+1]>=..>=a[l-1]>=a[j]>a[l]>=a[l+1]>=..>=a[len-1]\n\n a[l]=6 or l=2, j=1 just before swap [1, 5, 6, 4, 3, 2] \n after swap [1, 6, 5, 4, 3, 2] a[l]=5, a[j]=6\n '''\n l = len -1\n while(array[j] >= array[l]):\n l = l-1\n # print(f"After step 3 for l={l}, j={j} before swap {array}")\n array[j], array[l] = array[l], array[j]\n # print(f"After step 3 for l={l} j={j} after swap {array}")\n '''\n Reverse a[j+1...len-1](both inclusive)\n\n after reversing [1, 6, 2, 3, 4, 5]\n '''\n array[j+1:len] = reversed(array[j+1:len])\n # print(f"After step 4 reversing {array}")\n return True\n\narray = [1,2,4,4,5]\narray.sort()\nlen = len(array)\ncount =1\nprint(array)\n'''\nThe algorithm visits every permutation in lexicographic order\ngenerating one by one\n'''\nwhile(hasNextPermutation(array, len)):\n print(array)\n count = count +1\n# The number of permutations will be n! if no duplicates are present, else less than that\n# [1,4,3,3,2] -> 5!/2!=60\nprint(f"Number of permutations: {count}")\n\n\n</code></pre>\n"
},
{
"answer_id": 68712244,
"author": "Alon Barad",
"author_id": 8622976,
"author_profile": "https://Stackoverflow.com/users/8622976",
"pm_score": 3,
"selected": false,
"text": "<p>If you don't want to use the builtin methods such as:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import itertools\nlist(itertools.permutations([1, 2, 3]))\n</code></pre>\n<p>you can implement permute function yourself</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections.abc import Iterable\n\n\ndef permute(iterable: Iterable[str]) -> set[str]:\n perms = set()\n\n if len(iterable) == 1:\n return {*iterable}\n\n for index, char in enumerate(iterable):\n perms.update([char + perm for perm in permute(iterable[:index] + iterable[index + 1:])])\n\n return perms\n\n\nif __name__ == '__main__':\n print(permute('abc'))\n # {'bca', 'abc', 'cab', 'acb', 'cba', 'bac'}\n print(permute(['1', '2', '3']))\n # {'123', '312', '132', '321', '213', '231'}\n</code></pre>\n"
},
{
"answer_id": 69397777,
"author": "0script0",
"author_id": 3615178,
"author_profile": "https://Stackoverflow.com/users/3615178",
"pm_score": 1,
"selected": false,
"text": "<pre><code>def permutate(l):\n for i, x in enumerate(l):\n for y in l[i + 1:]:\n yield x, y\n\n\nif __name__ == '__main__':\n print(list(permutate(list('abcd'))))\n print(list(permutate([1, 2, 3, 4])))\n\n#[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]\n#[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]\n</code></pre>\n"
},
{
"answer_id": 71197512,
"author": "Yilmaz",
"author_id": 10262805,
"author_profile": "https://Stackoverflow.com/users/10262805",
"pm_score": 0,
"selected": false,
"text": "<p>Solving with recursion, iterate through elements, take i'th element, and ask yourself: 'What is the permutation of rest of items` till no more element left.</p>\n<p>I explained the solution here: <a href=\"https://www.youtube.com/watch?v=_7GE7psS2b4\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=_7GE7psS2b4</a></p>\n<pre><code>class Solution:\n def permute(self,nums:List[int])->List[List[int]]:\n res=[]\n def dfs(nums,path):\n if len(nums)==0:\n res.append(path)\n for i in range(len(nums)):\n dfs(nums[:i]+nums[i+1:],path+[nums[i]])\n dfs(nums,[])\n return res\n</code></pre>\n"
},
{
"answer_id": 71726156,
"author": "Splendor",
"author_id": 2516816,
"author_profile": "https://Stackoverflow.com/users/2516816",
"pm_score": 0,
"selected": false,
"text": "<p>In case the user wants to keep all permutations in a list, the following code can be used:</p>\n<pre><code>def get_permutations(nums, p_list=[], temp_items=[]):\n if not nums:\n return\n elif len(nums) == 1:\n new_items = temp_items+[nums[0]]\n p_list.append(new_items)\n return\n else:\n for i in range(len(nums)):\n temp_nums = nums[:i]+nums[i+1:]\n new_temp_items = temp_items + [nums[i]]\n get_permutations(temp_nums, p_list, new_temp_items)\n\nnums = [1,2,3]\np_list = []\n\nget_permutations(nums, p_list)\n\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104420",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3399/"
]
| How do I generate all the permutations of a list? For example:
```
permutations([])
[]
permutations([1])
[1]
permutations([1, 2])
[1, 2]
[2, 1]
permutations([1, 2, 3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
``` | Use [`itertools.permutations`](https://docs.python.org/3/library/itertools.html#itertools.permutations) from the **standard library**:
```
import itertools
list(itertools.permutations([1, 2, 3]))
```
---
Adapted from [here](http://code.activestate.com/recipes/252178/) is a demonstration of how `itertools.permutations` might be implemented:
```
def permutations(elements):
if len(elements) <= 1:
yield elements
return
for perm in permutations(elements[1:]):
for i in range(len(elements)):
# nb elements[0:1] works in both string and list contexts
yield perm[:i] + elements[0:1] + perm[i:]
```
A couple of alternative approaches are listed in the documentation of `itertools.permutations`. Here's one:
```
def permutations(iterable, r=None):
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = range(n)
cycles = range(n, n-r, -1)
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
```
And another, based on `itertools.product`:
```
def permutations(iterable, r=None):
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
for indices in product(range(n), repeat=r):
if len(set(indices)) == r:
yield tuple(pool[i] for i in indices)
``` |
104,439 | <p>The Eclipse projects are all stored in the Eclipse Foundation CVS servers. Using the source is a great way to debug your code and to figure out how to do new things. </p>
<p>Unfortunately in a large software project like BIRT, it can be difficult to know which projects and versions are required for a particular build. So what is the best way to get the source for a particular build?</p>
| [
{
"answer_id": 104426,
"author": "Ricardo Reyes",
"author_id": 3399,
"author_profile": "https://Stackoverflow.com/users/3399",
"pm_score": 5,
"selected": false,
"text": "<p>This solution implements a generator, to avoid holding all the permutations on memory:</p>\n\n<pre><code>def permutations (orig_list):\n if not isinstance(orig_list, list):\n orig_list = list(orig_list)\n\n yield orig_list\n\n if len(orig_list) == 1:\n return\n\n for n in sorted(orig_list):\n new_list = orig_list[:]\n pos = new_list.index(n)\n del(new_list[pos])\n new_list.insert(0, n)\n for resto in permutations(new_list[1:]):\n if new_list[:1] + resto <> orig_list:\n yield new_list[:1] + resto\n</code></pre>\n"
},
{
"answer_id": 104436,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 10,
"selected": true,
"text": "<p>Use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.permutations\" rel=\"noreferrer\"><code>itertools.permutations</code></a> from the <strong>standard library</strong>:</p>\n<pre><code>import itertools\nlist(itertools.permutations([1, 2, 3]))\n</code></pre>\n<hr />\n<p>Adapted from <a href=\"http://code.activestate.com/recipes/252178/\" rel=\"noreferrer\">here</a> is a demonstration of how <code>itertools.permutations</code> might be implemented:</p>\n<pre><code>def permutations(elements):\n if len(elements) <= 1:\n yield elements\n return\n for perm in permutations(elements[1:]):\n for i in range(len(elements)):\n # nb elements[0:1] works in both string and list contexts\n yield perm[:i] + elements[0:1] + perm[i:]\n</code></pre>\n<p>A couple of alternative approaches are listed in the documentation of <code>itertools.permutations</code>. Here's one:</p>\n<pre><code>def permutations(iterable, r=None):\n # permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC\n # permutations(range(3)) --> 012 021 102 120 201 210\n pool = tuple(iterable)\n n = len(pool)\n r = n if r is None else r\n if r > n:\n return\n indices = range(n)\n cycles = range(n, n-r, -1)\n yield tuple(pool[i] for i in indices[:r])\n while n:\n for i in reversed(range(r)):\n cycles[i] -= 1\n if cycles[i] == 0:\n indices[i:] = indices[i+1:] + indices[i:i+1]\n cycles[i] = n - i\n else:\n j = cycles[i]\n indices[i], indices[-j] = indices[-j], indices[i]\n yield tuple(pool[i] for i in indices[:r])\n break\n else:\n return\n</code></pre>\n<p>And another, based on <code>itertools.product</code>:</p>\n<pre><code>def permutations(iterable, r=None):\n pool = tuple(iterable)\n n = len(pool)\n r = n if r is None else r\n for indices in product(range(n), repeat=r):\n if len(set(indices)) == r:\n yield tuple(pool[i] for i in indices)\n</code></pre>\n"
},
{
"answer_id": 104471,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 8,
"selected": false,
"text": "<p>For <a href=\"http://docs.python.org/dev/whatsnew/2.6.html\" rel=\"noreferrer\">Python 2.6</a> onwards:</p>\n<pre><code>import itertools\nitertools.permutations([1, 2, 3])\n</code></pre>\n<p>This returns as a generator. Use <code>list(permutations(xs))</code> to return as a list.</p>\n"
},
{
"answer_id": 108651,
"author": "Ber",
"author_id": 11527,
"author_profile": "https://Stackoverflow.com/users/11527",
"pm_score": 4,
"selected": false,
"text": "<p>The following code is an in-place permutation of a given list, implemented as a generator. Since it only returns references to the list, the list should not be modified outside the generator.\nThe solution is non-recursive, so uses low memory. Work well also with multiple copies of elements in the input list.</p>\n\n<pre><code>def permute_in_place(a):\n a.sort()\n yield list(a)\n\n if len(a) <= 1:\n return\n\n first = 0\n last = len(a)\n while 1:\n i = last - 1\n\n while 1:\n i = i - 1\n if a[i] < a[i+1]:\n j = last - 1\n while not (a[i] < a[j]):\n j = j - 1\n a[i], a[j] = a[j], a[i] # swap the values\n r = a[i+1:last]\n r.reverse()\n a[i+1:last] = r\n yield list(a)\n break\n if i == first:\n a.reverse()\n return\n\nif __name__ == '__main__':\n for n in range(5):\n for a in permute_in_place(range(1, n+1)):\n print a\n print\n\n for a in permute_in_place([0, 0, 1, 1, 1]):\n print a\n print\n</code></pre>\n"
},
{
"answer_id": 170248,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 8,
"selected": false,
"text": "<p>First, import <code>itertools</code>:</p>\n<pre><code>import itertools\n</code></pre>\n<h3>Permutation (order matters):</h3>\n<pre><code>print(list(itertools.permutations([1,2,3,4], 2)))\n\n[(1, 2), (1, 3), (1, 4),\n(2, 1), (2, 3), (2, 4),\n(3, 1), (3, 2), (3, 4),\n(4, 1), (4, 2), (4, 3)]\n</code></pre>\n<h3>Combination (order does NOT matter):</h3>\n<pre><code>print(list(itertools.combinations('123', 2)))\n\n[('1', '2'), ('1', '3'), ('2', '3')]\n</code></pre>\n<h3>Cartesian product (with several iterables):</h3>\n<pre><code>print(list(itertools.product([1,2,3], [4,5,6])))\n\n[(1, 4), (1, 5), (1, 6),\n(2, 4), (2, 5), (2, 6),\n(3, 4), (3, 5), (3, 6)]\n</code></pre>\n<h3>Cartesian product (with one iterable and itself):</h3>\n<pre><code>print(list(itertools.product([1,2], repeat=3)))\n\n[(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),\n(2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]\n</code></pre>\n"
},
{
"answer_id": 5501066,
"author": "tzwenn",
"author_id": 522943,
"author_profile": "https://Stackoverflow.com/users/522943",
"pm_score": 4,
"selected": false,
"text": "<p>A quite obvious way in my opinion might be also:</p>\n\n<pre><code>def permutList(l):\n if not l:\n return [[]]\n res = []\n for e in l:\n temp = l[:]\n temp.remove(e)\n res.extend([[e] + r for r in permutList(temp)])\n\n return res\n</code></pre>\n"
},
{
"answer_id": 7140205,
"author": "zmk",
"author_id": 891004,
"author_profile": "https://Stackoverflow.com/users/891004",
"pm_score": 4,
"selected": false,
"text": "<pre><code>list2Perm = [1, 2.0, 'three']\nlistPerm = [[a, b, c]\n for a in list2Perm\n for b in list2Perm\n for c in list2Perm\n if ( a != b and b != c and a != c )\n ]\nprint listPerm\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>[\n [1, 2.0, 'three'], \n [1, 'three', 2.0], \n [2.0, 1, 'three'], \n [2.0, 'three', 1], \n ['three', 1, 2.0], \n ['three', 2.0, 1]\n]\n</code></pre>\n"
},
{
"answer_id": 7733966,
"author": "kx2k",
"author_id": 990523,
"author_profile": "https://Stackoverflow.com/users/990523",
"pm_score": 6,
"selected": false,
"text": "<pre><code>def permutations(head, tail=''):\n if len(head) == 0:\n print(tail)\n else:\n for i in range(len(head)):\n permutations(head[:i] + head[i+1:], tail + head[i])\n</code></pre>\n<p>called as:</p>\n<pre><code>permutations('abc')\n</code></pre>\n"
},
{
"answer_id": 10799849,
"author": "Eric O Lebigot",
"author_id": 42973,
"author_profile": "https://Stackoverflow.com/users/42973",
"pm_score": 3,
"selected": false,
"text": "<p>One can indeed iterate over the first element of each permutation, as in tzwenn's answer. It is however more efficient to write this solution this way:</p>\n\n<pre><code>def all_perms(elements):\n if len(elements) <= 1:\n yield elements # Only permutation possible = no permutation\n else:\n # Iteration over the first element in the result permutation:\n for (index, first_elmt) in enumerate(elements):\n other_elmts = elements[:index]+elements[index+1:]\n for permutation in all_perms(other_elmts): \n yield [first_elmt] + permutation\n</code></pre>\n\n<p>This solution is about 30 % faster, apparently thanks to the recursion ending at <code>len(elements) <= 1</code> instead of <code>0</code>.\nIt is also much more memory-efficient, as it uses a generator function (through <code>yield</code>), like in Riccardo Reyes's solution.</p>\n"
},
{
"answer_id": 11962517,
"author": "Silveira Neto",
"author_id": 914818,
"author_profile": "https://Stackoverflow.com/users/914818",
"pm_score": 5,
"selected": false,
"text": "<pre><code>#!/usr/bin/env python\n\ndef perm(a, k=0):\n if k == len(a):\n print a\n else:\n for i in xrange(k, len(a)):\n a[k], a[i] = a[i] ,a[k]\n perm(a, k+1)\n a[k], a[i] = a[i], a[k]\n\nperm([1,2,3])\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>[1, 2, 3]\n[1, 3, 2]\n[2, 1, 3]\n[2, 3, 1]\n[3, 2, 1]\n[3, 1, 2]\n</code></pre>\n\n<p>As I'm swapping the content of the list it's required a mutable sequence type as input. E.g. <code>perm(list(\"ball\"))</code> will work and <code>perm(\"ball\")</code> won't because you can't change a string. </p>\n\n<p>This Python implementation is inspired by the algorithm presented in the book <em>Computer Algorithms by Horowitz, Sahni and Rajasekeran</em>.</p>\n"
},
{
"answer_id": 14470271,
"author": "Chen Xie",
"author_id": 1234376,
"author_profile": "https://Stackoverflow.com/users/1234376",
"pm_score": 3,
"selected": false,
"text": "<p>Note that this algorithm has an <code>n factorial</code> time complexity, where <code>n</code> is the length of the input list</p>\n\n<p>Print the results on the run:</p>\n\n<pre><code>global result\nresult = [] \n\ndef permutation(li):\nif li == [] or li == None:\n return\n\nif len(li) == 1:\n result.append(li[0])\n print result\n result.pop()\n return\n\nfor i in range(0,len(li)):\n result.append(li[i])\n permutation(li[:i] + li[i+1:])\n result.pop() \n</code></pre>\n\n<p>Example: </p>\n\n<pre><code>permutation([1,2,3])\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>[1, 2, 3]\n[1, 3, 2]\n[2, 1, 3]\n[2, 3, 1]\n[3, 1, 2]\n[3, 2, 1]\n</code></pre>\n"
},
{
"answer_id": 16446022,
"author": "Adrian Statescu",
"author_id": 633040,
"author_profile": "https://Stackoverflow.com/users/633040",
"pm_score": 2,
"selected": false,
"text": "<pre><code>from __future__ import print_function\n\ndef perm(n):\n p = []\n for i in range(0,n+1):\n p.append(i)\n while True:\n for i in range(1,n+1):\n print(p[i], end=' ')\n print(\"\")\n i = n - 1\n found = 0\n while (not found and i>0):\n if p[i]<p[i+1]:\n found = 1\n else:\n i = i - 1\n k = n\n while p[i]>p[k]:\n k = k - 1\n aux = p[i]\n p[i] = p[k]\n p[k] = aux\n for j in range(1,(n-i)/2+1):\n aux = p[i+j]\n p[i+j] = p[n-j+1]\n p[n-j+1] = aux\n if not found:\n break\n\nperm(5)\n</code></pre>\n"
},
{
"answer_id": 17391851,
"author": "Paolo",
"author_id": 2536705,
"author_profile": "https://Stackoverflow.com/users/2536705",
"pm_score": 4,
"selected": false,
"text": "<p>In a functional style</p>\n\n<pre><code>def addperm(x,l):\n return [ l[0:i] + [x] + l[i:] for i in range(len(l)+1) ]\n\ndef perm(l):\n if len(l) == 0:\n return [[]]\n return [x for y in perm(l[1:]) for x in addperm(l[0],y) ]\n\nprint perm([ i for i in range(3)])\n</code></pre>\n\n<p>The result:</p>\n\n<pre><code>[[0, 1, 2], [1, 0, 2], [1, 2, 0], [0, 2, 1], [2, 0, 1], [2, 1, 0]]\n</code></pre>\n"
},
{
"answer_id": 17504089,
"author": "cdiggins",
"author_id": 184528,
"author_profile": "https://Stackoverflow.com/users/184528",
"pm_score": 2,
"selected": false,
"text": "<p>Here is an algorithm that works on a list without creating new intermediate lists similar to Ber's solution at <a href=\"https://stackoverflow.com/a/108651/184528\">https://stackoverflow.com/a/108651/184528</a>. </p>\n\n<pre><code>def permute(xs, low=0):\n if low + 1 >= len(xs):\n yield xs\n else:\n for p in permute(xs, low + 1):\n yield p \n for i in range(low + 1, len(xs)): \n xs[low], xs[i] = xs[i], xs[low]\n for p in permute(xs, low + 1):\n yield p \n xs[low], xs[i] = xs[i], xs[low]\n\nfor p in permute([1, 2, 3, 4]):\n print p\n</code></pre>\n\n<p>You can try the code out for yourself here: <a href=\"http://repl.it/J9v\" rel=\"nofollow noreferrer\">http://repl.it/J9v</a></p>\n"
},
{
"answer_id": 18135428,
"author": "timeeeee",
"author_id": 1478340,
"author_profile": "https://Stackoverflow.com/users/1478340",
"pm_score": 4,
"selected": false,
"text": "<p>I used an algorithm based on the <a href=\"http://en.wikipedia.org/wiki/Factorial_number_system\" rel=\"noreferrer\">factorial number system</a>- For a list of length n, you can assemble each permutation item by item, selecting from the items left at each stage. You have n choices for the first item, n-1 for the second, and only one for the last, so you can use the digits of a number in the factorial number system as the indices. This way the numbers 0 through n!-1 correspond to all possible permutations in lexicographic order.</p>\n\n<pre><code>from math import factorial\ndef permutations(l):\n permutations=[]\n length=len(l)\n for x in xrange(factorial(length)):\n available=list(l)\n newPermutation=[]\n for radix in xrange(length, 0, -1):\n placeValue=factorial(radix-1)\n index=x/placeValue\n newPermutation.append(available.pop(index))\n x-=index*placeValue\n permutations.append(newPermutation)\n return permutations\n\npermutations(range(3))\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>[[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]\n</code></pre>\n\n<p>This method is non-recursive, but it is slightly slower on my computer and xrange raises an error when n! is too large to be converted to a C long integer (n=13 for me). It was enough when I needed it, but it's no itertools.permutations by a long shot.</p>\n"
},
{
"answer_id": 20014561,
"author": "piggybox",
"author_id": 2102764,
"author_profile": "https://Stackoverflow.com/users/2102764",
"pm_score": 3,
"selected": false,
"text": "<p>This is inspired by the Haskell implementation using list comprehension: </p>\n\n<pre><code>def permutation(list):\n if len(list) == 0:\n return [[]]\n else:\n return [[x] + ys for x in list for ys in permutation(delete(list, x))]\n\ndef delete(list, item):\n lc = list[:]\n lc.remove(item)\n return lc\n</code></pre>\n"
},
{
"answer_id": 23732953,
"author": "darxtrix",
"author_id": 2679770,
"author_profile": "https://Stackoverflow.com/users/2679770",
"pm_score": 2,
"selected": false,
"text": "<p>The beauty of recursion:</p>\n\n<pre><code>>>> import copy\n>>> def perm(prefix,rest):\n... for e in rest:\n... new_rest=copy.copy(rest)\n... new_prefix=copy.copy(prefix)\n... new_prefix.append(e)\n... new_rest.remove(e)\n... if len(new_rest) == 0:\n... print new_prefix + new_rest\n... continue\n... perm(new_prefix,new_rest)\n... \n>>> perm([],['a','b','c','d'])\n['a', 'b', 'c', 'd']\n['a', 'b', 'd', 'c']\n['a', 'c', 'b', 'd']\n['a', 'c', 'd', 'b']\n['a', 'd', 'b', 'c']\n['a', 'd', 'c', 'b']\n['b', 'a', 'c', 'd']\n['b', 'a', 'd', 'c']\n['b', 'c', 'a', 'd']\n['b', 'c', 'd', 'a']\n['b', 'd', 'a', 'c']\n['b', 'd', 'c', 'a']\n['c', 'a', 'b', 'd']\n['c', 'a', 'd', 'b']\n['c', 'b', 'a', 'd']\n['c', 'b', 'd', 'a']\n['c', 'd', 'a', 'b']\n['c', 'd', 'b', 'a']\n['d', 'a', 'b', 'c']\n['d', 'a', 'c', 'b']\n['d', 'b', 'a', 'c']\n['d', 'b', 'c', 'a']\n['d', 'c', 'a', 'b']\n['d', 'c', 'b', 'a']\n</code></pre>\n"
},
{
"answer_id": 28256360,
"author": "Cmyker",
"author_id": 1079659,
"author_profile": "https://Stackoverflow.com/users/1079659",
"pm_score": 2,
"selected": false,
"text": "<p>This algorithm is the most effective one, it avoids of array passing and manipulation in recursive calls, works in Python 2, 3:</p>\n\n<pre><code>def permute(items):\n length = len(items)\n def inner(ix=[]):\n do_yield = len(ix) == length - 1\n for i in range(0, length):\n if i in ix: #avoid duplicates\n continue\n if do_yield:\n yield tuple([items[y] for y in ix + [i]])\n else:\n for p in inner(ix + [i]):\n yield p\n return inner()\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>for p in permute((1,2,3)):\n print(p)\n\n(1, 2, 3)\n(1, 3, 2)\n(2, 1, 3)\n(2, 3, 1)\n(3, 1, 2)\n(3, 2, 1)\n</code></pre>\n"
},
{
"answer_id": 30112080,
"author": "manish kumar",
"author_id": 4166033,
"author_profile": "https://Stackoverflow.com/users/4166033",
"pm_score": 2,
"selected": false,
"text": "<pre><code>def pzip(c, seq):\n result = []\n for item in seq:\n for i in range(len(item)+1):\n result.append(item[i:]+c+item[:i])\n return result\n\n\ndef perm(line):\n seq = [c for c in line]\n if len(seq) <=1 :\n return seq\n else:\n return pzip(seq[0], perm(seq[1:]))\n</code></pre>\n"
},
{
"answer_id": 30428753,
"author": "B. M.",
"author_id": 4016285,
"author_profile": "https://Stackoverflow.com/users/4016285",
"pm_score": 3,
"selected": false,
"text": "<p>For performance, a numpy solution inspired by <a href=\"http://www.kcats.org/csci/464/doc/knuth/fascicles/fasc2b.pdf\" rel=\"noreferrer\">Knuth</a>, (p22) :</p>\n\n<pre><code>from numpy import empty, uint8\nfrom math import factorial\n\ndef perms(n):\n f = 1\n p = empty((2*n-1, factorial(n)), uint8)\n for i in range(n):\n p[i, :f] = i\n p[i+1:2*i+1, :f] = p[:i, :f] # constitution de blocs\n for j in range(i):\n p[:i+1, f*(j+1):f*(j+2)] = p[j+1:j+i+2, :f] # copie de blocs\n f = f*(i+1)\n return p[:n, :]\n</code></pre>\n\n<p>Copying large blocs of memory saves time - \nit's 20x faster than <code>list(itertools.permutations(range(n))</code> :</p>\n\n<pre><code>In [1]: %timeit -n10 list(permutations(range(10)))\n10 loops, best of 3: 815 ms per loop\n\nIn [2]: %timeit -n100 perms(10) \n100 loops, best of 3: 40 ms per loop\n</code></pre>\n"
},
{
"answer_id": 32448587,
"author": "Bharatwaja",
"author_id": 3944755,
"author_profile": "https://Stackoverflow.com/users/3944755",
"pm_score": -1,
"selected": false,
"text": "<p>for Python we can use itertools and import both permutations and combinations to solve your problem</p>\n\n<pre><code>from itertools import product, permutations\nA = ([1,2,3])\nprint (list(permutations(sorted(A),2)))\n</code></pre>\n"
},
{
"answer_id": 36102351,
"author": "Miled Louis Rizk",
"author_id": 6023433,
"author_profile": "https://Stackoverflow.com/users/6023433",
"pm_score": 2,
"selected": false,
"text": "<p>Generate all possible permutations</p>\n\n<p>I'm using python3.4:</p>\n\n<pre><code>def calcperm(arr, size):\n result = set([()])\n for dummy_idx in range(size):\n temp = set()\n for dummy_lst in result:\n for dummy_outcome in arr:\n if dummy_outcome not in dummy_lst:\n new_seq = list(dummy_lst)\n new_seq.append(dummy_outcome)\n temp.add(tuple(new_seq))\n result = temp\n return result\n</code></pre>\n\n<p>Test Cases:</p>\n\n<pre><code>lst = [1, 2, 3, 4]\n#lst = [\"yellow\", \"magenta\", \"white\", \"blue\"]\nseq = 2\nfinal = calcperm(lst, seq)\nprint(len(final))\nprint(final)\n</code></pre>\n"
},
{
"answer_id": 38793421,
"author": "Karo Castro-Wunsch",
"author_id": 4725204,
"author_profile": "https://Stackoverflow.com/users/4725204",
"pm_score": 2,
"selected": false,
"text": "<p>I see a <em>lot</em> of iteration going on inside these recursive functions, not exactly <em>pure</em> recursion...</p>\n\n<p>so for those of you who cannot abide by even a single loop, here's a gross, totally unnecessary fully recursive solution</p>\n\n<pre><code>def all_insert(x, e, i=0):\n return [x[0:i]+[e]+x[i:]] + all_insert(x,e,i+1) if i<len(x)+1 else []\n\ndef for_each(X, e):\n return all_insert(X[0], e) + for_each(X[1:],e) if X else []\n\ndef permute(x):\n return [x] if len(x) < 2 else for_each( permute(x[1:]) , x[0])\n\n\nperms = permute([1,2,3])\n</code></pre>\n"
},
{
"answer_id": 43018229,
"author": "anhldbk",
"author_id": 197896,
"author_profile": "https://Stackoverflow.com/users/197896",
"pm_score": 1,
"selected": false,
"text": "<p>Another solution:</p>\n\n<pre><code>def permutation(flag, k =1 ):\n N = len(flag)\n for i in xrange(0, N):\n if flag[i] != 0:\n continue\n flag[i] = k \n if k == N:\n print flag\n permutation(flag, k+1)\n flag[i] = 0\n\npermutation([0, 0, 0])\n</code></pre>\n"
},
{
"answer_id": 49072115,
"author": "abelenky",
"author_id": 34824,
"author_profile": "https://Stackoverflow.com/users/34824",
"pm_score": 0,
"selected": false,
"text": "<p>My Python Solution:</p>\n\n<pre><code>def permutes(input,offset):\n if( len(input) == offset ):\n return [''.join(input)]\n\n result=[] \n for i in range( offset, len(input) ):\n input[offset], input[i] = input[i], input[offset]\n result = result + permutes(input,offset+1)\n input[offset], input[i] = input[i], input[offset]\n return result\n\n# input is a \"string\"\n# return value is a list of strings\ndef permutations(input):\n return permutes( list(input), 0 )\n\n# Main Program\nprint( permutations(\"wxyz\") )\n</code></pre>\n"
},
{
"answer_id": 50311529,
"author": "Ilgorbek Kuchkarov",
"author_id": 6283828,
"author_profile": "https://Stackoverflow.com/users/6283828",
"pm_score": 0,
"selected": false,
"text": "<pre><code>def permutation(word, first_char=None):\n if word == None or len(word) == 0: return []\n if len(word) == 1: return [word]\n\n result = []\n first_char = word[0]\n for sub_word in permutation(word[1:], first_char):\n result += insert(first_char, sub_word)\n return sorted(result)\n\ndef insert(ch, sub_word):\n arr = [ch + sub_word]\n for i in range(len(sub_word)):\n arr.append(sub_word[i:] + ch + sub_word[:i])\n return arr\n\n\nassert permutation(None) == []\nassert permutation('') == []\nassert permutation('1') == ['1']\nassert permutation('12') == ['12', '21']\n\nprint permutation('abc')\n</code></pre>\n\n<p>Output: ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']</p>\n"
},
{
"answer_id": 53785851,
"author": "Anatoly Alekseev",
"author_id": 4334120,
"author_profile": "https://Stackoverflow.com/users/4334120",
"pm_score": 2,
"selected": false,
"text": "<p>To save you folks possible hours of searching and experimenting, here's the non-recursive permutaions solution in Python which also works with Numba (as of v. 0.41):</p>\n\n<pre><code>@numba.njit()\ndef permutations(A, k):\n r = [[i for i in range(0)]]\n for i in range(k):\n r = [[a] + b for a in A for b in r if (a in b)==False]\n return r\npermutations([1,2,3],3)\n[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n</code></pre>\n\n<p>To give an impression about performance:</p>\n\n<pre><code>%timeit permutations(np.arange(5),5)\n\n243 µs ± 11.1 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)\ntime: 406 ms\n\n%timeit list(itertools.permutations(np.arange(5),5))\n15.9 µs ± 8.61 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\ntime: 12.9 s\n</code></pre>\n\n<p>So use this version only if you have to call it from njitted function, otherwise prefer itertools implementation.</p>\n"
},
{
"answer_id": 55070316,
"author": "Hello.World",
"author_id": 8850552,
"author_profile": "https://Stackoverflow.com/users/8850552",
"pm_score": 0,
"selected": false,
"text": "<p>Using <code>Counter</code></p>\n\n<pre><code>from collections import Counter\n\ndef permutations(nums):\n ans = [[]]\n cache = Counter(nums)\n\n for idx, x in enumerate(nums):\n result = []\n for items in ans:\n cache1 = Counter(items)\n for id, n in enumerate(nums):\n if cache[n] != cache1[n] and items + [n] not in result:\n result.append(items + [n])\n\n ans = result\n return ans\npermutations([1, 2, 2])\n> [[1, 2, 2], [2, 1, 2], [2, 2, 1]]\n\n</code></pre>\n"
},
{
"answer_id": 55421084,
"author": "Tatsu",
"author_id": 5938224,
"author_profile": "https://Stackoverflow.com/users/5938224",
"pm_score": 2,
"selected": false,
"text": "<p><strong>ANOTHER APPROACH (without libs)</strong></p>\n\n<pre><code>def permutation(input):\n if len(input) == 1:\n return input if isinstance(input, list) else [input]\n\n result = []\n for i in range(len(input)):\n first = input[i]\n rest = input[:i] + input[i + 1:]\n rest_permutation = permutation(rest)\n for p in rest_permutation:\n result.append(first + p)\n return result\n</code></pre>\n\n<p><strong>Input can be a string or a list</strong></p>\n\n<pre><code>print(permutation('abcd'))\nprint(permutation(['a', 'b', 'c', 'd']))\n</code></pre>\n"
},
{
"answer_id": 59433823,
"author": "Richard Ambler",
"author_id": 1340742,
"author_profile": "https://Stackoverflow.com/users/1340742",
"pm_score": 3,
"selected": false,
"text": "<p>Disclaimer: shameless plug by package author. :)</p>\n<p>The <a href=\"https://pypi.org/project/trotter/\" rel=\"nofollow noreferrer\">trotter</a> package is different from most implementations in that it generates pseudo lists that don't actually contain permutations but rather describe mappings between permutations and respective positions in an ordering, making it possible to work with very large 'lists' of permutations, as shown in <a href=\"https://permutation-products.netlify.com/\" rel=\"nofollow noreferrer\">this demo</a> which performs pretty instantaneous operations and look-ups in a pseudo-list 'containing' all the permutations of the letters in the alphabet, without using more memory or processing than a typical web page.</p>\n<p>In any case, to generate a list of permutations, we can do the following.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import trotter\n\nmy_permutations = trotter.Permutations(3, [1, 2, 3])\n\nprint(my_permutations)\n\nfor p in my_permutations:\n print(p)\n</code></pre>\n<p>Output:</p>\n<pre>\nA pseudo-list containing 6 3-permutations of [1, 2, 3].\n[1, 2, 3]\n[1, 3, 2]\n[3, 1, 2]\n[3, 2, 1]\n[2, 3, 1]\n[2, 1, 3]\n</pre>\n"
},
{
"answer_id": 59593816,
"author": "Maverick Meerkat",
"author_id": 6296435,
"author_profile": "https://Stackoverflow.com/users/6296435",
"pm_score": 4,
"selected": false,
"text": "<p>Regular implementation (no yield - will do everything in memory):</p>\n\n<pre><code>def getPermutations(array):\n if len(array) == 1:\n return [array]\n permutations = []\n for i in range(len(array)): \n # get all perm's of subarray w/o current item\n perms = getPermutations(array[:i] + array[i+1:]) \n for p in perms:\n permutations.append([array[i], *p])\n return permutations\n</code></pre>\n\n<p>Yield implementation:</p>\n\n<pre><code>def getPermutations(array):\n if len(array) == 1:\n yield array\n else:\n for i in range(len(array)):\n perms = getPermutations(array[:i] + array[i+1:])\n for p in perms:\n yield [array[i], *p]\n</code></pre>\n\n<p>The basic idea is to go over all the elements in the array for the 1st position, and then in 2nd position go over all the rest of the elements without the chosen element for the 1st, etc. You can do this with <strong>recursion</strong>, where the stop criteria is getting to an array of 1 element - in which case you return that array.</p>\n\n<p><a href=\"https://i.stack.imgur.com/eX3df.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/eX3df.jpg\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 62189160,
"author": "Dritte Saskaita",
"author_id": 12278470,
"author_profile": "https://Stackoverflow.com/users/12278470",
"pm_score": 0,
"selected": false,
"text": "<pre><code>def permuteArray (arr):\n\n arraySize = len(arr)\n\n permutedList = []\n\n if arraySize == 1:\n return [arr]\n\n i = 0\n\n for item in arr:\n\n for elem in permuteArray(arr[:i] + arr[i + 1:]):\n permutedList.append([item] + elem)\n\n i = i + 1 \n\n return permutedList\n</code></pre>\n\n<p>I intended to not exhaust every possibility in a new line to make it somewhat unique.</p>\n"
},
{
"answer_id": 62770287,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Anyway we could use <a href=\"https://docs.sympy.org/latest/\" rel=\"nofollow noreferrer\">sympy</a> library , also support for multiset permutations</p>\n<pre><code>import sympy\nfrom sympy.utilities.iterables import multiset_permutations\nt = [1,2,3]\np = list(multiset_permutations(t))\nprint(p)\n\n# [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]\n</code></pre>\n<p>Answer is highly inspired by <a href=\"https://stackoverflow.com/questions/41210142/get-all-permutations-of-a-numpy-array/41210450\">Get all permutations of a numpy array</a></p>\n"
},
{
"answer_id": 64471115,
"author": "Harvey Mao",
"author_id": 10665136,
"author_profile": "https://Stackoverflow.com/users/10665136",
"pm_score": 0,
"selected": false,
"text": "<pre><code>from typing import List\nimport time, random\n\ndef measure_time(func):\n def wrapper_time(*args, **kwargs):\n start_time = time.perf_counter()\n res = func(*args, **kwargs)\n end_time = time.perf_counter()\n return res, end_time - start_time\n\n return wrapper_time\n\n\nclass Solution:\n def permute(self, nums: List[int], method: int = 1) -> List[List[int]]:\n perms = []\n perm = []\n if method == 1:\n _, time_perm = self._permute_recur(nums, 0, len(nums) - 1, perms)\n elif method == 2:\n _, time_perm = self._permute_recur_agian(nums, perm, perms)\n print(perm)\n return perms, time_perm\n\n @measure_time\n def _permute_recur(self, nums: List[int], l: int, r: int, perms: List[List[int]]):\n # base case\n if l == r:\n perms.append(nums.copy())\n\n for i in range(l, r + 1):\n nums[l], nums[i] = nums[i], nums[l]\n self._permute_recur(nums, l + 1, r , perms)\n nums[l], nums[i] = nums[i], nums[l]\n\n @measure_time\n def _permute_recur_agian(self, nums: List[int], perm: List[int], perms_list: List[List[int]]):\n """\n The idea is similar to nestedForLoops visualized as a recursion tree.\n """\n if nums:\n for i in range(len(nums)):\n # perm.append(nums[i]) mistake, perm will be filled with all nums's elements.\n # Method1 perm_copy = copy.deepcopy(perm)\n # Method2 add in the parameter list using + (not in place)\n # caveat: list.append is in-place , which is useful for operating on global element perms_list\n # Note that:\n # perms_list pass by reference. shallow copy\n # perm + [nums[i]] pass by value instead of reference.\n self._permute_recur_agian(nums[:i] + nums[i+1:], perm + [nums[i]], perms_list)\n else:\n # Arrive at the last loop, i.e. leaf of the recursion tree.\n perms_list.append(perm)\n\n\n\nif __name__ == "__main__":\n array = [random.randint(-10, 10) for _ in range(3)]\n sol = Solution()\n # perms, time_perm = sol.permute(array, 1)\n perms2, time_perm2 = sol.permute(array, 2)\n print(perms2)\n # print(perms, perms2)\n # print(time_perm, time_perm2)\n```\n</code></pre>\n"
},
{
"answer_id": 65241289,
"author": "Michael Hodel",
"author_id": 12363750,
"author_profile": "https://Stackoverflow.com/users/12363750",
"pm_score": 0,
"selected": false,
"text": "<p>in case anyone fancies this ugly one-liner (works only for strings though):</p>\n<pre><code>def p(a):\n return a if len(a) == 1 else [[a[i], *j] for i in range(len(a)) for j in p(a[:i] + a[i + 1:])]\n</code></pre>\n"
},
{
"answer_id": 65542989,
"author": "Bhaskar13",
"author_id": 11930483,
"author_profile": "https://Stackoverflow.com/users/11930483",
"pm_score": 1,
"selected": false,
"text": "<p>This is the asymptotically optimal way O(n*n!) of generating permutations after initial sorting.</p>\n<p>There are n! permutations at most and hasNextPermutation(..) runs in O(n) time complexity</p>\n<p>In 3 steps, <br></p>\n<ol>\n<li>Find largest j such that a[j] can be increased</li>\n<li>Increase a[j] by smallest feasible amount</li>\n<li>Find lexicogrpahically least way to extend the new a[0..j]</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>'''\nLexicographic permutation generation\n\nconsider example array state of [1,5,6,4,3,2] for sorted [1,2,3,4,5,6]\nafter 56432(treat as number) ->nothing larger than 6432(using 6,4,3,2) beginning with 5\nso 6 is next larger and 2345(least using numbers other than 6)\nso [1, 6,2,3,4,5]\n'''\ndef hasNextPermutation(array, len):\n ' Base Condition '\n if(len ==1):\n return False\n '''\n Set j = last-2 and find first j such that a[j] < a[j+1]\n If no such j(j==-1) then we have visited all permutations\n after this step a[j+1]>=..>=a[len-1] and a[j]<a[j+1]\n\n a[j]=5 or j=1, 6>5>4>3>2\n '''\n j = len -2\n while (j >= 0 and array[j] >= array[j + 1]):\n j= j-1\n if(j==-1):\n return False\n # print(f"After step 2 for j {j} {array}")\n '''\n decrease l (from n-1 to j) repeatedly until a[j]<a[l]\n Then swap a[j], a[l]\n a[l] is the smallest element > a[j] that can follow a[l]...a[j-1] in permutation\n before swap we have a[j+1]>=..>=a[l-1]>=a[l]>a[j]>=a[l+1]>=..>=a[len-1]\n after swap -> a[j+1]>=..>=a[l-1]>=a[j]>a[l]>=a[l+1]>=..>=a[len-1]\n\n a[l]=6 or l=2, j=1 just before swap [1, 5, 6, 4, 3, 2] \n after swap [1, 6, 5, 4, 3, 2] a[l]=5, a[j]=6\n '''\n l = len -1\n while(array[j] >= array[l]):\n l = l-1\n # print(f"After step 3 for l={l}, j={j} before swap {array}")\n array[j], array[l] = array[l], array[j]\n # print(f"After step 3 for l={l} j={j} after swap {array}")\n '''\n Reverse a[j+1...len-1](both inclusive)\n\n after reversing [1, 6, 2, 3, 4, 5]\n '''\n array[j+1:len] = reversed(array[j+1:len])\n # print(f"After step 4 reversing {array}")\n return True\n\narray = [1,2,4,4,5]\narray.sort()\nlen = len(array)\ncount =1\nprint(array)\n'''\nThe algorithm visits every permutation in lexicographic order\ngenerating one by one\n'''\nwhile(hasNextPermutation(array, len)):\n print(array)\n count = count +1\n# The number of permutations will be n! if no duplicates are present, else less than that\n# [1,4,3,3,2] -> 5!/2!=60\nprint(f"Number of permutations: {count}")\n\n\n</code></pre>\n"
},
{
"answer_id": 68712244,
"author": "Alon Barad",
"author_id": 8622976,
"author_profile": "https://Stackoverflow.com/users/8622976",
"pm_score": 3,
"selected": false,
"text": "<p>If you don't want to use the builtin methods such as:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import itertools\nlist(itertools.permutations([1, 2, 3]))\n</code></pre>\n<p>you can implement permute function yourself</p>\n<pre class=\"lang-py prettyprint-override\"><code>from collections.abc import Iterable\n\n\ndef permute(iterable: Iterable[str]) -> set[str]:\n perms = set()\n\n if len(iterable) == 1:\n return {*iterable}\n\n for index, char in enumerate(iterable):\n perms.update([char + perm for perm in permute(iterable[:index] + iterable[index + 1:])])\n\n return perms\n\n\nif __name__ == '__main__':\n print(permute('abc'))\n # {'bca', 'abc', 'cab', 'acb', 'cba', 'bac'}\n print(permute(['1', '2', '3']))\n # {'123', '312', '132', '321', '213', '231'}\n</code></pre>\n"
},
{
"answer_id": 69397777,
"author": "0script0",
"author_id": 3615178,
"author_profile": "https://Stackoverflow.com/users/3615178",
"pm_score": 1,
"selected": false,
"text": "<pre><code>def permutate(l):\n for i, x in enumerate(l):\n for y in l[i + 1:]:\n yield x, y\n\n\nif __name__ == '__main__':\n print(list(permutate(list('abcd'))))\n print(list(permutate([1, 2, 3, 4])))\n\n#[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]\n#[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]\n</code></pre>\n"
},
{
"answer_id": 71197512,
"author": "Yilmaz",
"author_id": 10262805,
"author_profile": "https://Stackoverflow.com/users/10262805",
"pm_score": 0,
"selected": false,
"text": "<p>Solving with recursion, iterate through elements, take i'th element, and ask yourself: 'What is the permutation of rest of items` till no more element left.</p>\n<p>I explained the solution here: <a href=\"https://www.youtube.com/watch?v=_7GE7psS2b4\" rel=\"nofollow noreferrer\">https://www.youtube.com/watch?v=_7GE7psS2b4</a></p>\n<pre><code>class Solution:\n def permute(self,nums:List[int])->List[List[int]]:\n res=[]\n def dfs(nums,path):\n if len(nums)==0:\n res.append(path)\n for i in range(len(nums)):\n dfs(nums[:i]+nums[i+1:],path+[nums[i]])\n dfs(nums,[])\n return res\n</code></pre>\n"
},
{
"answer_id": 71726156,
"author": "Splendor",
"author_id": 2516816,
"author_profile": "https://Stackoverflow.com/users/2516816",
"pm_score": 0,
"selected": false,
"text": "<p>In case the user wants to keep all permutations in a list, the following code can be used:</p>\n<pre><code>def get_permutations(nums, p_list=[], temp_items=[]):\n if not nums:\n return\n elif len(nums) == 1:\n new_items = temp_items+[nums[0]]\n p_list.append(new_items)\n return\n else:\n for i in range(len(nums)):\n temp_nums = nums[:i]+nums[i+1:]\n new_temp_items = temp_items + [nums[i]]\n get_permutations(temp_nums, p_list, new_temp_items)\n\nnums = [1,2,3]\np_list = []\n\nget_permutations(nums, p_list)\n\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5412/"
]
| The Eclipse projects are all stored in the Eclipse Foundation CVS servers. Using the source is a great way to debug your code and to figure out how to do new things.
Unfortunately in a large software project like BIRT, it can be difficult to know which projects and versions are required for a particular build. So what is the best way to get the source for a particular build? | Use [`itertools.permutations`](https://docs.python.org/3/library/itertools.html#itertools.permutations) from the **standard library**:
```
import itertools
list(itertools.permutations([1, 2, 3]))
```
---
Adapted from [here](http://code.activestate.com/recipes/252178/) is a demonstration of how `itertools.permutations` might be implemented:
```
def permutations(elements):
if len(elements) <= 1:
yield elements
return
for perm in permutations(elements[1:]):
for i in range(len(elements)):
# nb elements[0:1] works in both string and list contexts
yield perm[:i] + elements[0:1] + perm[i:]
```
A couple of alternative approaches are listed in the documentation of `itertools.permutations`. Here's one:
```
def permutations(iterable, r=None):
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = range(n)
cycles = range(n, n-r, -1)
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
```
And another, based on `itertools.product`:
```
def permutations(iterable, r=None):
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
for indices in product(range(n), repeat=r):
if len(set(indices)) == r:
yield tuple(pool[i] for i in indices)
``` |
104,458 | <p>How can styles be applied to CheckBoxList ListItems. Unlike other controls, such as the Repeater where you can specify <code><ItemStyle></code>, you can't seem to specify a style for each individual control.</p>
<p>Is there some sort of work around?</p>
| [
{
"answer_id": 104502,
"author": "Andrew Burgess",
"author_id": 12096,
"author_profile": "https://Stackoverflow.com/users/12096",
"pm_score": 4,
"selected": false,
"text": "<p>It seems the best way to do this is to create a new CssClass. ASP.NET translates CheckBoxList into a table structure.</p>\n\n<p>Using something like</p>\n\n<p>Style.css</p>\n\n<pre><code>.chkboxlist td \n{\n font-size:x-large;\n}\n</code></pre>\n\n<p>Page.aspx</p>\n\n<pre><code><asp:CheckBoxList ID=\"chkboxlist1\" runat=\"server\" CssClass=\"chkboxlist\" />\n</code></pre>\n\n<p>will do the trick</p>\n"
},
{
"answer_id": 104589,
"author": "Cyberherbalist",
"author_id": 16964,
"author_profile": "https://Stackoverflow.com/users/16964",
"pm_score": 6,
"selected": true,
"text": "<p>You can add Attributes to ListItems programmatically as follows.</p>\n\n<p>Say you've got a CheckBoxList and you are adding ListItems. You can add Attributes along the way.</p>\n\n<pre><code>ListItem li = new ListItem(\"Richard Byrd\", \"11\");\nli.Selected = false;\nli.Attributes.Add(\"Style\", \"color: red;\");\nCheckBoxList1.Items.Add(li);\n</code></pre>\n\n<p>This will make the color of the listitem text red. Experiment and have fun.</p>\n"
},
{
"answer_id": 118373,
"author": "CMPalmer",
"author_id": 14894,
"author_profile": "https://Stackoverflow.com/users/14894",
"pm_score": 3,
"selected": false,
"text": "<p>In addition to Andrew's answer...</p>\n\n<p>Depending on what other attributes you put on a <code>CheckBoxList</code> or <code>RadioButtonList</code>, or whatever, ASP.Net will render the output using different structures. For example, if you set <code>RepeatLayout=\"Flow\"</code>, it won't render as a TABLE, so you have to be careful of what descendant selectors you use in your CSS file.</p>\n\n<p>In <em>most</em> cases, you can can just do a \"View Source\" on your rendered page, maybe on a couple of different browsers, and figure out what ASP.Net is doing. There is a danger, though, that new versions of the server controls or different browsers will render them differently.</p>\n\n<p>If you want to style a particular list item or set of list items differently without adding in attributes in the code-behind, you can use CSS attribute selectors. The only drawback to that is that they aren't supported in IE6. <a href=\"http://jquery.com\" rel=\"nofollow noreferrer\">jQuery</a> fully supports CSS 3 style attribute selectors, so you could probably also use it for wider browser support.</p>\n"
},
{
"answer_id": 9632437,
"author": "Jon White",
"author_id": 1259067,
"author_profile": "https://Stackoverflow.com/users/1259067",
"pm_score": 3,
"selected": false,
"text": "<p>You can also achieve this in the markup.</p>\n\n<pre><code><asp:ListItem Text=\"Good\" Value=\"True\" style=\"background-color:green;color:white\" />\n<br />\n<asp:ListItem Text=\"Bad\" Value=\"False\" style=\"background-color:red;color:white\" />\n</code></pre>\n\n<p>The word Style will be underlined with the warning that <em>Attribute 'style' is not a valid attribute of element 'ListItem'.</em>, but the items are formatted as desired anyway.</p>\n"
},
{
"answer_id": 11250136,
"author": "John",
"author_id": 1489376,
"author_profile": "https://Stackoverflow.com/users/1489376",
"pm_score": 1,
"selected": false,
"text": "<pre><code>public bool Repeater_Bind()\n{\n RadioButtonList objRadioButton = (RadioButtonList)eventArgs.Item.FindControl(\"rbList\");\n if (curQuestionInfo.CorrectAnswer != -1) {\n objRadioButton.Items[curQuestionInfo.CorrectAnswer].Attributes.Add(\"Style\", \"color: #b4fbb1;\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 19596627,
"author": "SubhoM",
"author_id": 2547399,
"author_profile": "https://Stackoverflow.com/users/2547399",
"pm_score": 2,
"selected": false,
"text": "<p>You can even have different font styles and color for each word. </p>\n\n<pre><code><asp:ListItem Text=\"Other (<span style=font-weight:bold;>please </span><span>style=color:Red;font-weight:bold;>specify</span>):\" Value=\"10\"></asp:ListItem>\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12096/"
]
| How can styles be applied to CheckBoxList ListItems. Unlike other controls, such as the Repeater where you can specify `<ItemStyle>`, you can't seem to specify a style for each individual control.
Is there some sort of work around? | You can add Attributes to ListItems programmatically as follows.
Say you've got a CheckBoxList and you are adding ListItems. You can add Attributes along the way.
```
ListItem li = new ListItem("Richard Byrd", "11");
li.Selected = false;
li.Attributes.Add("Style", "color: red;");
CheckBoxList1.Items.Add(li);
```
This will make the color of the listitem text red. Experiment and have fun. |
104,485 | <p>I'm trying to skin HTML output which I don't have control over. One of the elements is a <code>div</code> with a <code>style="overflow: auto"</code> attribute.<br>
Is there a way in CSS to force that <code>div</code> to use <code>overflow: hidden;</code>?</p>
| [
{
"answer_id": 104497,
"author": "17 of 26",
"author_id": 2284,
"author_profile": "https://Stackoverflow.com/users/2284",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I know, styles on the actual HTML elements override anything you can do in separate CSS style.</p>\n\n<p>You can, however, use Javascript to override it.</p>\n"
},
{
"answer_id": 104499,
"author": "Magnar",
"author_id": 1123,
"author_profile": "https://Stackoverflow.com/users/1123",
"pm_score": 7,
"selected": true,
"text": "<p>You can add <code>!important</code> to the end of your style, like this:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>element {\n overflow: hidden !important;\n}\n</code></pre>\n\n<p>This is something you should not rely on normally, but in your case that's the best option. Changing the value in Javascript strays from the best practice of separating markup, presentation, and behavior (html/css/javascript).</p>\n"
},
{
"answer_id": 104501,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 4,
"selected": false,
"text": "<p>Have you tried setting <code>!important</code> in the CSS file? Something like:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#mydiv { overflow: hidden !important; }\n</code></pre>\n"
},
{
"answer_id": 104507,
"author": "DanWoolston",
"author_id": 19133,
"author_profile": "https://Stackoverflow.com/users/19133",
"pm_score": 3,
"selected": false,
"text": "<p>Not sure if this would work or not, haven't tested it with <code>overflow</code>.</p>\n\n<pre><code>overflow:hidden !important\n</code></pre>\n\n<p>maybe?</p>\n"
},
{
"answer_id": 104509,
"author": "BrewinBombers",
"author_id": 5989,
"author_profile": "https://Stackoverflow.com/users/5989",
"pm_score": 2,
"selected": false,
"text": "<p>If the div has an inline style declaration, the only way to modify it without changing the source is with JavaScript. Inline style attributes 'win' every time in CSS.</p>\n"
},
{
"answer_id": 104683,
"author": "TheZenker",
"author_id": 10552,
"author_profile": "https://Stackoverflow.com/users/10552",
"pm_score": 2,
"selected": false,
"text": "<p>Magnar is correct as explained by the W3C spec pasted below. Seems the !important keyword was added to allow users to override even \"baked in\" style settings at the element level. Since you are in the situation where you do not have control over the html this may be your best option, though it would not be a normal design pattern.</p>\n\n<p><a href=\"http://www.w3.org/TR/CSS2/cascade.html\" rel=\"nofollow noreferrer\">W3C CSS Specs</a></p>\n\n<p>Excerpt:</p>\n\n<blockquote>\n <p>6.4.2 !important rules\n CSS attempts to create a balance of power between author and user style\n sheets. By default, rules in an\n author's style sheet override those in\n a user's style sheet (see cascade rule\n 3). </p>\n\n<pre><code>However, for balance, an \"!important\" declaration (the keywords\n</code></pre>\n \n <p>\"!\" and \"important\" follow the\n declaration) takes precedence over a\n normal declaration. Both author and\n user style sheets may contain\n \"!important\" declarations, and user\n \"!important\" rules override author\n \"!important\" rules. This CSS feature\n improves accessibility of documents by\n giving users with special requirements\n (large fonts, color combinations,\n etc.) control over presentation. </p>\n\n<pre><code>Note. This is a semantic change since CSS1. In CSS1, author\n</code></pre>\n \n <p>\"!important\" rules took precedence\n over user \"!important\" rules. </p>\n\n<pre><code>Declaring a shorthand property (e.g., 'background') to be\n</code></pre>\n \n <p>\"!important\" is equivalent to\n declaring all of its sub-properties to\n be \"!important\". </p>\n\n<pre><code>Example(s):\n\nThe first rule in the user's style sheet in the following example\n</code></pre>\n \n <p>contains an \"!important\" declaration,\n which overrides the corresponding\n declaration in the author's styles\n sheet. The second declaration will\n also win due to being marked\n \"!important\". However, the third rule\n in the user's style sheet is not\n \"!important\" and will therefore lose\n to the second rule in the author's\n style sheet (which happens to set\n style on a shorthand property). Also,\n the third author rule will lose to the\n second author rule since the second\n rule is \"!important\". This shows that\n \"!important\" declarations have a\n function also within author style\n sheets. </p>\n\n<pre><code>/* From the user's style sheet */\nP { text-indent: 1em ! important }\nP { font-style: italic ! important }\nP { font-size: 18pt }\n\n/* From the author's style sheet */\nP { text-indent: 1.5em !important }\nP { font: 12pt sans-serif !important }\nP { font-size: 24pt }\n</code></pre>\n</blockquote>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4898/"
]
| I'm trying to skin HTML output which I don't have control over. One of the elements is a `div` with a `style="overflow: auto"` attribute.
Is there a way in CSS to force that `div` to use `overflow: hidden;`? | You can add `!important` to the end of your style, like this:
```css
element {
overflow: hidden !important;
}
```
This is something you should not rely on normally, but in your case that's the best option. Changing the value in Javascript strays from the best practice of separating markup, presentation, and behavior (html/css/javascript). |
104,487 | <p>Right now I'm doing something like this:</p>
<pre><code>RewriteRule ^/?logout(/)?$ logout.php
RewriteRule ^/?config(/)?$ config.php
</code></pre>
<p>I would much rather have one rules that would do the same thing for each url, so I don't have to keep adding them every time I add a new file.</p>
<p>Also, I like to match things like '/config/new' to 'config_new.php' if that is possible. I am guessing some regexp would let me accomplish this?</p>
| [
{
"answer_id": 104573,
"author": "Gabriel Ross",
"author_id": 10751,
"author_profile": "https://Stackoverflow.com/users/10751",
"pm_score": 3,
"selected": true,
"text": "<p>Try:</p>\n\n<p>RewriteRule ^/?(\\w+)/?$ $1.php</p>\n\n<p>the $1 is the content of the first captured string in brackets. The brackets around the 2nd slash are not needed.</p>\n\n<p>edit: For the other match, try this:</p>\n\n<p>RewriteRule ^/?(\\w+)/(\\w+)/?$ $1_$2.php</p>\n"
},
{
"answer_id": 104596,
"author": "Jason Terk",
"author_id": 12582,
"author_profile": "https://Stackoverflow.com/users/12582",
"pm_score": 1,
"selected": false,
"text": "<p>Mod rewrite can't do (potentially) boundless replaces like you want to do in the second part of your question. But check out the External Rewriting Engine at the bottom of the <a href=\"http://httpd.apache.org/docs/2.2/misc/rewriteguide.html\" rel=\"nofollow noreferrer\">Apache URL Rewriting Guide</a>:</p>\n\n<blockquote>\n <p>External Rewriting Engine</p>\n \n <p>Description:</p>\n \n <p>A FAQ: How can we solve the FOO/BAR/QUUX/etc. problem? There seems no solution by the use of mod_rewrite...\n Solution:</p>\n \n <p>Use an external RewriteMap, i.e. a program which acts like a RewriteMap. It is run once on startup of Apache receives the requested URLs on STDIN and has to put the resulting (usually rewritten) URL on STDOUT (same order!).</p>\n\n<pre><code>RewriteEngine on\nRewriteMap quux-map prg:/path/to/map.quux.pl\nRewriteRule ^/~quux/(.*)$ /~quux/${quux-map:$1}\n\n#!/path/to/perl\n\n# disable buffered I/O which would lead\n# to deadloops for the Apache server\n$| = 1;\n\n# read URLs one per line from stdin and\n# generate substitution URL on stdout\nwhile (<>) {\n s|^foo/|bar/|;\n print $_;\n}\n</code></pre>\n \n <p>This is a demonstration-only example and just rewrites all URLs /~quux/foo/... to /~quux/bar/.... Actually you can program whatever you like. But notice that while such maps can be used also by an average user, only the system administrator can define it.</p>\n</blockquote>\n"
},
{
"answer_id": 104614,
"author": "Aeon",
"author_id": 13289,
"author_profile": "https://Stackoverflow.com/users/13289",
"pm_score": 2,
"selected": false,
"text": "<p>I would do something like this:</p>\n\n<pre><code>RewriteRule ^/?(logout|config|foo)/?$ $1.php\nRewriteRule ^/?(logout|config|foo)/(new|edit|delete)$ $1_$2.php\n</code></pre>\n\n<p>I prefer to explicitly list the url's I want to match, so that I don't have to worry about static content or adding new things later that don't need to be rewritten to php files. </p>\n\n<p>The above is ok if all sub url's are valid for all root url's (<code>book/new</code>, <code>movie/new</code>, <code>user/new</code>), but not so good if you want to have different sub url's depending on root action (<code>logout/new</code> doesn't make much sense). You can handle that either with a more complex regex, or by routing everything to a single php file which will determine what files to include and display based on the url.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15000/"
]
| Right now I'm doing something like this:
```
RewriteRule ^/?logout(/)?$ logout.php
RewriteRule ^/?config(/)?$ config.php
```
I would much rather have one rules that would do the same thing for each url, so I don't have to keep adding them every time I add a new file.
Also, I like to match things like '/config/new' to 'config\_new.php' if that is possible. I am guessing some regexp would let me accomplish this? | Try:
RewriteRule ^/?(\w+)/?$ $1.php
the $1 is the content of the first captured string in brackets. The brackets around the 2nd slash are not needed.
edit: For the other match, try this:
RewriteRule ^/?(\w+)/(\w+)/?$ $1\_$2.php |
104,516 | <p>In PHP, the HEREDOC string declarations are really useful for outputting a block of html. You can have it parse in variables just by prefixing them with $, but for more complicated syntax (like $var[2][3]), you have to put your expression inside {} braces.</p>
<p>In PHP 5, it <em>is</em> possible to actually make function calls within {} braces inside a HEREDOC string, but you have to go through a bit of work. The function name itself has to be stored in a variable, and you have to call it like it is a dynamically-named function. For example:</p>
<pre><code>$fn = 'testfunction';
function testfunction() { return 'ok'; }
$string = <<< heredoc
plain text and now a function: {$fn()}
heredoc;
</code></pre>
<p>As you can see, this is a bit more messy than just:</p>
<pre><code>$string = <<< heredoc
plain text and now a function: {testfunction()}
heredoc;
</code></pre>
<p>There are other ways besides the first code example, such as breaking out of the HEREDOC to call the function, or reversing the issue and doing something like:</p>
<pre><code>?>
<!-- directly output html and only breaking into php for the function -->
plain text and now a function: <?PHP print testfunction(); ?>
</code></pre>
<p>The latter has the disadvantage that the output is directly put into the output stream (unless I'm using output buffering), which might not be what I want.</p>
<p>So, the essence of my question is: is there a more elegant way to approach this?</p>
<p><b>Edit based on responses:</b> It certainly does seem like some kind of template engine would make my life much easier, but it would require me basically invert my usual PHP style. Not that that's a bad thing, but it explains my inertia.. I'm up for figuring out ways to make life easier though, so I'm looking into templates now.</p>
| [
{
"answer_id": 104556,
"author": "boxxar",
"author_id": 15732,
"author_profile": "https://Stackoverflow.com/users/15732",
"pm_score": 6,
"selected": false,
"text": "<p>I would do the following:</p>\n\n<pre><code>$string = <<< heredoc\nplain text and now a function: %s\nheredoc;\n$string = sprintf($string, testfunction());\n</code></pre>\n\n<p>Not sure if you'd consider this to be more elegant ...</p>\n"
},
{
"answer_id": 104645,
"author": "Peter Bailey",
"author_id": 8815,
"author_profile": "https://Stackoverflow.com/users/8815",
"pm_score": 7,
"selected": true,
"text": "<p>I would not use HEREDOC at all for this, personally. It just doesn't make for a good \"template building\" system. All your HTML is locked down in a string which has several disadvantages</p>\n\n<ul>\n<li>No option for WYSIWYG</li>\n<li>No code completion for HTML from IDEs</li>\n<li>Output (HTML) locked to logic files</li>\n<li>You end up having to use hacks like what you're trying to do now to achieve more complex templating, such as looping</li>\n</ul>\n\n<p>Get a basic template engine, or just use PHP with includes - it's why the language has the <code><?php</code> and <code>?></code> delimiters.</p>\n\n<p><strong>template_file.php</strong></p>\n\n<pre><code><html>\n<head>\n <title><?php echo $page_title; ?></title>\n</head>\n<body>\n <?php echo getPageContent(); ?>\n</body>\n</code></pre>\n\n<p><strong>index.php</strong></p>\n\n<pre><code><?php\n\n$page_title = \"This is a simple demo\";\n\nfunction getPageContent() {\n return '<p>Hello World!</p>';\n}\n\ninclude('template_file.php');\n</code></pre>\n"
},
{
"answer_id": 106436,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "<p>I'd take a look at <a href=\"http://www.smarty.net/\" rel=\"nofollow noreferrer\">Smarty</a> as a template engine - I haven't tried any other ones myself, but it has done me well.</p>\n<p>If you wanted to stick with your current approach <em>sans</em> templates, what's so bad about output buffering? It'll give you much more flexibility than having to declare variables which are the string names of the functions you want to call.</p>\n"
},
{
"answer_id": 1386692,
"author": "BraedenP",
"author_id": 95764,
"author_profile": "https://Stackoverflow.com/users/95764",
"pm_score": 3,
"selected": false,
"text": "<p>I'm a bit late, but I randomly came across it. For any future readers, here's what I would probably do:</p>\n\n<p>I would just use an output buffer. So basically, you start the buffering using ob_start(), then include your \"template file\" with any functions, variables, etc. inside of it, get the contents of the buffer and write them to a string, and then close the buffer. Then you've used any variables you need, you can run any function, and you still have the HTML syntax highlighting available in your IDE.</p>\n\n<p>Here's what I mean:</p>\n\n<p><strong>Template File:</strong></p>\n\n<pre><code><?php echo \"plain text and now a function: \" . testfunction(); ?>\n</code></pre>\n\n<p><strong>Script:</strong></p>\n\n<pre><code><?php\nob_start();\ninclude \"template_file.php\";\n$output_string = ob_get_contents();\nob_end_clean();\necho $output_string;\n?>\n</code></pre>\n\n<p>So the script includes the template_file.php into its buffer, running any functions/methods and assigning any variables along the way. Then you simply record the buffer's contents into a variable and do what you want with it.</p>\n\n<p>That way if you don't want to echo it onto the page right at that second, you don't have to. You can loop and keep adding to the string before outputting it.</p>\n\n<p>I think that's the best way to go if you don't want to use a templating engine.</p>\n"
},
{
"answer_id": 1948173,
"author": "Isofarro",
"author_id": 237069,
"author_profile": "https://Stackoverflow.com/users/237069",
"pm_score": 4,
"selected": false,
"text": "<p>Try this (either as a global variable, or instantiated when you need it):</p>\n\n<pre><code><?php\n class Fn {\n public function __call($name, $args) {\n if (function_exists($name)) {\n return call_user_func_array($name, $args);\n }\n }\n }\n\n $fn = new Fn();\n?>\n</code></pre>\n\n<p>Now any function call goes through the <code>$fn</code> instance. So the existing function <code>testfunction()</code> can be called in a heredoc with <code>{$fn->testfunction()}</code></p>\n\n<p>Basically we are wrapping all functions into a class instance, and using PHP's <code>__call magic</code> method to map the class method to the actual function needing to be called.</p>\n"
},
{
"answer_id": 2802169,
"author": "SomeOne",
"author_id": 337190,
"author_profile": "https://Stackoverflow.com/users/337190",
"pm_score": 1,
"selected": false,
"text": "<p>Guys should note that it also works with double-quoted strings.</p>\n\n<p><a href=\"http://www.php.net/manual/en/language.types.string.php\" rel=\"nofollow noreferrer\">http://www.php.net/manual/en/language.types.string.php</a></p>\n\n<p>Interesting tip anyway.</p>\n"
},
{
"answer_id": 4387729,
"author": "Michael McMillan",
"author_id": 510652,
"author_profile": "https://Stackoverflow.com/users/510652",
"pm_score": 3,
"selected": false,
"text": "<p>This snippet will define variables with the name of your defined functions within userscope and bind them to a string which contains the same name. Let me demonstrate.</p>\n\n<pre><code>function add ($int) { return $int + 1; }\n$f=get_defined_functions();foreach($f[user]as$v){$$v=$v;}\n\n$string = <<< heredoc\nplain text and now a function: {$add(1)}\nheredoc;\n</code></pre>\n\n<p>Will now work. </p>\n"
},
{
"answer_id": 5601596,
"author": "tftd",
"author_id": 393805,
"author_profile": "https://Stackoverflow.com/users/393805",
"pm_score": 2,
"selected": false,
"text": "<p>A bit late but still.\nThis is possible in heredoc!</p>\n\n<p><a href=\"http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.nowdoc\" rel=\"nofollow\">Have a look in the php manual, section \"Complex (curly) syntax\"</a></p>\n"
},
{
"answer_id": 6384711,
"author": "MLU",
"author_id": 803058,
"author_profile": "https://Stackoverflow.com/users/803058",
"pm_score": 3,
"selected": false,
"text": "<p>I think using heredoc is great for generating HTML code. For example, I find the following almost completely unreadable.</p>\n\n<pre><code><html>\n<head>\n <title><?php echo $page_title; ?></title>\n</head>\n<body>\n <?php echo getPageContent(); ?>\n</body>\n</code></pre>\n\n<p>However, in order to achieve the simplicity you are forced to evaluate the functions before you start. I don't believe that is such a terrible constraint, since in so doing, you end up separating your computation from display, which is usually a good idea.</p>\n\n<p>I think the following is quite readable:</p>\n\n<pre><code>$page_content = getPageContent();\n\nprint <<<END\n<html>\n<head>\n <title>$page_title</title>\n</head>\n<body>\n$page_content\n</body>\nEND;\n</code></pre>\n\n<p>Unfortunately, even though it was a good suggestion you made in your question to bind the function to a variable, in the end, it adds a level of complexity to the code, which is not worth, and makes the code less readable, which is the major advantage of heredoc.</p>\n"
},
{
"answer_id": 10713298,
"author": "CJ Dennis",
"author_id": 1166898,
"author_profile": "https://Stackoverflow.com/users/1166898",
"pm_score": 6,
"selected": false,
"text": "<p>If you really want to do this but a bit simpler than using a class you can use:</p>\n\n<pre><code>function fn($data) {\n return $data;\n}\n$fn = 'fn';\n\n$my_string = <<<EOT\nNumber of seconds since the Unix Epoch: {$fn(time())}\nEOT;\n</code></pre>\n"
},
{
"answer_id": 14392377,
"author": "Paulo Buchsbaum",
"author_id": 1062727,
"author_profile": "https://Stackoverflow.com/users/1062727",
"pm_score": 2,
"selected": false,
"text": "<p>Here a nice example using @CJDennis proposal:</p>\n\n<pre><code>function double($i)\n{ return $i*2; }\n\nfunction triple($i)\n{ return $i*3;}\n\n$tab = 'double';\necho \"{$tab(5)} is $tab 5<br>\";\n\n$tab = 'triple';\necho \"{$tab(5)} is $tab 5<br>\";\n</code></pre>\n\n<p>For instance, a good use for HEREDOC syntax is generate huge forms with master-detail relationship in a Database. One can use HEREDOC feature inside a FOR control, adding a suffix after each field name. It's a typical server side task.</p>\n"
},
{
"answer_id": 18955399,
"author": "Ismael Miguel",
"author_id": 2729937,
"author_profile": "https://Stackoverflow.com/users/2729937",
"pm_score": 2,
"selected": false,
"text": "<p>you are forgetting about lambda function:</p>\n\n<pre><code>$or=function($c,$t,$f){return$c?$t:$f;};\necho <<<TRUEFALSE\n The best color ever is {$or(rand(0,1),'green','black')}\nTRUEFALSE;\n</code></pre>\n\n<p>You also could use the function create_function</p>\n"
},
{
"answer_id": 27049352,
"author": "p.voinov",
"author_id": 2121460,
"author_profile": "https://Stackoverflow.com/users/2121460",
"pm_score": 3,
"selected": false,
"text": "<p>found nice solution with wrapping function here: <a href=\"http://blog.nazdrave.net/?p=626\" rel=\"noreferrer\">http://blog.nazdrave.net/?p=626</a></p>\n\n<pre><code>function heredoc($param) {\n // just return whatever has been passed to us\n return $param;\n}\n\n$heredoc = 'heredoc';\n\n$string = <<<HEREDOC\n\\$heredoc is now a generic function that can be used in all sorts of ways:\nOutput the result of a function: {$heredoc(date('r'))}\nOutput the value of a constant: {$heredoc(__FILE__)}\nStatic methods work just as well: {$heredoc(MyClass::getSomething())}\n2 + 2 equals {$heredoc(2+2)}\nHEREDOC;\n\n// The same works not only with HEREDOC strings,\n// but with double-quoted strings as well:\n$string = \"{$heredoc(2+2)}\";\n</code></pre>\n"
},
{
"answer_id": 36202673,
"author": "bishop",
"author_id": 2908724,
"author_profile": "https://Stackoverflow.com/users/2908724",
"pm_score": 5,
"selected": false,
"text": "<p>For completeness, you can also use the <code>!${''}</code> <strike>black magic</strike> <a href=\"https://tpunt.github.io/jekyll/update/2016/01/25/php-parser-hack.html\" rel=\"noreferrer\">parser hack</a>:</p>\n\n<pre><code>echo <<<EOT\nOne month ago was ${!${''} = date('Y-m-d H:i:s', strtotime('-1 month'))}.\nEOT;\n</code></pre>\n"
},
{
"answer_id": 39303612,
"author": "Rubel Hossain",
"author_id": 4305693,
"author_profile": "https://Stackoverflow.com/users/4305693",
"pm_score": 0,
"selected": false,
"text": "<pre><code><?php\necho <<<ETO\n<h1>Hellow ETO</h1>\nETO;\n</code></pre>\n\n<p>you should try it . after end the ETO; command you should give an enter.</p>\n"
},
{
"answer_id": 39542266,
"author": "Ken",
"author_id": 638510,
"author_profile": "https://Stackoverflow.com/users/638510",
"pm_score": 1,
"selected": false,
"text": "<pre><code><div><?=<<<heredoc\nUse heredoc and functions in ONE statement.\nShow lower case ABC=\"\nheredoc\n. strtolower('ABC') . <<<heredoc\n\". And that is it!\nheredoc\n?></div>\n</code></pre>\n"
},
{
"answer_id": 58964820,
"author": "codeasaurus",
"author_id": 5914739,
"author_profile": "https://Stackoverflow.com/users/5914739",
"pm_score": 2,
"selected": false,
"text": "<p>This is a little more elegant today on php 7.x</p>\n\n<pre><code><?php\n\n$test = function(){\n return 'it works!';\n};\n\n\necho <<<HEREDOC\nthis is a test: {$test()}\nHEREDOC;\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9330/"
]
| In PHP, the HEREDOC string declarations are really useful for outputting a block of html. You can have it parse in variables just by prefixing them with $, but for more complicated syntax (like $var[2][3]), you have to put your expression inside {} braces.
In PHP 5, it *is* possible to actually make function calls within {} braces inside a HEREDOC string, but you have to go through a bit of work. The function name itself has to be stored in a variable, and you have to call it like it is a dynamically-named function. For example:
```
$fn = 'testfunction';
function testfunction() { return 'ok'; }
$string = <<< heredoc
plain text and now a function: {$fn()}
heredoc;
```
As you can see, this is a bit more messy than just:
```
$string = <<< heredoc
plain text and now a function: {testfunction()}
heredoc;
```
There are other ways besides the first code example, such as breaking out of the HEREDOC to call the function, or reversing the issue and doing something like:
```
?>
<!-- directly output html and only breaking into php for the function -->
plain text and now a function: <?PHP print testfunction(); ?>
```
The latter has the disadvantage that the output is directly put into the output stream (unless I'm using output buffering), which might not be what I want.
So, the essence of my question is: is there a more elegant way to approach this?
**Edit based on responses:** It certainly does seem like some kind of template engine would make my life much easier, but it would require me basically invert my usual PHP style. Not that that's a bad thing, but it explains my inertia.. I'm up for figuring out ways to make life easier though, so I'm looking into templates now. | I would not use HEREDOC at all for this, personally. It just doesn't make for a good "template building" system. All your HTML is locked down in a string which has several disadvantages
* No option for WYSIWYG
* No code completion for HTML from IDEs
* Output (HTML) locked to logic files
* You end up having to use hacks like what you're trying to do now to achieve more complex templating, such as looping
Get a basic template engine, or just use PHP with includes - it's why the language has the `<?php` and `?>` delimiters.
**template\_file.php**
```
<html>
<head>
<title><?php echo $page_title; ?></title>
</head>
<body>
<?php echo getPageContent(); ?>
</body>
```
**index.php**
```
<?php
$page_title = "This is a simple demo";
function getPageContent() {
return '<p>Hello World!</p>';
}
include('template_file.php');
``` |
104,520 | <p>I have been seriously disappointed with WPF validation system. Anyway! How can I validate the complete form by clicking the "button"? </p>
<p>For some reason everything in WPF is soo complicated! I can do the validation in 1 line of code in ASP.NET which requires like 10-20 lines of code in WPF!!</p>
<p>I can do this using my own ValidationEngine framework: </p>
<pre><code>Customer customer = new Customer();
customer.FirstName = "John";
customer.LastName = String.Empty;
ValidationEngine.Validate(customer);
if (customer.BrokenRules.Count > 0)
{
// do something display the broken rules!
}
</code></pre>
| [
{
"answer_id": 104957,
"author": "adriaanp",
"author_id": 12230,
"author_profile": "https://Stackoverflow.com/users/12230",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest to look at the IDataErrorInfo interface on your business object. Also have a look at this article: <a href=\"http://www.codeproject.com/KB/WPF/WPF_SelfValidatingTextBox.aspx\" rel=\"nofollow noreferrer\">Self Validating Text Box</a></p>\n"
},
{
"answer_id": 157665,
"author": "Christopher Bennage",
"author_id": 6855,
"author_profile": "https://Stackoverflow.com/users/6855",
"pm_score": 0,
"selected": false,
"text": "<p>The description of your problem is a little vague to me. I mean, I'm not exactly sure what your difficulty is.\nAssuming that the DataContext is some sort of presenter or controller that has a propetry representing the customer instance, and ValidateCommand is a property of type ICommand:</p>\n\n<pre><code> <StackPanel> \n <TextBox Text=\"{Binding CurrentCustomer.FirstName}\" />\n <TextBox Text=\"{Binding CurrentCustomer.LastName}\" />\n <Button Content=\"Validate\" \n Command=\"{Binding ValidateCommand}\"\n CommandParameter=\"{Binding CurrentCustomer}\" />\n <ItemsControl ItemsSource=\"{Binding CurrentCustomer.BrokenRules}\" />\n </StackPanel>\n</code></pre>\n\n<p>This XAML is really simplified, of course, and there are other ways to do it.\nAs a Web developer who is now heavily involved with WPF, I find most tasks like this significantly easier in WPF.</p>\n"
},
{
"answer_id": 182330,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 6,
"selected": true,
"text": "<p>A WPF application should disable the button to submit a form iff the entered data is not valid. You can achieve this by implementing the <a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo.aspx\" rel=\"noreferrer\">IDataErrorInfo</a> interface on your business object, using Bindings with <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.data.binding.validatesondataerrors.aspx\" rel=\"noreferrer\"><code>ValidatesOnDataErrors</code></a><code>=true</code>. For customizing the look of individual controls in the case of errors, set a <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.controls.validation.errortemplate.aspx\" rel=\"noreferrer\"><code>Validation.ErrorTemplate</code></a>.</p>\n\n<h3>XAML:</h3>\n\n<pre><code><Window x:Class=\"Example.CustomerWindow\" ...>\n <Window.CommandBindings>\n <CommandBinding Command=\"ApplicationCommands.Save\"\n CanExecute=\"SaveCanExecute\"\n Executed=\"SaveExecuted\" />\n </Window.CommandBindings>\n <StackPanel>\n <TextBox Text=\"{Binding FirstName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}\" />\n <TextBox Text=\"{Binding LastName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}\" />\n <Button Command=\"ApplicationCommands.Save\" IsDefault=\"True\">Save</Button>\n <TextBlock Text=\"{Binding Error}\"/>\n </StackPanel>\n</Window>\n</code></pre>\n\n<p>This creates a <code>Window</code> with two <code>TextBox</code>es where you can edit the first and last name of a customer. The \"Save\" button is only enabled if no validation errors have occurred. The <code>TextBlock</code> beneath the button shows the current errors, so the user knows what's up.</p>\n\n<p>The default <code>ErrorTemplate</code> is a thin red border around the erroneous Control. If that doesn't fit into you visual concept, look at <a href=\"http://www.codeproject.com/KB/WPF/wpfvalidation.aspx\" rel=\"noreferrer\">Validation in Windows Presentation Foundation</a> article on CodeProject for an in-depth look into what can be done about that.</p>\n\n<p>To get the window to actually work, there has to be a bit infrastructure in the Window and the Customer.</p>\n\n<h3>Code Behind</h3>\n\n<pre><code>// The CustomerWindow class receives the Customer to display\n// and manages the Save command\npublic class CustomerWindow : Window\n{\n private Customer CurrentCustomer;\n public CustomerWindow(Customer c) \n {\n // store the customer for the bindings\n DataContext = CurrentCustomer = c;\n InitializeComponent();\n }\n\n private void SaveCanExecute(object sender, CanExecuteRoutedEventArgs e)\n {\n e.CanExecute = ValidationEngine.Validate(CurrentCustomer);\n }\n\n private void SaveExecuted(object sender, ExecutedRoutedEventArgs e) \n {\n CurrentCustomer.Save();\n }\n}\n\npublic class Customer : IDataErrorInfo, INotifyPropertyChanged\n{\n // holds the actual value of FirstName\n private string FirstNameBackingStore;\n // the accessor for FirstName. Only accepts valid values.\n public string FirstName {\n get { return FirstNameBackingStore; }\n set {\n FirstNameBackingStore = value;\n ValidationEngine.Validate(this);\n OnPropertyChanged(\"FirstName\");\n }\n }\n // similar for LastName \n\n string IDataErrorInfo.Error {\n get { return String.Join(\"\\n\", BrokenRules.Values); }\n }\n\n string IDataErrorInfo.this[string columnName]\n {\n get { return BrokenRules[columnName]; }\n }\n}\n</code></pre>\n\n<p>An obvious improvement would be to move the <code>IDataErrorInfo</code> implementation up the class hierarchy, since it only depends on the <code>ValidationEngine</code>, but not the business object.</p>\n\n<p>While this is indeed more code than the simple example you provided, it also has quite a bit more of functionality than only checking for validity. This gives you fine grained, and automatically updated indications to the user about validation problems and automatically disables the \"Save\" button as long as the user tries to enter invalid data.</p>\n"
},
{
"answer_id": 3495538,
"author": "jbe",
"author_id": 103988,
"author_profile": "https://Stackoverflow.com/users/103988",
"pm_score": 1,
"selected": false,
"text": "<p>You might be interested in the <strong>BookLibrary</strong> sample application of the <strong><a href=\"http://waf.codeplex.com\" rel=\"nofollow noreferrer\">WPF Application Framework (WAF)</a></strong>. It shows how to use validation in WPF and how to control the Save button when validation errors exists.</p>\n"
},
{
"answer_id": 4263768,
"author": "skjagini",
"author_id": 185907,
"author_profile": "https://Stackoverflow.com/users/185907",
"pm_score": 1,
"selected": false,
"text": "<p>ValidatesOnDataError is used to validate business rules against your view models, and it will validate only if the binding succeeds. </p>\n\n<p>ValidatesOnExceptions needs to be applied along with ValidatesOnDataError to handle those scenarios where wpf cannot perform binding because of data type mismatch, lets say you want to bind a TextBox to the Age (integer) property in your view model</p>\n\n<pre><code><TextBox Text=\"{Binding Age, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}\" />\n</code></pre>\n\n<p>If the user enters invalid entry by typing alphabets rather than numbers as age, say xyz, the wpf databinding will silently ignores the value as it cannot bind xyz to Age, and the binding error will be lost unless the binding is decorated with <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.data.binding.validatesonexceptions.aspx\" rel=\"nofollow\">ValidatesOnExceptions</a></p>\n\n<pre><code><TextBox Text=\"{Binding Age, ValidatesOnDataErrors=true, ValidatesOnExceptions=\"True\", UpdateSourceTrigger=PropertyChanged}\" />\n</code></pre>\n\n<p>ValidatesOnException uses default exception handling for binding errors using ExceptionValidationRule, the above syntax is a short form for the following </p>\n\n<pre><code><TextBox>\n <TextBox.Text>\n <Binding Path=\"Age\" UpdateSourceTrigger=\"PropertyChanged\" ValidatesOnDataErrors=\"True\">\n <Binding.ValidationRules>\n <ExceptionValidationRule />\n </Binding.ValidationRules>\n </Binding>\n </TextBox.Text>\n</TextBox>\n</code></pre>\n\n<p>You can defined your own rules to validate against the user input by deriving from ValidationRule and implementing Validate method, NumericRule in the following example</p>\n\n<pre><code><TextBox.Text>\n <Binding Path=\"Age\" ValidatesOnDataErrors=\"True\">\n <Binding.ValidationRules>\n <rules:NumericRule />\n </Binding.ValidationRules>\n </Binding>\n </TextBox.Text>\n</code></pre>\n\n<p>The validation rules should be generic and not tied to business, as the later is accomplished through IDataErrorInfo and ValidatesOnDataError. </p>\n\n<p>The above syntax is quite messy compared to the one line binding syntax we have, by implementing the ValidationRule as an attached property the syntax can be improved and you can take a look at it <a href=\"http://www.hardcodet.net/2009/01/combinding-wpf-validation-rules-and-idataerrorinfo-to-validate-conversion-errors\" rel=\"nofollow\">here</a></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104520",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3797/"
]
| I have been seriously disappointed with WPF validation system. Anyway! How can I validate the complete form by clicking the "button"?
For some reason everything in WPF is soo complicated! I can do the validation in 1 line of code in ASP.NET which requires like 10-20 lines of code in WPF!!
I can do this using my own ValidationEngine framework:
```
Customer customer = new Customer();
customer.FirstName = "John";
customer.LastName = String.Empty;
ValidationEngine.Validate(customer);
if (customer.BrokenRules.Count > 0)
{
// do something display the broken rules!
}
``` | A WPF application should disable the button to submit a form iff the entered data is not valid. You can achieve this by implementing the [IDataErrorInfo](http://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo.aspx) interface on your business object, using Bindings with [`ValidatesOnDataErrors`](http://msdn.microsoft.com/en-us/library/system.windows.data.binding.validatesondataerrors.aspx)`=true`. For customizing the look of individual controls in the case of errors, set a [`Validation.ErrorTemplate`](http://msdn.microsoft.com/en-us/library/system.windows.controls.validation.errortemplate.aspx).
### XAML:
```
<Window x:Class="Example.CustomerWindow" ...>
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.Save"
CanExecute="SaveCanExecute"
Executed="SaveExecuted" />
</Window.CommandBindings>
<StackPanel>
<TextBox Text="{Binding FirstName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" />
<TextBox Text="{Binding LastName, ValidatesOnDataErrors=true, UpdateSourceTrigger=PropertyChanged}" />
<Button Command="ApplicationCommands.Save" IsDefault="True">Save</Button>
<TextBlock Text="{Binding Error}"/>
</StackPanel>
</Window>
```
This creates a `Window` with two `TextBox`es where you can edit the first and last name of a customer. The "Save" button is only enabled if no validation errors have occurred. The `TextBlock` beneath the button shows the current errors, so the user knows what's up.
The default `ErrorTemplate` is a thin red border around the erroneous Control. If that doesn't fit into you visual concept, look at [Validation in Windows Presentation Foundation](http://www.codeproject.com/KB/WPF/wpfvalidation.aspx) article on CodeProject for an in-depth look into what can be done about that.
To get the window to actually work, there has to be a bit infrastructure in the Window and the Customer.
### Code Behind
```
// The CustomerWindow class receives the Customer to display
// and manages the Save command
public class CustomerWindow : Window
{
private Customer CurrentCustomer;
public CustomerWindow(Customer c)
{
// store the customer for the bindings
DataContext = CurrentCustomer = c;
InitializeComponent();
}
private void SaveCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = ValidationEngine.Validate(CurrentCustomer);
}
private void SaveExecuted(object sender, ExecutedRoutedEventArgs e)
{
CurrentCustomer.Save();
}
}
public class Customer : IDataErrorInfo, INotifyPropertyChanged
{
// holds the actual value of FirstName
private string FirstNameBackingStore;
// the accessor for FirstName. Only accepts valid values.
public string FirstName {
get { return FirstNameBackingStore; }
set {
FirstNameBackingStore = value;
ValidationEngine.Validate(this);
OnPropertyChanged("FirstName");
}
}
// similar for LastName
string IDataErrorInfo.Error {
get { return String.Join("\n", BrokenRules.Values); }
}
string IDataErrorInfo.this[string columnName]
{
get { return BrokenRules[columnName]; }
}
}
```
An obvious improvement would be to move the `IDataErrorInfo` implementation up the class hierarchy, since it only depends on the `ValidationEngine`, but not the business object.
While this is indeed more code than the simple example you provided, it also has quite a bit more of functionality than only checking for validity. This gives you fine grained, and automatically updated indications to the user about validation problems and automatically disables the "Save" button as long as the user tries to enter invalid data. |
104,525 | <p>We have a warm sql backup. full backup nightly, txn logs shipped every so often during the day and restored. I need to move the data files to another disk. These DB's are in a "warm backup" state (such that I can't unmark them as read-only - "Error 5063: Database '<dbname>' is in warm standby. A warm-standby database is read-only.
") and am worried about detaching and re-attaching. </p>
<p>How do we obtain the "warm backup" status after detach/attach operations are complete?</p>
| [
{
"answer_id": 104762,
"author": "boes",
"author_id": 17746,
"author_profile": "https://Stackoverflow.com/users/17746",
"pm_score": 3,
"selected": true,
"text": "<p>The only solution I know is to create a complete backup of your active database and restore this backup to a copy of the database in a 'warm backup' state. First create a backup from the active db:</p>\n\n<pre><code>backup database activedb to disk='somefile'\n</code></pre>\n\n<p>Then restore the backup on another sql server. If needed you can use the WITH REPLACE option to change the default storage directory</p>\n\n<pre><code>restore database warmbackup from disk='somefile'\n with norecovery, replace ....\n</code></pre>\n\n<p>Now you can create backups of the logs and restore them to the warmbackup with the restore log statement.</p>\n"
},
{
"answer_id": 67075511,
"author": "Endex",
"author_id": 15622896,
"author_profile": "https://Stackoverflow.com/users/15622896",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like you didn't complete the restore task , just do the restore task only for the TRANSACTOINAL LOG .Then it will be fine immediately when you finish that.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104525",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10235/"
]
| We have a warm sql backup. full backup nightly, txn logs shipped every so often during the day and restored. I need to move the data files to another disk. These DB's are in a "warm backup" state (such that I can't unmark them as read-only - "Error 5063: Database '<dbname>' is in warm standby. A warm-standby database is read-only.
") and am worried about detaching and re-attaching.
How do we obtain the "warm backup" status after detach/attach operations are complete? | The only solution I know is to create a complete backup of your active database and restore this backup to a copy of the database in a 'warm backup' state. First create a backup from the active db:
```
backup database activedb to disk='somefile'
```
Then restore the backup on another sql server. If needed you can use the WITH REPLACE option to change the default storage directory
```
restore database warmbackup from disk='somefile'
with norecovery, replace ....
```
Now you can create backups of the logs and restore them to the warmbackup with the restore log statement. |
104,568 | <p>Is there any way that my script can retrieve metadata values that are declared in its own header? I don't see anything promising in the API, except perhaps <code>GM_getValue()</code>. That would of course involve a special name syntax. I have tried, for example: <code>GM_getValue("@name")</code>.</p>
<p>The motivation here is to avoid redundant specification.</p>
<p>If GM metadata is not directly accessible, perhaps there's a way to read the body of the script itself. It's certainly in memory somewhere, and it wouldn't be too awfully hard to parse for <code>"// @"</code>. (That may be necessary in my case any way, since the value I'm really interested in is <code>@version</code>, which is an extended value read by <a href="http://userscripts.org/" rel="noreferrer">userscripts.org</a>.)</p>
| [
{
"answer_id": 104814,
"author": "Athena",
"author_id": 17846,
"author_profile": "https://Stackoverflow.com/users/17846",
"pm_score": 4,
"selected": true,
"text": "<p><strong>This answer is out of date :</strong> As of Greasemonkey 0.9.16 (Feb 2012) please see <a href=\"https://stackoverflow.com/a/10475344/1820\">Brock's answer</a> regarding <code>GM_info</code></p>\n\n<hr>\n\n<p>Yes. A very simple example is:</p>\n\n<pre><code>var metadata=<> \n// ==UserScript==\n// @name Reading metadata\n// @namespace http://www.afunamatata.com/greasemonkey/\n// @description Read in metadata from the header\n// @version 0.9\n// @include https://stackoverflow.com/questions/104568/accessing-greasemonkey-metadata-from-within-your-script\n// ==/UserScript==\n</>.toString();\n\nGM_log(metadata); \n</code></pre>\n\n<p>See <a href=\"http://groups.google.com/group/greasemonkey-users/browse_thread/thread/2003daba08cc14b6/62a635f278d8f9fc\" rel=\"nofollow noreferrer\">this thread on the greasemonkey-users group</a> for more information. A more robust implementation can be found near the end.</p>\n"
},
{
"answer_id": 112148,
"author": "Chris Noe",
"author_id": 14749,
"author_profile": "https://Stackoverflow.com/users/14749",
"pm_score": 2,
"selected": false,
"text": "<p>Building on Athena's answer, here is my generalized solution that yields an object of name/value pairs, each representing a metadata property. Note that certain properties can have multiple values, (@include, @exclude, @require, @resource), therefore my parser captures those as Arrays - or in the case of @resource, as a subordinate Object of name/value pairs.</p>\n\n<pre>\nvar scriptMetadata = parseMetadata(.toString());\n\nfunction parseMetadata(headerBlock)\n{\n // split up the lines, omitting those not containing \"// @\"\n function isAGmParm(element) { return /\\/\\/ @/.test(element); }\n var lines = headerBlock.split(/[\\r\\n]+/).filter(isAGmParm);\n // initialize the result object with empty arrays for the enumerated properties\n var metadata = { include: [], exclude: [], require: [], resource: {} };\n for each (var line in lines)\n {\n [line, name, value] = line.match(/\\/\\/ @(\\S+)\\s*(.*)/);\n if (metadata[name] instanceof Array)\n metadata[name].push(value);\n else if (metadata[name] instanceof Object) {\n [rName, rValue] = value.split(/\\s+/); // each resource is named\n metadata[name][rName] = rValue;\n }\n else\n metadata[name] = value;\n }\n return metadata;\n}\n\n// example usage\nGM_log(\"version: \" + scriptMetadata[\"version\"]);\nGM_log(\"res1: \" + scriptMetadata[\"resource\"][\"res1\"]);\n</pre>\n\n<p>This is working nicely in my scripts.</p>\n\n<p>EDIT: Added @resource and @require, which were introduced in Greasemonkey 0.8.0.</p>\n\n<p>EDIT: FF5+ compatibility, Array.filter() no longer accepts a regular expression</p>\n"
},
{
"answer_id": 10475344,
"author": "Brock Adams",
"author_id": 331508,
"author_profile": "https://Stackoverflow.com/users/331508",
"pm_score": 3,
"selected": false,
"text": "<p>Use <a href=\"http://wiki.greasespot.net/GM_info\" rel=\"noreferrer\">the <code>GM_info</code> object</a>, which was added to Greasemonkey in version 0.9.16.</p>\n\n<p>For example, if You run this script:</p>\n\n<pre><code>// ==UserScript==\n// @name _GM_info demo\n// @namespace Stack Overflow\n// @description Tell me more about me, me, ME!\n// @include http://stackoverflow.com/questions/*\n// @version 8.8\n// ==/UserScript==\n\nunsafeWindow.console.clear ();\nunsafeWindow.console.log (GM_info);\n</code></pre>\n\n<p><br>\nIt will output this object:</p>\n\n<pre><code>{\n version: (new String(\"0.9.18\")),\n scriptWillUpdate: false,\n script: {\n description: \"Tell me more about me, me, ME!\",\n excludes: [],\n includes: [\"http://stackoverflow.com/questions/*\"],\n matches: [],\n name: \"_GM_info demo\",\n namespace: \"Stack Overflow\",\n 'run-at': \"document-end\",\n unwrap: false,\n version: \"8.8\"\n },\n scriptMetaStr: \"// @name _GM_info demo\\r\\n// @namespace Stack Overflow\\r\\n// @description Tell me more about me, me, ME!\\r\\n// @include http://stackoverflow.com/questions/*\\r\\n// @version 8.8\\r\\n\"\n}\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104568",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14749/"
]
| Is there any way that my script can retrieve metadata values that are declared in its own header? I don't see anything promising in the API, except perhaps `GM_getValue()`. That would of course involve a special name syntax. I have tried, for example: `GM_getValue("@name")`.
The motivation here is to avoid redundant specification.
If GM metadata is not directly accessible, perhaps there's a way to read the body of the script itself. It's certainly in memory somewhere, and it wouldn't be too awfully hard to parse for `"// @"`. (That may be necessary in my case any way, since the value I'm really interested in is `@version`, which is an extended value read by [userscripts.org](http://userscripts.org/).) | **This answer is out of date :** As of Greasemonkey 0.9.16 (Feb 2012) please see [Brock's answer](https://stackoverflow.com/a/10475344/1820) regarding `GM_info`
---
Yes. A very simple example is:
```
var metadata=<>
// ==UserScript==
// @name Reading metadata
// @namespace http://www.afunamatata.com/greasemonkey/
// @description Read in metadata from the header
// @version 0.9
// @include https://stackoverflow.com/questions/104568/accessing-greasemonkey-metadata-from-within-your-script
// ==/UserScript==
</>.toString();
GM_log(metadata);
```
See [this thread on the greasemonkey-users group](http://groups.google.com/group/greasemonkey-users/browse_thread/thread/2003daba08cc14b6/62a635f278d8f9fc) for more information. A more robust implementation can be found near the end. |
104,587 | <p>Everywhere I look always the same explanation pop ups.<br/>
Configure the view resolver.</p>
<pre><code><bean id="viewMappings"
class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views" />
</bean>
</code></pre>
<p>And then put a file in the classpath named view.properties with some key-value pairs (don't mind the names).<br/></p>
<pre><code>logout.class=org.springframework.web.servlet.view.JstlView
logout.url=WEB-INF/jsp/logout.jsp
</code></pre>
<p>What does <code>logout.class</code> and <code>logout.url</code> mean?<br/>
How does <code>ResourceBundleViewResolver</code> uses the key-value pairs in the file?<br/>
My goal is that when someone enters the URI <code>myserver/myapp/logout.htm</code> the file <code>logout.jsp</code> gets served.</p>
| [
{
"answer_id": 105481,
"author": "Craig Day",
"author_id": 5193,
"author_profile": "https://Stackoverflow.com/users/5193",
"pm_score": 4,
"selected": true,
"text": "<p>ResourceBundleViewResolver uses the key/vals in views.properties to create view beans (actually created in an internal application context). The name of the view bean in your example will be \"logout\" and it will be a bean of type JstlView. JstlView has an attribute called URL which will be set to \"WEB-INF/jsp/logout.jsp\". You can set any attribute on the view class in a similar way.</p>\n\n<p>What you appear to be missing is your controller/handler layer. If you want /myapp/logout.htm to serve logout.jsp, you must map a Controller into /myapp/logout.htm and that Controller needs to return the view name \"logout\". The ResourceBundleViewResolver will then be consulted for a bean of that name, and return your instance of JstlView.</p>\n"
},
{
"answer_id": 105554,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 0,
"selected": false,
"text": "<p>To answer your question <code>logout</code> is the view name obtained from the ModelAndView object returned by the controller. If your are having problems you many need the following additional configuration.</p>\n\n<p>You need to add a servlet mapping for <code>*.htm</code> in your <code>web.xml</code>:</p>\n\n<p><pre>\n <web-app>\n <servlet>\n <servlet-name>htm</servlet-name>\n <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>\n <oad-on-startup>1</load-on-startup>\n </servlet>\n <servlet-mapping>\n <servlet-name>htm</servlet-name>\n <url-pattern>*.htm</url-pattern>\n </servlet-mapping>\n </web-app>\n</pre></p>\n\n<p>And if you want to map directly to the <code>*.jsp</code> without creating a custom controller then you need to add the following bean to your Spring context:</p>\n\n<p><pre>\n <bean id=\"urlFilenameController\"\n class=\"org.springframework.web.servlet.mvc.UrlFilenameViewController\" />\n</pre></p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104587",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2024/"
]
| Everywhere I look always the same explanation pop ups.
Configure the view resolver.
```
<bean id="viewMappings"
class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename" value="views" />
</bean>
```
And then put a file in the classpath named view.properties with some key-value pairs (don't mind the names).
```
logout.class=org.springframework.web.servlet.view.JstlView
logout.url=WEB-INF/jsp/logout.jsp
```
What does `logout.class` and `logout.url` mean?
How does `ResourceBundleViewResolver` uses the key-value pairs in the file?
My goal is that when someone enters the URI `myserver/myapp/logout.htm` the file `logout.jsp` gets served. | ResourceBundleViewResolver uses the key/vals in views.properties to create view beans (actually created in an internal application context). The name of the view bean in your example will be "logout" and it will be a bean of type JstlView. JstlView has an attribute called URL which will be set to "WEB-INF/jsp/logout.jsp". You can set any attribute on the view class in a similar way.
What you appear to be missing is your controller/handler layer. If you want /myapp/logout.htm to serve logout.jsp, you must map a Controller into /myapp/logout.htm and that Controller needs to return the view name "logout". The ResourceBundleViewResolver will then be consulted for a bean of that name, and return your instance of JstlView. |
104,601 | <p>I want to do a <code>Response.Redirect("MyPage.aspx")</code> but have it open in a new browser window. I've done this before without using the JavaScript register script method. I just can't remember how?</p>
| [
{
"answer_id": 104653,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 3,
"selected": false,
"text": "<p>This is not possible with Response.Redirect as it happens on the server side and cannot direct your browser to take that action. What would be left in the initial window? A blank page?</p>\n"
},
{
"answer_id": 104660,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 5,
"selected": false,
"text": "<p>Because Response.Redirect is initiated on the server you can't do it using that. </p>\n\n<p>If you can write directly to the Response stream you could try something like:</p>\n\n<pre><code>response.write(\"<script>\");\nresponse.write(\"window.open('page.html','_blank')\");\nresponse.write(\"</script>\");\n</code></pre>\n"
},
{
"answer_id": 104685,
"author": "CodeRot",
"author_id": 14134,
"author_profile": "https://Stackoverflow.com/users/14134",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to use the Page.RegisterStartupScript to ensure that the javascript fires on page load.</p>\n"
},
{
"answer_id": 104881,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "<p>I just found the answer and it works :)</p>\n\n<p>You need to add the following to your server side link/button:</p>\n\n<pre><code>OnClientClick=\"aspnetForm.target ='_blank';\"\n</code></pre>\n\n<p>My entire button code looks something like:</p>\n\n<pre><code><asp:LinkButton ID=\"myButton\" runat=\"server\" Text=\"Click Me!\" \n OnClick=\"myButton_Click\" \n OnClientClick=\"aspnetForm.target ='_blank';\"/>\n</code></pre>\n\n<p>In the server side OnClick I do a <code>Response.Redirect(\"MyPage.aspx\");</code> and the page is opened in a new window.</p>\n\n<p>The other part you need to add is to fix the form's target otherwise every link will open in a new window. To do so add the following in the header of your POPUP window.</p>\n\n<pre><code><script type=\"text/javascript\">\n function fixform() {\n if (opener.document.getElementById(\"aspnetForm\").target != \"_blank\") return;\n opener.document.getElementById(\"aspnetForm\").target = \"\";\n opener.document.getElementById(\"aspnetForm\").action = opener.location.href;\n }\n</script>\n</code></pre>\n\n<p>and</p>\n\n<pre><code><body onload=\"fixform()\">\n</code></pre>\n"
},
{
"answer_id": 829034,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>You can also use in code behind like this way</p>\n\n<pre><code>ClientScript.RegisterStartupScript(this.Page.GetType(), \"\",\n \"window.open('page.aspx','Graph','height=400,width=500');\", true);\n</code></pre>\n"
},
{
"answer_id": 2829992,
"author": "tom",
"author_id": 340651,
"author_profile": "https://Stackoverflow.com/users/340651",
"pm_score": 4,
"selected": false,
"text": "<p>The fixform trick is neat, but:</p>\n\n<ol>\n<li><p>You may not have access to the code\nof what loads in the new window.</p></li>\n<li><p>Even if you do, you are depending on\nthe fact that it always loads, error\nfree.</p></li>\n<li><p>And you are depending on the fact\nthat the user won't click another\nbutton before the other page gets a\nchance to load and run fixform.</p></li>\n</ol>\n\n<p>I would suggest doing this instead:</p>\n\n<pre><code>OnClientClick=\"aspnetForm.target ='_blank';setTimeout('fixform()', 500);\"\n</code></pre>\n\n<p>And set up fixform on the <em>same page</em>, looking like this:</p>\n\n<pre><code>function fixform() {\n document.getElementById(\"aspnetForm\").target = '';\n}\n</code></pre>\n"
},
{
"answer_id": 3578157,
"author": "Abhishek Shrivastava",
"author_id": 328116,
"author_profile": "https://Stackoverflow.com/users/328116",
"pm_score": 2,
"selected": false,
"text": "<p>I always use this code...\n<b>Use this code </b></p>\n\n<pre><code>String clientScriptName = \"ButtonClickScript\";\nType clientScriptType = this.GetType ();\n\n// Get a ClientScriptManager reference from the Page class.\nClientScriptManager clientScript = Page.ClientScript;\n\n// Check to see if the client script is already registered.\nif (!clientScript.IsClientScriptBlockRegistered (clientScriptType, clientScriptName))\n {\n StringBuilder sb = new StringBuilder ();\n sb.Append (\"<script type='text/javascript'>\");\n sb.Append (\"window.open(' \" + url + \"')\"); //URL = where you want to redirect.\n sb.Append (\"</script>\");\n clientScript.RegisterClientScriptBlock (clientScriptType, clientScriptName, sb.ToString ());\n }\n</code></pre>\n"
},
{
"answer_id": 3883008,
"author": "Yaplex",
"author_id": 199027,
"author_profile": "https://Stackoverflow.com/users/199027",
"pm_score": 0,
"selected": false,
"text": "<p>you can <a href=\"http://alexandershapovalov.com/open-new-window-from-code-behind-in-aspnet-68/\" rel=\"nofollow\">open new window from asp.net code behind</a> using ajax like I did here\n<a href=\"http://alexandershapovalov.com/open-new-window-from-code-behind-in-aspnet-68/\" rel=\"nofollow\">http://alexandershapovalov.com/open-new-window-from-code-behind-in-aspnet-68/</a></p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n Calendar1.SelectionChanged += CalendarSelectionChanged;\n}\n\nprivate void CalendarSelectionChanged(object sender, EventArgs e)\n{\n DateTime selectedDate = ((Calendar) sender).SelectedDate;\n string url = \"HistoryRates.aspx?date=\"\n+ HttpUtility.UrlEncode(selectedDate.ToShortDateString());\n ScriptManager.RegisterClientScriptBlock(this, GetType(),\n\"rates\" + selectedDate, \"openWindow('\" + url + \"');\", true);\n}\n</code></pre>\n"
},
{
"answer_id": 4961312,
"author": "Sasa Tancev",
"author_id": 611904,
"author_profile": "https://Stackoverflow.com/users/611904",
"pm_score": 6,
"selected": false,
"text": "<p>You can use this as extension method</p>\n\n<pre><code>public static class ResponseHelper\n{ \n public static void Redirect(this HttpResponse response, string url, string target, string windowFeatures) \n { \n\n if ((String.IsNullOrEmpty(target) || target.Equals(\"_self\", StringComparison.OrdinalIgnoreCase)) && String.IsNullOrEmpty(windowFeatures)) \n { \n response.Redirect(url); \n } \n else \n { \n Page page = (Page)HttpContext.Current.Handler; \n\n if (page == null) \n { \n throw new InvalidOperationException(\"Cannot redirect to new window outside Page context.\"); \n } \n url = page.ResolveClientUrl(url); \n\n string script; \n if (!String.IsNullOrEmpty(windowFeatures)) \n { \n script = @\"window.open(\"\"{0}\"\", \"\"{1}\"\", \"\"{2}\"\");\"; \n } \n else \n { \n script = @\"window.open(\"\"{0}\"\", \"\"{1}\"\");\"; \n }\n script = String.Format(script, url, target, windowFeatures); \n ScriptManager.RegisterStartupScript(page, typeof(Page), \"Redirect\", script, true); \n } \n }\n}\n</code></pre>\n\n<p>With this you get nice override on the actual Response object</p>\n\n<pre><code>Response.Redirect(redirectURL, \"_blank\", \"menubar=0,scrollbars=1,width=780,height=900,top=10\");\n</code></pre>\n"
},
{
"answer_id": 6222358,
"author": "kazinix",
"author_id": 724689,
"author_profile": "https://Stackoverflow.com/users/724689",
"pm_score": 3,
"selected": false,
"text": "<pre><code><asp:Button ID=\"btnNewEntry\" runat=\"Server\" CssClass=\"button\" Text=\"New Entry\"\n\nOnClick=\"btnNewEntry_Click\" OnClientClick=\"aspnetForm.target ='_blank';\"/>\n\nprotected void btnNewEntry_Click(object sender, EventArgs e)\n{\n Response.Redirect(\"New.aspx\");\n}\n</code></pre>\n\n<p>Source: <a href=\"http://dotnetchris.wordpress.com/2008/11/04/c-aspnet-responseredirect-open-into-new-window/\">http://dotnetchris.wordpress.com/2008/11/04/c-aspnet-responseredirect-open-into-new-window/</a></p>\n"
},
{
"answer_id": 6816642,
"author": "humbads",
"author_id": 553396,
"author_profile": "https://Stackoverflow.com/users/553396",
"pm_score": 2,
"selected": false,
"text": "<p>If you can re-structure your code so that you do not need to postback, then you can use this code in the PreRender event of the button:</p>\n\n<pre><code>protected void MyButton_OnPreRender(object sender, EventArgs e)\n{\n string URL = \"~/MyPage.aspx\";\n URL = Page.ResolveClientUrl(URL);\n MyButton.OnClientClick = \"window.open('\" + URL + \"'); return false;\";\n}\n</code></pre>\n"
},
{
"answer_id": 7071967,
"author": "steve",
"author_id": 374480,
"author_profile": "https://Stackoverflow.com/users/374480",
"pm_score": 5,
"selected": false,
"text": "<p>Contruct your url via click event handler:</p>\n\n<pre><code>string strUrl = \"/some/url/path\" + myvar;\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>ScriptManager.RegisterStartupScript(Page, Page.GetType(), \"popup\", \"window.open('\" + strUrl + \"','_blank')\", true);\n</code></pre>\n"
},
{
"answer_id": 10451855,
"author": "Ben Barreth",
"author_id": 603670,
"author_profile": "https://Stackoverflow.com/users/603670",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a jQuery version based on the answer by @takrl and @tom above. Note: no hardcoded formid (named aspnetForm above) and also does not use direct form.target references which Firefox may find problematic: </p>\n\n<pre><code><asp:Button ID=\"btnSubmit\" OnClientClick=\"openNewWin();\" Text=\"Submit\" OnClick=\"btn_OnClick\" runat=\"server\"/>\n</code></pre>\n\n<p>Then in your js file referenced on the SAME page:</p>\n\n<pre><code>function openNewWin () {\n $('form').attr('target','_blank');\n setTimeout('resetFormTarget()', 500);\n}\n\nfunction resetFormTarget(){\n $('form').attr('target','');\n}\n</code></pre>\n"
},
{
"answer_id": 12860475,
"author": "bokkie",
"author_id": 1071439,
"author_profile": "https://Stackoverflow.com/users/1071439",
"pm_score": 1,
"selected": false,
"text": "<p>I used Hyperlink instead of LinkButton and it worked just fine, it has the Target property so it solved my problem. There was the solution with Response.Write but that was messing up my layout, and the one with ScriptManager, at every refresh or back was reopening the window. So this is how I solved it:</p>\n\n<pre><code><asp:HyperLink CssClass=\"hlk11\" ID=\"hlkLink\" runat=\"server\" Text='<%# Eval(\"LinkText\") %>' Visible='<%# !(bool)Eval(\"IsDocument\") %>' Target=\"_blank\" NavigateUrl='<%# Eval(\"WebAddress\") %>'></asp:HyperLink>\n</code></pre>\n"
},
{
"answer_id": 17902865,
"author": "Zohaib",
"author_id": 2221450,
"author_profile": "https://Stackoverflow.com/users/2221450",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use the following code to open new page in new tab.</p>\n\n<pre><code><asp:Button ID=\"Button1\" runat=\"server\" Text=\"Go\" \n OnClientClick=\"window.open('yourPage.aspx');return false;\" \n onclick=\"Button3_Click\" />\n</code></pre>\n\n<p>And just call Response.Redirect(\"yourPage.aspx\"); behind button event.</p>\n"
},
{
"answer_id": 19864862,
"author": "crh225",
"author_id": 1879992,
"author_profile": "https://Stackoverflow.com/users/1879992",
"pm_score": 0,
"selected": false,
"text": "<p>None of the previous examples worked for me, so I decided to post my solution. In the button click events, here is the code behind. </p>\n\n<pre><code>Dim URL As String = \"http://www.google/?Search=\" + txtExample.Text.ToString\nURL = Page.ResolveClientUrl(URL)\nbtnSearch.OnClientClick = \"window.open('\" + URL + \"'); return false;\"\n</code></pre>\n\n<p>I was having to modify someone else's response.redirect code to open in a new browser.</p>\n"
},
{
"answer_id": 21834600,
"author": "Ricketts",
"author_id": 754830,
"author_profile": "https://Stackoverflow.com/users/754830",
"pm_score": 0,
"selected": false,
"text": "<p>I used this approach, it doesn't require you to do anything on the popup (which I didn't have access to because I was redirecting to a PDF file). It also uses classes.</p>\n\n<pre><code>$(function () {\n //--- setup click event for elements that use a response.redirect in code behind but should open in a new window\n $(\".new-window\").on(\"click\", function () {\n\n //--- change the form's target\n $(\"#aspnetForm\").prop(\"target\", \"_blank\");\n\n //--- change the target back after the window has opened\n setTimeout(function () {\n $(\"#aspnetForm\").prop(\"target\", \"\");\n }, 1);\n });\n});\n</code></pre>\n\n<p>To use, add the class \"new-window\" to any element. You do not need to add anything to the body tag. This function sets up the new window and fixes it in the same function.</p>\n"
},
{
"answer_id": 25188941,
"author": "Zen Of Kursat",
"author_id": 2036103,
"author_profile": "https://Stackoverflow.com/users/2036103",
"pm_score": 3,
"selected": false,
"text": "<p>popup method will give a secure question to visitor..</p>\n\n<p>here is my simple solution: and working everyhere.</p>\n\n<pre><code><script type=\"text/javascript\">\n function targetMeBlank() {\n document.forms[0].target = \"_blank\";\n }\n</script>\n</code></pre>\n\n<hr/>\n\n<pre><code><asp:linkbutton runat=\"server\" ID=\"lnkbtn1\" Text=\"target me to blank dude\" OnClick=\"lnkbtn1_Click\" OnClientClick=\"targetMeBlank();\"/>\n</code></pre>\n"
},
{
"answer_id": 30050188,
"author": "Hevski",
"author_id": 2373058,
"author_profile": "https://Stackoverflow.com/users/2373058",
"pm_score": 0,
"selected": false,
"text": "<p>I did this by putting target=\"_blank\" in the linkbutton</p>\n\n<pre><code><asp:LinkButton ID=\"btn\" runat=\"server\" CausesValidation=\"false\" Text=\"Print\" Visible=\"false\" target=\"_blank\" />\n</code></pre>\n\n<p>then in the codebehind pageload just set the href attribute:</p>\n\n<pre><code>btn.Attributes(\"href\") = String.Format(ResolveUrl(\"~/\") + \"test/TestForm.aspx?formId={0}\", formId)\n</code></pre>\n"
},
{
"answer_id": 48512798,
"author": "Tran Anh Hien",
"author_id": 6537098,
"author_profile": "https://Stackoverflow.com/users/6537098",
"pm_score": 0,
"selected": false,
"text": "<p>HTML</p>\n\n<pre><code><asp:Button ID=\"Button1\" runat=\"server\" Text=\"Button\" onclick=\"Button1_Click\" OnClientClick = \"SetTarget();\" />\n</code></pre>\n\n<p>Javascript:</p>\n\n<pre><code>function SetTarget() {\n document.forms[0].target = \"_blank\";}\n</code></pre>\n\n<p>AND codebehind:</p>\n\n<pre><code>Response.Redirect(URL); \n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I want to do a `Response.Redirect("MyPage.aspx")` but have it open in a new browser window. I've done this before without using the JavaScript register script method. I just can't remember how? | I just found the answer and it works :)
You need to add the following to your server side link/button:
```
OnClientClick="aspnetForm.target ='_blank';"
```
My entire button code looks something like:
```
<asp:LinkButton ID="myButton" runat="server" Text="Click Me!"
OnClick="myButton_Click"
OnClientClick="aspnetForm.target ='_blank';"/>
```
In the server side OnClick I do a `Response.Redirect("MyPage.aspx");` and the page is opened in a new window.
The other part you need to add is to fix the form's target otherwise every link will open in a new window. To do so add the following in the header of your POPUP window.
```
<script type="text/javascript">
function fixform() {
if (opener.document.getElementById("aspnetForm").target != "_blank") return;
opener.document.getElementById("aspnetForm").target = "";
opener.document.getElementById("aspnetForm").action = opener.location.href;
}
</script>
```
and
```
<body onload="fixform()">
``` |
104,603 | <p>Is there a way to iterate (through foreach preferably) over a collection using reflection? I'm iterating over the properties in an object using reflection, and when the program gets to a type that is a collection, I'd like it to iterate over the contents of the collection and be able to access the objects in the collection.</p>
<p>At the moment I have an attribute set on all of my properties, with an IsCollection flag set to true on the properties that are collections. My code checks for this flag and if it's true, it gets the Type using reflection. Is there a way to invoke GetEnumerator or Items somehow on a collection to be able to iterate over the items?</p>
| [
{
"answer_id": 104655,
"author": "Adam Driscoll",
"author_id": 13688,
"author_profile": "https://Stackoverflow.com/users/13688",
"pm_score": 0,
"selected": false,
"text": "<p>When your using reflection you aren't necessarily using an instance of that object. You would have to create an instance of that type of be able to iterate through the object's properties. So if you are using reflection use the ConstructorInfo.Invoke() (?) method to create a new instance or point to an instance of the type.</p>\n"
},
{
"answer_id": 104657,
"author": "Andy",
"author_id": 3857,
"author_profile": "https://Stackoverflow.com/users/3857",
"pm_score": 2,
"selected": false,
"text": "<p>The best you could probably do would be to check if the object implements certain collection interfaces - probably IEnumerable would be all that you need. Then it's just a matter of calling GetEnumerator() off of the object, and using IEnumerator.MoveNext() and IEnumerator.Current to work your way through the collection.</p>\n\n<p>This won't help you if the collection doesn't implement those interfaces, but if that's the case it's not really much of a collection, I suppose.</p>\n"
},
{
"answer_id": 104664,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 6,
"selected": true,
"text": "<p>I had this issue, but instead of using reflection, i ended up just checking if it was IEnumerable. All collections implement that.</p>\n\n<pre><code>if (item is IEnumerable)\n{\n foreach (object o in (item as IEnumerable))\n {\n\n }\n} else {\n // reflect over item\n}\n</code></pre>\n"
},
{
"answer_id": 104684,
"author": "nullDev",
"author_id": 6621,
"author_profile": "https://Stackoverflow.com/users/6621",
"pm_score": 0,
"selected": false,
"text": "<p>A rather straightforward approach would be to type cast the object as the collection and directly use that.</p>\n"
},
{
"answer_id": 104757,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 3,
"selected": false,
"text": "<p>Just get the value of the property and then cast it into an IEnumerable. Here is some (untested) code to give you an idea:</p>\n\n<pre><code>ClassWithListProperty obj = new ClassWithListProperty();\nobj.List.Add(1);\nobj.List.Add(2);\nobj.List.Add(3);\n\nType type = obj.GetType();\nPropertyInfo listProperty = type.GetProperty(\"List\", BindingFlags.Public);\nIEnumerable listObject = (IEnumerable) listProperty.GetValue(obj, null);\n\nforeach (int i in listObject)\n Console.Write(i); // should print out 123\n</code></pre>\n"
},
{
"answer_id": 549212,
"author": "Nagyman",
"author_id": 45715,
"author_profile": "https://Stackoverflow.com/users/45715",
"pm_score": 5,
"selected": false,
"text": "<p>I've tried to use a similar technique as Darren suggested, however just beware that not just collections implement IEnumerable. <code>string</code> for instance is also IEnumerable and will iterate over the characters.</p>\n\n<p>Here's a small function I'm using to determine if an object is a collection (which will be enumerable as well since ICollection is also IEnumerable).</p>\n\n<pre><code> public bool isCollection(object o)\n {\n return typeof(ICollection).IsAssignableFrom(o.GetType())\n || typeof(ICollection<>).IsAssignableFrom(o.GetType());\n }\n</code></pre>\n"
},
{
"answer_id": 570191,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I would look at the Type.FindInterfaces method. This can filter out the interfaces implemented by a given type. As in PropertyInfo.PropertyType.FindInterfaces(filterMethod, filterObjects). You can filter by IEnumerable and see if any results are returned. MSDN has a great example in the method documentation.</p>\n"
},
{
"answer_id": 3012496,
"author": "Abdo",
"author_id": 226255,
"author_profile": "https://Stackoverflow.com/users/226255",
"pm_score": 0,
"selected": false,
"text": "<p>If you're not using an instance of the object but rather a Type, you can use the following:</p>\n\n<pre><code>// type is IEnumerable\nif (type.GetInterface(\"IEnumerable\") != null)\n{\n}\n</code></pre>\n"
},
{
"answer_id": 10726432,
"author": "Sugar Bowl",
"author_id": 757992,
"author_profile": "https://Stackoverflow.com/users/757992",
"pm_score": 2,
"selected": false,
"text": "<p>Just for information may be it will be of someone's help...\nI had a class with nested classes and collection of some other classes. I wanted to save the property values of the class as well nested classes and collection of classes. My code is as follows:</p>\n\n<pre><code> public void LogObject(object obj, int indent)\n {\n if (obj == null) return;\n string indentString = new string(' ', indent);\n Type objType = obj.GetType();\n PropertyInfo[] properties = objType.GetProperties();\n\n foreach (PropertyInfo property in properties)\n {\n Type tColl = typeof(ICollection<>);\n Type t = property.PropertyType;\n string name = property.Name;\n\n\n object propValue = property.GetValue(obj, null); \n //check for nested classes as properties\n if (property.PropertyType.Assembly == objType.Assembly)\n {\n string _result = string.Format(\"{0}{1}:\", indentString, property.Name);\n log.Info(_result);\n LogObject(propValue, indent + 2);\n }\n else\n {\n string _result = string.Format(\"{0}{1}: {2}\", indentString, property.Name, propValue);\n log.Info(_result);\n }\n\n //check for collection\n if (t.IsGenericType && tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) ||\n t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tColl))\n {\n //var get = property.GetGetMethod();\n IEnumerable listObject = (IEnumerable)property.GetValue(obj, null);\n if (listObject != null)\n {\n foreach (object o in listObject)\n {\n LogObject(o, indent + 2);\n }\n }\n }\n }\n }\n</code></pre>\n\n<p>An called this function </p>\n\n<pre><code>LogObject(obj, 0);\n</code></pre>\n\n<p>However, I have some structs inside my classes and I need to figure out how to get their values. Moreoevr, I have some LIst. I need to get their value as well.... I will post if I update my code.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12999/"
]
| Is there a way to iterate (through foreach preferably) over a collection using reflection? I'm iterating over the properties in an object using reflection, and when the program gets to a type that is a collection, I'd like it to iterate over the contents of the collection and be able to access the objects in the collection.
At the moment I have an attribute set on all of my properties, with an IsCollection flag set to true on the properties that are collections. My code checks for this flag and if it's true, it gets the Type using reflection. Is there a way to invoke GetEnumerator or Items somehow on a collection to be able to iterate over the items? | I had this issue, but instead of using reflection, i ended up just checking if it was IEnumerable. All collections implement that.
```
if (item is IEnumerable)
{
foreach (object o in (item as IEnumerable))
{
}
} else {
// reflect over item
}
``` |
104,612 | <p>I want to copy a live production database into my local development database. Is there a way to do this without locking the production database?</p>
<p>I'm currently using:</p>
<pre class="lang-none prettyprint-override"><code>mysqldump -u root --password=xxx -h xxx my_db1 | mysql -u root --password=xxx -h localhost my_db1
</code></pre>
<p>But it's locking each table as it runs.</p>
| [
{
"answer_id": 104628,
"author": "John Millikin",
"author_id": 3560,
"author_profile": "https://Stackoverflow.com/users/3560",
"pm_score": 10,
"selected": true,
"text": "<p>Does the <code>--lock-tables=false</code> option work?</p>\n<p>According to the <a href=\"https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#option_mysqldump_lock-tables\" rel=\"noreferrer\">man page</a>, if you are dumping InnoDB tables you can use the <code>--single-transaction</code> option:</p>\n<pre class=\"lang-none prettyprint-override\"><code>--lock-tables, -l\n\nLock all tables before dumping them. The tables are locked with READ\nLOCAL to allow concurrent inserts in the case of MyISAM tables. For\ntransactional tables such as InnoDB and BDB, --single-transaction is\na much better option, because it does not need to lock the tables at\nall.\n</code></pre>\n<p>For <strong>innodb DB</strong>:</p>\n<pre><code>mysqldump --single-transaction=TRUE -u username -p DB\n</code></pre>\n"
},
{
"answer_id": 104921,
"author": "mike",
"author_id": 19217,
"author_profile": "https://Stackoverflow.com/users/19217",
"pm_score": 3,
"selected": false,
"text": "<p>Honestly, I would setup replication for this, as if you don't lock tables you will get inconsistent data out of the dump.</p>\n\n<p>If the dump takes longer time, tables which were already dumped might have changed along with some table which is only about to be dumped.</p>\n\n<p>So either lock the tables or use replication.</p>\n"
},
{
"answer_id": 105207,
"author": "dvorak",
"author_id": 19235,
"author_profile": "https://Stackoverflow.com/users/19235",
"pm_score": 6,
"selected": false,
"text": "<p>The answer varies depending on what storage engine you're using. The ideal scenario is if you're using InnoDB. In that case you can use the <code>--single-transaction</code> flag, which will give you a coherent snapshot of the database at the time that the dump begins.</p>\n"
},
{
"answer_id": 1263296,
"author": "Warren Krewenki",
"author_id": 98028,
"author_profile": "https://Stackoverflow.com/users/98028",
"pm_score": 8,
"selected": false,
"text": "<p>This is ages too late, but good for anyone that is searching the topic. If you're not innoDB, and you're not worried about locking while you dump simply use the option:</p>\n\n<pre><code>--lock-tables=false\n</code></pre>\n"
},
{
"answer_id": 4460408,
"author": "Azamat Tokhtaev",
"author_id": 544701,
"author_profile": "https://Stackoverflow.com/users/544701",
"pm_score": 6,
"selected": false,
"text": "<p><code>--skip-add-locks</code> helped for me</p>\n"
},
{
"answer_id": 10395650,
"author": "naveen_sfx",
"author_id": 1099905,
"author_profile": "https://Stackoverflow.com/users/1099905",
"pm_score": 3,
"selected": false,
"text": "<pre><code> mysqldump -uuid -ppwd --skip-opt --single-transaction --max_allowed_packet=1G -q db | mysql -u root --password=xxx -h localhost db\n</code></pre>\n"
},
{
"answer_id": 10454782,
"author": "dgitman",
"author_id": 1273029,
"author_profile": "https://Stackoverflow.com/users/1273029",
"pm_score": 4,
"selected": false,
"text": "<p>To dump large tables, you should combine the --single-transaction option with --quick.</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_single-transaction\">http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_single-transaction</a></p>\n"
},
{
"answer_id": 10726820,
"author": "dtbarne",
"author_id": 477628,
"author_profile": "https://Stackoverflow.com/users/477628",
"pm_score": 4,
"selected": false,
"text": "<p>This is about as late compared to the guy who said he was late as he was to the original answer, but in my case (MySQL via WAMP on Windows 7), I had to use:</p>\n\n<pre><code>--skip-lock-tables\n</code></pre>\n"
},
{
"answer_id": 14252179,
"author": "Lex",
"author_id": 615397,
"author_profile": "https://Stackoverflow.com/users/615397",
"pm_score": 4,
"selected": false,
"text": "<p>For InnoDB tables use flag <code>--single-transaction</code></p>\n\n<blockquote>\n <p>it dumps the consistent state of the database at the time when BEGIN\n was issued without blocking any applications</p>\n</blockquote>\n\n<p>MySQL DOCS</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_single-transaction\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/5.1/en/mysqldump.html#option_mysqldump_single-transaction</a></p>\n"
},
{
"answer_id": 40113862,
"author": "augustomen",
"author_id": 317971,
"author_profile": "https://Stackoverflow.com/users/317971",
"pm_score": -1,
"selected": false,
"text": "<p>As none of these approaches worked for me, I simply did a:</p>\n\n<pre><code>mysqldump [...] | grep -v \"LOCK TABLE\" | mysql [...]\n</code></pre>\n\n<p>It will exclude both <code>LOCK TABLE <x></code> and <code>UNLOCK TABLES</code> commands.</p>\n\n<p><strong>Note:</strong> Hopefully your data doesn't contain that string in it!</p>\n"
},
{
"answer_id": 45650415,
"author": "Andrés Morales",
"author_id": 422765,
"author_profile": "https://Stackoverflow.com/users/422765",
"pm_score": 0,
"selected": false,
"text": "<p>Another late answer:</p>\n\n<p>If you are trying to make a hot copy of server database (in a linux environment) and the database engine of all tables is MyISAM you <strong>should</strong> use <code>mysqlhotcopy</code>.</p>\n\n<p>Acordingly to documentation:</p>\n\n<blockquote>\n <p>It uses FLUSH TABLES, LOCK TABLES, and cp or scp to make a database\n backup. It is a fast way to make a backup of the database or single\n tables, but it can be run only on the same machine where the database\n directories are located. mysqlhotcopy works only for backing up\n MyISAM and ARCHIVE tables.</p>\n</blockquote>\n\n<p>The <code>LOCK TABLES</code> time depends of the time the server can copy MySQL files (it doesn't make a dump).</p>\n"
},
{
"answer_id": 52857141,
"author": "Dmytro Gierman",
"author_id": 7709003,
"author_profile": "https://Stackoverflow.com/users/7709003",
"pm_score": 1,
"selected": false,
"text": "<p>Due to <a href=\"https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#option_mysqldump_lock-tables\" rel=\"nofollow noreferrer\">https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#option_mysqldump_lock-tables</a> :</p>\n\n<blockquote>\n <p>Some options, such as --opt (which is enabled by default), automatically enable --lock-tables. If you want to override this, use --skip-lock-tables at the end of the option list.</p>\n</blockquote>\n"
},
{
"answer_id": 54931736,
"author": "Samuel Diogo",
"author_id": 2551889,
"author_profile": "https://Stackoverflow.com/users/2551889",
"pm_score": 2,
"selected": false,
"text": "<p>When using MySQL Workbench, at Data Export, click in Advanced Options and uncheck the \"lock-tables\" options.</p>\n\n<p><a href=\"https://i.stack.imgur.com/3d2Gg.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3d2Gg.png\" alt=\"enter image description here\"></a> </p>\n"
},
{
"answer_id": 65717342,
"author": "user14570900",
"author_id": 14570900,
"author_profile": "https://Stackoverflow.com/users/14570900",
"pm_score": 1,
"selected": false,
"text": "<p>If you use the Percona XtraDB Cluster -\nI found that adding\n--skip-add-locks<br />\nto the mysqldump command\nAllows the Percona XtraDB Cluster to run the dump file\nwithout an issue about LOCK TABLES commands in the dump file.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13009/"
]
| I want to copy a live production database into my local development database. Is there a way to do this without locking the production database?
I'm currently using:
```none
mysqldump -u root --password=xxx -h xxx my_db1 | mysql -u root --password=xxx -h localhost my_db1
```
But it's locking each table as it runs. | Does the `--lock-tables=false` option work?
According to the [man page](https://dev.mysql.com/doc/refman/5.7/en/mysqldump.html#option_mysqldump_lock-tables), if you are dumping InnoDB tables you can use the `--single-transaction` option:
```none
--lock-tables, -l
Lock all tables before dumping them. The tables are locked with READ
LOCAL to allow concurrent inserts in the case of MyISAM tables. For
transactional tables such as InnoDB and BDB, --single-transaction is
a much better option, because it does not need to lock the tables at
all.
```
For **innodb DB**:
```
mysqldump --single-transaction=TRUE -u username -p DB
``` |
104,618 | <p>I've been trying to get into F# on and off for a while but I keep getting put off. Why?</p>
<p>Because no matter which 'beginners' resource I try to look at I see very simple examples that start using the operator <code>-></code>.</p>
<p>However, nowhere have I found as yet that provides a clear simple explanation of what this operator means. It's as though it must be so obvious that it doesn't need explanation even to complete newbies.</p>
<p>I must therefore be really dense or perhaps it's nearly 3 decades of previous experience holding me back.</p>
<p>Can someone please, explain it or point to a truly accessible resource that explains it?</p>
| [
{
"answer_id": 104744,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 4,
"selected": false,
"text": "<p>It basically means \"maps to\". Read it that way or as \"is transformed into\" or something like that.</p>\n\n<p>So, from the <a href=\"http://blogs.msdn.com/chrsmith/archive/2008/05/02/f-in-20-minutes-part-i.aspx\" rel=\"noreferrer\">F# in 20 minutes</a> tutorial,</p>\n\n<pre><code>> List.map (fun x -> x % 2 = 0) [1 .. 10];;\nval it : bool list\n= [false; true; false; true; false; true; false; true; false; true]\n</code></pre>\n\n<blockquote>\n <p>The code (fun i -> i % 2 = 0) defines\n an anonymous function, called a lambda\n expression, that has a parameter x and\n the function returns the result of \"x\n % 2 = 0\", which is whether or not x is\n even.</p>\n</blockquote>\n"
},
{
"answer_id": 104759,
"author": "Brettski",
"author_id": 5836,
"author_profile": "https://Stackoverflow.com/users/5836",
"pm_score": 1,
"selected": false,
"text": "<p>From <a href=\"http://research.microsoft.com/fsharp/manual/quicktour.aspx?0sr=a\" rel=\"nofollow noreferrer\">Microsoft</a>:</p>\n\n<blockquote>\n <p>Function types are the types given to\n first-class function values and are\n written int -> int. They are similar\n to .NET delegate types, except they\n aren't given names. All F# function\n identifiers can be used as first-class\n function values, and anonymous\n function values can be created using\n the (fun ... -> ...) expression form.</p>\n</blockquote>\n"
},
{
"answer_id": 104779,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 2,
"selected": false,
"text": "<p>(a -> b) means \"function from a to b\". In type annotation, it denotes a function type. For example, f : (int -> String) means that f refers to a function that takes an integer and returns a string. It is also used as a contstructor of such values, as in</p>\n\n<pre><code>val f : (int -> int) = fun n -> n * 2\n</code></pre>\n\n<p>which creates a value which is a function from some number n to that same number multiplied by two.</p>\n"
},
{
"answer_id": 104924,
"author": "Mikael Jansson",
"author_id": 18753,
"author_profile": "https://Stackoverflow.com/users/18753",
"pm_score": 0,
"selected": false,
"text": "<p>The nice thing about languages such as Haskell (it's very similar in F#, but I don't know the exact syntax -- this should help you understand ->, though) is that you can apply only parts of the argument, to create <em>curried</em> functions:</p>\n\n<pre><code>adder n x y = n + x + y\n</code></pre>\n\n<p>In other words: \"give me three things, and I'll add them together\". When you throw numbers at it, the compiler will infer the types of n x and y. Say you write</p>\n\n<pre><code>adder 1 2 3\n</code></pre>\n\n<p>The type of 1, 2 and 3 is Int. Therefore:</p>\n\n<pre><code>adder :: Int -> Int -> Int -> Int\n</code></pre>\n\n<p>That is, give me three integers, and I will become an integer, eventually, or the same thing as saying:</p>\n\n<pre><code>five :: Int\nfive = 5\n</code></pre>\n\n<p>But, here's the nice part! Try this:</p>\n\n<pre><code>add5 = adder 5\n</code></pre>\n\n<p>As you remember, adder takes an int, an int, an int, and gives you back an int. However, that is not the entire truth, as you'll see shortly. In fact, add5 will have this type:</p>\n\n<pre><code>add5 :: Int -> Int -> Int\n</code></pre>\n\n<p>It will be as if you have \"peeled off\" of the integers (the left-most), and glued it directly to the function. Looking closer at the function signature, we notice that the -> are right-associative, i.e.:</p>\n\n<pre><code>addder :: Int -> (Int -> (Int -> Int))\n</code></pre>\n\n<p>This should make it quite clear: when you give adder the first integer, it'll evaluate to whatever's to the right of the first arrow, or:</p>\n\n<pre><code>add5andtwomore :: Int -> (Int -> Int)\nadd5andtwomore = adder 5\n</code></pre>\n\n<p>Now you can use add5andtwomore instead of \"adder 5\". This way, you can apply another integer to get (say) \"add5and7andonemore\":</p>\n\n<pre><code>add5and7andonemore :: Int -> Int\nadd5and7andonemore = adder 5 7\n</code></pre>\n\n<p>As you see, add5and7andonemore wants exactly another argument, and when you give it one, it will suddenly become an integer!</p>\n\n<pre><code> > add5and7andonemore 9\n => ((add5andtwomore) 7) 9\n => ((adder 5) 7) 9)\n<=> adder 5 7 9\n</code></pre>\n\n<p>Substituting the parameters to adder (n x y) for (5 7 9), we get:</p>\n\n<pre><code> > adder 5 7 9 = 5 + 7 + 9\n => 5 + 7 + 9\n => 21\n</code></pre>\n\n<p><em>In fact</em>, plus is also just a function that takes an int and gives you back another int, so the above is really more like:</p>\n\n<pre><code> > 5 + 7 + 9\n => (+ 5 (+ 7 9))\n => (+ 5 16)\n => 21\n</code></pre>\n\n<p>There you go!</p>\n"
},
{
"answer_id": 105013,
"author": "Chris Smith",
"author_id": 322,
"author_profile": "https://Stackoverflow.com/users/322",
"pm_score": 1,
"selected": false,
"text": "<p>There are plenty of great answers here already, I just want to add to the conversation another way of thinking about it.</p>\n\n<p>' -> ' means function. </p>\n\n<p>'a -> 'b is a function that takes an 'a and returns a 'b</p>\n\n<p>('a * 'b) -> ('c * 'd) is a function that takes a tuple of type ('a, 'b) and returns a tuple of ('c, 'd). Such as int/string returns float/char.</p>\n\n<p>Where it gets interesting is in the cascade case of 'a -> 'b -> 'c. This is a function that takes an 'a and returns a function ('b -> 'c), or a function that takes a 'b -> 'c.</p>\n\n<p>So if you write:\n let f x y z = ()</p>\n\n<p>The type will be f : 'a -> 'b -> 'c -> unit, so if you only applied the first parameter, the result would be a curried function 'b -> 'c -> 'unit. </p>\n"
},
{
"answer_id": 105157,
"author": "Michiel Borkent",
"author_id": 6264,
"author_profile": "https://Stackoverflow.com/users/6264",
"pm_score": 1,
"selected": false,
"text": "<p>In the context of defining a function, it is similar to <code>=></code> from the lambda expression in C# 3.0.</p>\n\n<pre><code>F#: let f = fun x -> x*x\nC#: Func<int, int> f = x => x * x;\n</code></pre>\n\n<p>The <code>-></code> in F# is also used in pattern matching, where it means: if the expression matches the part between <code>|</code> and <code>-></code>, then what comes after <code>-></code> should be given back as the result:</p>\n\n<pre><code>let isOne x = match x with\n | 1 -> true\n | _ -> false\n</code></pre>\n"
},
{
"answer_id": 105318,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 3,
"selected": false,
"text": "<p>First question - are you familiar with lambda expressions in C#? If so the -> in F# is the same as the => in C# (I think you read it 'goes to').</p>\n\n<p>The -> operator can also be found in the context of pattern matching</p>\n\n<pre><code>match x with\n| 1 -> dosomething\n| _ -> dosomethingelse\n</code></pre>\n\n<p>I'm not sure if this is also a lambda expression, or something else, but I guess the 'goes to' still holds.</p>\n\n<p>Maybe what you are really referring to is the F# parser's 'cryptic' responses:</p>\n\n<pre><code>> let add a b = a + b\nval add: int -> int -> int\n</code></pre>\n\n<p>This means (as most of the examples explain) that add is a 'val' that takes two ints and returns an int. To me this was totally opaque to start with. I mean, how do I know that add isn't a val that takes one int and returns two ints?</p>\n\n<p>Well, the thing is that in a sense, it does. If I give add just one int, I get back an (int -> int):</p>\n\n<pre><code>> let inc = add 1\nval inc: int -> int\n</code></pre>\n\n<p>This (currying) is one of the things that makes F# so sexy, for me. </p>\n\n<p>For helpful info on F#, I have found that blogs are FAR more useful that any of the official 'documentation': Here are some names to check out</p>\n\n<ul>\n<li><a href=\"http://diditwith.net\" rel=\"nofollow noreferrer\">Dustin Campbell</a> (that's diditwith.net, cited in another answer)</li>\n<li><a href=\"http://blogs.msdn.com/dsyme\" rel=\"nofollow noreferrer\">Don Symes</a> ('the' man)</li>\n<li><a href=\"http://Tomasp.net\" rel=\"nofollow noreferrer\">Tomasp.net</a> (aka <a href=\"https://stackoverflow.com/users/33518/tomas-petricek\">Tomas Petricek</a>)</li>\n<li><a href=\"http://blogs.msdn.com/andrewkennedy\" rel=\"nofollow noreferrer\">Andrew Kennedy</a> (for units of measure)</li>\n<li><a href=\"http://Fsharp.it\" rel=\"nofollow noreferrer\">Fsharp.it</a> (famous for the Project Euler solutions)</li>\n<li><a href=\"http://lorgonblog.spaces.live.com/Blog\" rel=\"nofollow noreferrer\">http://lorgonblog.spaces.live.com/Blog</a> (aka <a href=\"https://stackoverflow.com/users/19299/brian\">Brian</a>)</li>\n<li><a href=\"http://blogs.msdn.com/jomo_fisher\" rel=\"nofollow noreferrer\">Jomo Fisher</a></li>\n</ul>\n"
},
{
"answer_id": 105559,
"author": "Brian",
"author_id": 19299,
"author_profile": "https://Stackoverflow.com/users/19299",
"pm_score": 7,
"selected": true,
"text": "<p>'->' is not an operator. It appears in the F# syntax in a number of places, and its meaning depends on how it is used as part of a larger construct.</p>\n\n<p>Inside a type, '->' describes function types as people have described above. For example</p>\n\n<pre><code>let f : int -> int = ...\n</code></pre>\n\n<p>says that 'f' is a function that takes an int and returns an int.</p>\n\n<p>Inside a lambda (\"thing that starts with 'fun' keyword\"), '->' is syntax that separates the arguments from the body. For example</p>\n\n<pre><code>fun x y -> x + y + 1\n</code></pre>\n\n<p>is an expression that defines a two argument function with the given implementation.</p>\n\n<p>Inside a \"match\" construct, '->' is syntax that separates patterns from the code that should run if the pattern is matched. For example, in</p>\n\n<pre><code>match someList with\n| [] -> 0\n| h::t -> 1\n</code></pre>\n\n<p>the stuff to the left of each '->' are patterns, and the stuff on the right is what happens if the pattern on the left was matched.</p>\n\n<p>The difficulty in understanding may be rooted in the faulty assumption that '->' is \"an operator\" with a single meaning. An analogy might be \".\" in C#, if you have never seen any code before, and try to analyze the \".\" operator based on looking at \"obj.Method\" and \"3.14\" and \"System.Collections\", you may get very confused, because the symbol has different meanings in different contexts. Once you know enough of the language to recognize these contexts, however, things become clear.</p>\n"
},
{
"answer_id": 109426,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 1,
"selected": false,
"text": "<p>Many great answers to this questions, thanks people. I'd like to put here an editable answer that brings things together.</p>\n\n<p>For those familiar with C# understanding -> being the same as => lamba expression is a good first step. This usage is :-</p>\n\n<pre><code>fun x y -> x + y + 1\n</code></pre>\n\n<p>Can be understood as the equivalent to:-</p>\n\n<pre><code>(x, y) => x + y + 1;\n</code></pre>\n\n<p>However its clear that -> has a more fundemental meaning which stems from concept that a function that takes two parameters such as the above can be reduced (is that the correct term?) to a series of functions only taking one parameter.</p>\n\n<p>Hence when the above is described in like this:-</p>\n\n<pre><code>Int -> Int -> Int\n</code></pre>\n\n<p>It really helped to know that -> is right associative hence the above can be considered:-</p>\n\n<pre><code>Int -> (Int -> Int)\n</code></pre>\n\n<p>Aha! We have a function that takes Int and returns (Int -> Int) (a curried function?).</p>\n\n<p>The explaination that -> can also appear as part of type definiton also helped. (Int -> Int) is the type of any of function which takes an Int and returns an Int.</p>\n\n<p>Also helpful is the -> appears in other syntax such as matching but there it doesn't have the same meaning? Is that correct? I'm not sure it is. I suspect it has the same meaning but I don't have the vocabulary to express that yet.</p>\n\n<p>Note the purpose of this answer is not to spawn further answers but to be collaboratively edited by you people to create a more definitive answer. Utlimately it would be good that all the uncertainies and fluf (such as this paragraph) be removed and better examples added. Lets try keep this answer as accessible to the uninitiated as possible.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17516/"
]
| I've been trying to get into F# on and off for a while but I keep getting put off. Why?
Because no matter which 'beginners' resource I try to look at I see very simple examples that start using the operator `->`.
However, nowhere have I found as yet that provides a clear simple explanation of what this operator means. It's as though it must be so obvious that it doesn't need explanation even to complete newbies.
I must therefore be really dense or perhaps it's nearly 3 decades of previous experience holding me back.
Can someone please, explain it or point to a truly accessible resource that explains it? | '->' is not an operator. It appears in the F# syntax in a number of places, and its meaning depends on how it is used as part of a larger construct.
Inside a type, '->' describes function types as people have described above. For example
```
let f : int -> int = ...
```
says that 'f' is a function that takes an int and returns an int.
Inside a lambda ("thing that starts with 'fun' keyword"), '->' is syntax that separates the arguments from the body. For example
```
fun x y -> x + y + 1
```
is an expression that defines a two argument function with the given implementation.
Inside a "match" construct, '->' is syntax that separates patterns from the code that should run if the pattern is matched. For example, in
```
match someList with
| [] -> 0
| h::t -> 1
```
the stuff to the left of each '->' are patterns, and the stuff on the right is what happens if the pattern on the left was matched.
The difficulty in understanding may be rooted in the faulty assumption that '->' is "an operator" with a single meaning. An analogy might be "." in C#, if you have never seen any code before, and try to analyze the "." operator based on looking at "obj.Method" and "3.14" and "System.Collections", you may get very confused, because the symbol has different meanings in different contexts. Once you know enough of the language to recognize these contexts, however, things become clear. |
104,747 | <p>I have a members table in MySQL</p>
<pre><code>CREATE TABLE `members` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(65) collate utf8_unicode_ci NOT NULL,
`order` tinyint(3) unsigned NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
</code></pre>
<p>And I would like to let users order the members how they like.
I'm storing the order in <code>order</code> column.</p>
<p>I'm wondering how to insert new user to be added to the bottom of the list.
This is what I have today:</p>
<pre><code>$db->query('insert into members VALUES (0, "new member", 0)');
$lastId = $db->lastInsertId();
$maxOrder = $db->fetchAll('select MAX(`order`) max_order FROM members');
$db->query('update members
SET
`order` = ?
WHERE
id = ?',
array(
$maxOrder[0]['max_order'] + 1,
$lastId
));
</code></pre>
<p>But that's not really precise while when there are several users adding new members at the same time, it might happen the <code>MAX(order)</code> will return the same values.</p>
<p>How do you handle such cases?</p>
| [
{
"answer_id": 104788,
"author": "sebastiaan",
"author_id": 5018,
"author_profile": "https://Stackoverflow.com/users/5018",
"pm_score": 2,
"selected": false,
"text": "<p>Since you already automatically increment the id for each new member, you can order by id.</p>\n"
},
{
"answer_id": 104802,
"author": "klasbas",
"author_id": 14801,
"author_profile": "https://Stackoverflow.com/users/14801",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure I understand. If each user wants a different order how will you store individual user preferences in one single field in the \"members\" table?</p>\n\n<p>Usually you just let users to order based on the natural order of the fields. What is the purpose of the order field?</p>\n"
},
{
"answer_id": 104834,
"author": "Chris Shaffer",
"author_id": 6744,
"author_profile": "https://Stackoverflow.com/users/6744",
"pm_score": 0,
"selected": false,
"text": "<p>Usually I make all my select statements order by \"order, name\"; Then I always insert the same value for Order (either 0 or 9999999 depending on if I want them first or last). Then the user can reorder however they like.</p>\n"
},
{
"answer_id": 104835,
"author": "boes",
"author_id": 17746,
"author_profile": "https://Stackoverflow.com/users/17746",
"pm_score": 0,
"selected": false,
"text": "<p>InnoDB supports transactions. Before the insert do a 'begin' statement and when your finished do a commit. See <a href=\"http://www.databasejournal.com/features/mysql/article.php/3382171\" rel=\"nofollow noreferrer\">this article</a> for an explanation of transactions in mySql.</p>\n"
},
{
"answer_id": 104961,
"author": "Harrison Fisk",
"author_id": 16111,
"author_profile": "https://Stackoverflow.com/users/16111",
"pm_score": 3,
"selected": true,
"text": "<p>You can do the SELECT as part of the INSERT, such as:</p>\n\n<pre>INSERT INTO members SELECT 0, \"new member\", max(`order`)+1 FROM members;</pre>\n\n<p>Keep in mind that you are going to want to have an index on the <code>order</code> column to make the SELECT part optimized. </p>\n\n<p>In addition, you might want to reconsider the tinyint for order, unless you only expect to only have 255 orders ever.</p>\n\n<p>Also order is a reserved word and you will always need to write it as `order`, so you might consider renaming that column as well.</p>\n"
},
{
"answer_id": 105217,
"author": "user10340",
"author_id": 10340,
"author_profile": "https://Stackoverflow.com/users/10340",
"pm_score": 0,
"selected": false,
"text": "<p>What you could do is create a table with keys (member_id,position) that maps to another member_id. Then you can store the ordering in that table separate from the member list itself. (Each member retains their own list ordering, which is what I assume you want...?)</p>\n\n<p>Supposing that you have a member table like this:</p>\n\n<pre><code>+-----------+--------------+\n| member_id | name |\n+-----------+--------------+\n| 1 | John Smith |\n| 2 | John Doe |\n| 3 | John Johnson |\n| 4 | Sue Someone |\n+-----------+--------------+\n</code></pre>\n\n<p>Then, you could have an ordering table like this:</p>\n\n<pre><code>+---------------+----------+-----------------+\n| member_id_key | position | member_id_value |\n+---------------+----------+-----------------+\n| 1 | 1 | 4 |\n| 1 | 2 | 1 |\n| 1 | 3 | 3 |\n| 1 | 4 | 2 |\n| 2 | 2 | 1 |\n| 2 | 3 | 2 |\n+---------------+----------+-----------------+\n</code></pre>\n\n<p>You can select the member list given the stored order by using an inner join. For example:</p>\n\n<pre><code>SELECT name\nFROM members inner join orderings \n ON members.member_id = orderings.member_id_value\nWHERE orderings.member_id_key = <ID for member you want to lookup>\nORDER BY position;\n</code></pre>\n\n<p>As an example, the result of running this query for John Smith's list (ie, WHERE member_id_key = 1) would be:</p>\n\n<pre><code>+--------------+\n| name |\n+--------------+\n| Sue Someone |\n| John Smith |\n| John Johnson |\n| John Doe |\n+--------------+\n</code></pre>\n\n<p>You can calculate position for adding to the bottom of the list by adding one to the max position value for a given id.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104747",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19217/"
]
| I have a members table in MySQL
```
CREATE TABLE `members` (
`id` int(10) unsigned NOT NULL auto_increment,
`name` varchar(65) collate utf8_unicode_ci NOT NULL,
`order` tinyint(3) unsigned NOT NULL default '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB;
```
And I would like to let users order the members how they like.
I'm storing the order in `order` column.
I'm wondering how to insert new user to be added to the bottom of the list.
This is what I have today:
```
$db->query('insert into members VALUES (0, "new member", 0)');
$lastId = $db->lastInsertId();
$maxOrder = $db->fetchAll('select MAX(`order`) max_order FROM members');
$db->query('update members
SET
`order` = ?
WHERE
id = ?',
array(
$maxOrder[0]['max_order'] + 1,
$lastId
));
```
But that's not really precise while when there are several users adding new members at the same time, it might happen the `MAX(order)` will return the same values.
How do you handle such cases? | You can do the SELECT as part of the INSERT, such as:
```
INSERT INTO members SELECT 0, "new member", max(`order`)+1 FROM members;
```
Keep in mind that you are going to want to have an index on the `order` column to make the SELECT part optimized.
In addition, you might want to reconsider the tinyint for order, unless you only expect to only have 255 orders ever.
Also order is a reserved word and you will always need to write it as `order`, so you might consider renaming that column as well. |
104,791 | <p>The SQL-LDR documentation states that you need to do a convetional Path Load:</p>
<blockquote>
<p>When you want to apply SQL functions
to data fields. SQL functions are not
available during a direct path load</p>
</blockquote>
<p>I have TimeStamp data stored in a CSV file that I'm loading with SQL-LDR by describing the fields as such:</p>
<pre><code>STARTTIME "To_TimeStamp(:STARTTIME,'YYYY-MM-DD HH24:MI:SS.FF6')",
COMPLETIONTIME "To_TimeStamp(:COMPLETIONTIME,'YYYY-MM-DD HH24:MI:SS.FF6')"
</code></pre>
<p>So my question is: Can you load timestamp data without a function, or is it the case that you can not do a Direct Path Load when Loading TimeStamp data?</p>
| [
{
"answer_id": 104783,
"author": "blowdart",
"author_id": 2525,
"author_profile": "https://Stackoverflow.com/users/2525",
"pm_score": 0,
"selected": false,
"text": "<p>A little more information please; do you want to log IPs or lock access via IP? Both those functions are built into IIS rather than ASP.NET; so are you looking for how to limit access via IP programatically?</p>\n"
},
{
"answer_id": 104839,
"author": "AaronS",
"author_id": 26932,
"author_profile": "https://Stackoverflow.com/users/26932",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the following to get a user's IP address:</p>\n\n<pre><code> Request.ServerVariables[\"REMOTE_ADDR\"]\n</code></pre>\n\n<p>Once you have the IP you will have to write something custom to log it or block by IP. There isn't something built in to asp.net to do this for you.</p>\n"
},
{
"answer_id": 104876,
"author": "CodeRot",
"author_id": 14134,
"author_profile": "https://Stackoverflow.com/users/14134",
"pm_score": 3,
"selected": true,
"text": "<p>As blowdart said, simple IP Address logging is handled by IIS already. Simply right-click on the Website in Internet Information Services (IIS) Manager tool, go to the Web Site tab, and check the Enable Logging box. You can customize what information is logged also. </p>\n\n<p>If you want to restrict the site or even a folder of the site to specific IP's, just go to the IIS Site or Folder properties that you want to protect in the IIS Manager, right click and select Properties. Choose the Directory Security tab. In the middle you should see the \"IP Addresses and domain name restrictions. This will be where you can setup which IP's to block or allow.</p>\n\n<p>If you want to do this programatically in the code-behind of ASP.Net, you could use the page preinit event.</p>\n"
},
{
"answer_id": 105373,
"author": "Chris Cudmore",
"author_id": 18907,
"author_profile": "https://Stackoverflow.com/users/18907",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p><em>Is there an event that's called everytime a page is loaded?</em></p>\n</blockquote>\n\n<p><code>Page_Load</code> might be what you're looking for.</p>\n\n<p>However, and I'm really not trying to be mean here, if you don't know that, you probably shouldn't be trying to secure the app. You're just not experienced enough in <code>.Net</code></p>\n\n<p>I'm sure you're great at what you do, in whatever platform you're experienced in. But <code>.Net WebForms</code> isn't your forte. This is one of those times when you should back off and let someone else handle it.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9940/"
]
| The SQL-LDR documentation states that you need to do a convetional Path Load:
>
> When you want to apply SQL functions
> to data fields. SQL functions are not
> available during a direct path load
>
>
>
I have TimeStamp data stored in a CSV file that I'm loading with SQL-LDR by describing the fields as such:
```
STARTTIME "To_TimeStamp(:STARTTIME,'YYYY-MM-DD HH24:MI:SS.FF6')",
COMPLETIONTIME "To_TimeStamp(:COMPLETIONTIME,'YYYY-MM-DD HH24:MI:SS.FF6')"
```
So my question is: Can you load timestamp data without a function, or is it the case that you can not do a Direct Path Load when Loading TimeStamp data? | As blowdart said, simple IP Address logging is handled by IIS already. Simply right-click on the Website in Internet Information Services (IIS) Manager tool, go to the Web Site tab, and check the Enable Logging box. You can customize what information is logged also.
If you want to restrict the site or even a folder of the site to specific IP's, just go to the IIS Site or Folder properties that you want to protect in the IIS Manager, right click and select Properties. Choose the Directory Security tab. In the middle you should see the "IP Addresses and domain name restrictions. This will be where you can setup which IP's to block or allow.
If you want to do this programatically in the code-behind of ASP.Net, you could use the page preinit event. |
104,797 | <p>What is the best way to create a webservice for accepting an image.
The image might be quite big and I do not want to change the default receive size for the web application.
I have written one that accepts a binary image but that I feel that there has to be a better alternative.</p>
| [
{
"answer_id": 104902,
"author": "core",
"author_id": 11574,
"author_profile": "https://Stackoverflow.com/users/11574",
"pm_score": 3,
"selected": true,
"text": "<p>Where does this image \"live?\" Is it accessible in the local file system or on the web? If so, I would suggest having your WebService accepting a URI (can be a URL or a local file) and opening it as a Stream, then using a StreamReader to read the contents of it.</p>\n\n<p>Example (but wrap the exceptions in FaultExceptions, and add FaultContractAttributes):</p>\n\n<pre><code>using System.Drawing;\nusing System.IO;\nusing System.Net;\nusing System.Net.Sockets;\n\n[OperationContract]\npublic void FetchImage(Uri url)\n{\n // Validate url\n\n if (url == null)\n {\n throw new ArgumentNullException(url);\n }\n\n // If the service doesn't know how to resolve relative URI paths\n\n /*if (!uri.IsAbsoluteUri)\n {\n throw new ArgumentException(\"Must be absolute.\", url);\n }*/\n\n // Download and load the image\n\n Image image = new Func<Bitmap>(() =>\n {\n try\n {\n using (WebClient downloader = new WebClient())\n {\n return new Bitmap(downloader.OpenRead(url));\n }\n }\n catch (ArgumentException exception)\n {\n throw new ResourceNotImageException(url, exception);\n }\n catch (WebException exception)\n {\n throw new ImageDownloadFailedException(url, exception);\n }\n\n // IOException and SocketException are not wrapped by WebException :( \n\n catch (IOException exception)\n {\n throw new ImageDownloadFailedException(url, exception);\n }\n catch (SocketException exception)\n {\n throw new ImageDownloadFailedException(url, exception);\n }\n })();\n\n // Do something with image\n\n}\n</code></pre>\n"
},
{
"answer_id": 2583207,
"author": "Nathan",
"author_id": 309054,
"author_profile": "https://Stackoverflow.com/users/309054",
"pm_score": 0,
"selected": false,
"text": "<p>Can't you upload the image to the server using FTP, then when that's done the server (and thus WCF service) van easily access it? That way you don't need to thinker with the receive size settings etc.</p>\n\n<p>At least, that's how I did it.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/403/"
]
| What is the best way to create a webservice for accepting an image.
The image might be quite big and I do not want to change the default receive size for the web application.
I have written one that accepts a binary image but that I feel that there has to be a better alternative. | Where does this image "live?" Is it accessible in the local file system or on the web? If so, I would suggest having your WebService accepting a URI (can be a URL or a local file) and opening it as a Stream, then using a StreamReader to read the contents of it.
Example (but wrap the exceptions in FaultExceptions, and add FaultContractAttributes):
```
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
[OperationContract]
public void FetchImage(Uri url)
{
// Validate url
if (url == null)
{
throw new ArgumentNullException(url);
}
// If the service doesn't know how to resolve relative URI paths
/*if (!uri.IsAbsoluteUri)
{
throw new ArgumentException("Must be absolute.", url);
}*/
// Download and load the image
Image image = new Func<Bitmap>(() =>
{
try
{
using (WebClient downloader = new WebClient())
{
return new Bitmap(downloader.OpenRead(url));
}
}
catch (ArgumentException exception)
{
throw new ResourceNotImageException(url, exception);
}
catch (WebException exception)
{
throw new ImageDownloadFailedException(url, exception);
}
// IOException and SocketException are not wrapped by WebException :(
catch (IOException exception)
{
throw new ImageDownloadFailedException(url, exception);
}
catch (SocketException exception)
{
throw new ImageDownloadFailedException(url, exception);
}
})();
// Do something with image
}
``` |
104,803 | <p>I've got a (mostly) working plugin developed, but since its function is directly related to the project it processes, how do you develop unit and integration tests for the plugin. The best idea I've had is to create an integration test project for the plugin that uses the plugin during its lifecycle and has tests that report on the plugins success or failure in processing the data.</p>
<p>Anyone with better ideas?</p>
| [
{
"answer_id": 105259,
"author": "Brian Matthews",
"author_id": 1969,
"author_profile": "https://Stackoverflow.com/users/1969",
"pm_score": 4,
"selected": true,
"text": "<p>You need to use the <a href=\"http://maven.apache.org/shared/maven-plugin-testing-harness/\" rel=\"noreferrer\">maven-plugin-testing-harness</a>, </p>\n\n<pre>\n <dependency>\n <groupId>org.apache.maven.shared</groupId>\n <artifactId>maven-plugin-testing-harness</artifactId>\n <version>1.1</version>\n <scope>test</scope>\n </dependency>\n</pre>\n\n<p>You derive your unit test classes from <a href=\"http://maven.apache.org/shared/maven-plugin-testing-harness/apidocs/org/apache/maven/plugin/testing/AbstractMojoTestCase.html\" rel=\"noreferrer\">AbstractMojoTestCase</a>. </p>\n\n<p>You need to create a bare bones POM, usually in the <code>src/test/resources</code> folder. </p>\n\n<pre>\n <project>\n <build>\n <plugins>\n <plugin>\n <groupId>com.mydomain,mytools</groupId>\n <artifactId>mytool-maven-plugin</artifactId>\n <configuration>\n <!-- Insert configuration settings here -->\n </configuration>\n <executions>\n <execution>\n <goals>\n <goal>mygoal</goal>\n </goals>\n </execution>\n </executions>\n </plugin>\n </plugins>\n </build>\n </project>\n</pre>\n\n<p>Use the AbstractMojoTest.lookupMojo(String,File) (or one of the other variations) to load the Mojo for a specific goal and execute it.</p>\n\n<pre>\n final File testPom = new File(PlexusTestCase.getBasedir(), \"/target/test-classes/mytools-plugin-config.xml\");\n Mojo mojo = this.lookupMojo(\"mygoal\", testPom);\n // Insert assertions to validate that your plugin was initialised correctly\n mojo.execute();\n // Insert assertions to validate that your plugin behaved as expected\n</pre>\n\n<p>I created my a plugin of my own that you can refer to for clarification <a href=\"http://ldap-plugin.btmatthews.com\" rel=\"noreferrer\">http://ldap-plugin.btmatthews.com</a>,</p>\n"
},
{
"answer_id": 105577,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 1,
"selected": false,
"text": "<p>If you'd like to see some real-world examples, the Terracotta Maven plugin (tc-maven-plugin) has some tests with it that you can peruse in the open source forge.</p>\n\n<p>The plugin is at: <a href=\"http://forge.terracotta.org/releases/projects/tc-maven-plugin/\" rel=\"nofollow noreferrer\">http://forge.terracotta.org/releases/projects/tc-maven-plugin/</a></p>\n\n<p>And the source is in svn at: <a href=\"http://svn.terracotta.org/svn/forge/projects/tc-maven-plugin/trunk/\" rel=\"nofollow noreferrer\">http://svn.terracotta.org/svn/forge/projects/tc-maven-plugin/trunk/</a></p>\n\n<p>And in that source you can find some actual Maven plugin tests at: src/test/java/org/terracotta/maven/plugins/tc/</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104803",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17008/"
]
| I've got a (mostly) working plugin developed, but since its function is directly related to the project it processes, how do you develop unit and integration tests for the plugin. The best idea I've had is to create an integration test project for the plugin that uses the plugin during its lifecycle and has tests that report on the plugins success or failure in processing the data.
Anyone with better ideas? | You need to use the [maven-plugin-testing-harness](http://maven.apache.org/shared/maven-plugin-testing-harness/),
```
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-plugin-testing-harness</artifactId>
<version>1.1</version>
<scope>test</scope>
</dependency>
```
You derive your unit test classes from [AbstractMojoTestCase](http://maven.apache.org/shared/maven-plugin-testing-harness/apidocs/org/apache/maven/plugin/testing/AbstractMojoTestCase.html).
You need to create a bare bones POM, usually in the `src/test/resources` folder.
```
<project>
<build>
<plugins>
<plugin>
<groupId>com.mydomain,mytools</groupId>
<artifactId>mytool-maven-plugin</artifactId>
<configuration>
<!-- Insert configuration settings here -->
</configuration>
<executions>
<execution>
<goals>
<goal>mygoal</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
```
Use the AbstractMojoTest.lookupMojo(String,File) (or one of the other variations) to load the Mojo for a specific goal and execute it.
```
final File testPom = new File(PlexusTestCase.getBasedir(), "/target/test-classes/mytools-plugin-config.xml");
Mojo mojo = this.lookupMojo("mygoal", testPom);
// Insert assertions to validate that your plugin was initialised correctly
mojo.execute();
// Insert assertions to validate that your plugin behaved as expected
```
I created my a plugin of my own that you can refer to for clarification <http://ldap-plugin.btmatthews.com>, |
104,844 | <p>I'm looking for a way to find the name of the Windows default printer using unmanaged C++ (found plenty of .NET examples, but no success unmanaged). Thanks.</p>
| [
{
"answer_id": 104882,
"author": "Doug T.",
"author_id": 8123,
"author_profile": "https://Stackoverflow.com/users/8123",
"pm_score": 3,
"selected": true,
"text": "<p>The following works great for printing with the win32api from C++</p>\n\n<pre><code>char szPrinterName[255];\nunsigned long lPrinterNameLength;\nGetDefaultPrinter( szPrinterName, &lPrinterNameLength );\nHDC hPrinterDC;\nhPrinterDC = CreateDC(\"WINSPOOL\\0\", szPrinterName, NULL, NULL);\n</code></pre>\n\n<p>In the future instead of googling \"unmanaged\" try googling \"win32 /subject/\" or \"win32 api /subject/\"</p>\n"
},
{
"answer_id": 104904,
"author": "christopher_f",
"author_id": 9224,
"author_profile": "https://Stackoverflow.com/users/9224",
"pm_score": 1,
"selected": false,
"text": "<p>GetDefaultPrinter <a href=\"http://msdn.microsoft.com/en-us/library/ms535475(VS.85).aspx\" rel=\"nofollow noreferrer\">(MSDN)</a> ought to do the trick. That will get you the name to pass to CreateDC for printing.</p>\n"
},
{
"answer_id": 104910,
"author": "KPexEA",
"author_id": 13676,
"author_profile": "https://Stackoverflow.com/users/13676",
"pm_score": 2,
"selected": false,
"text": "<p>Here is how to get a list of current printers and the default one if there is one set as the default.</p>\n\n<p>Also note: getting zero for the default printer name length is valid if the user has no printers or has not set one as default. </p>\n\n<p>Also being able to handle long printer names should be supported so calling GetDefaultPrinter with NULL as a buffer pointer first will return the name length and then you can allocate a name buffer big enough to hold the name.</p>\n\n<pre><code>DWORD numprinters;\nDWORD defprinter=0;\nDWORD dwSizeNeeded=0;\nDWORD dwItem;\nLPPRINTER_INFO_2 printerinfo = NULL;\n\n// Get buffer size\n\nEnumPrinters ( PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS , NULL, 2, NULL, 0, &dwSizeNeeded, &numprinters );\n\n// allocate memory\n//printerinfo = (LPPRINTER_INFO_2)HeapAlloc ( GetProcessHeap (), HEAP_ZERO_MEMORY, dwSizeNeeded );\nprinterinfo = (LPPRINTER_INFO_2)new char[dwSizeNeeded];\n\nif ( EnumPrinters ( PRINTER_ENUM_LOCAL | PRINTER_ENUM_CONNECTIONS, // what to enumerate\n NULL, // printer name (NULL for all)\n 2, // level\n (LPBYTE)printerinfo, // buffer\n dwSizeNeeded, // size of buffer\n &dwSizeNeeded, // returns size\n &numprinters // return num. items\n ) == 0 )\n{\n numprinters=0;\n}\n\n{\n DWORD size=0; \n\n // Get the size of the default printer name.\n GetDefaultPrinter(NULL, &size);\n if(size)\n {\n // Allocate a buffer large enough to hold the printer name.\n TCHAR* buffer = new TCHAR[size];\n\n // Get the printer name.\n GetDefaultPrinter(buffer, &size);\n\n for ( dwItem = 0; dwItem < numprinters; dwItem++ )\n {\n if(!strcmp(buffer,printerinfo[dwItem].pPrinterName))\n defprinter=dwItem;\n }\n delete buffer;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 104914,
"author": "Panic",
"author_id": 18216,
"author_profile": "https://Stackoverflow.com/users/18216",
"pm_score": -1,
"selected": false,
"text": "<p>Unmanaged C++ doesn't exist (and managed C++ is now C++/CLI), if you are referring to C++, using unmanaged as a tag is just sad...</p>\n"
},
{
"answer_id": 104930,
"author": "jeffm",
"author_id": 1544,
"author_profile": "https://Stackoverflow.com/users/1544",
"pm_score": 2,
"selected": false,
"text": "<p>How to retrieve and set the default printer in Windows:</p>\n\n<p><a href=\"http://support.microsoft.com/default.aspx?scid=kb;EN-US;246772\" rel=\"nofollow noreferrer\">http://support.microsoft.com/default.aspx?scid=kb;EN-US;246772</a></p>\n\n<p>Code from now-unavailable article:</p>\n\n<pre><code>// You are explicitly linking to GetDefaultPrinter because linking \n// implicitly on Windows 95/98 or NT4 results in a runtime error.\n// This block specifies which text version you explicitly link to.\n#ifdef UNICODE\n #define GETDEFAULTPRINTER \"GetDefaultPrinterW\"\n#else\n #define GETDEFAULTPRINTER \"GetDefaultPrinterA\"\n#endif\n\n// Size of internal buffer used to hold \"printername,drivername,portname\"\n// string. You may have to increase this for huge strings.\n#define MAXBUFFERSIZE 250\n\n/*----------------------------------------------------------------*/ \n/* DPGetDefaultPrinter */ \n/* */ \n/* Parameters: */ \n/* pPrinterName: Buffer alloc'd by caller to hold printer name. */ \n/* pdwBufferSize: On input, ptr to size of pPrinterName. */ \n/* On output, min required size of pPrinterName. */ \n/* */ \n/* NOTE: You must include enough space for the NULL terminator! */ \n/* */ \n/* Returns: TRUE for success, FALSE for failure. */ \n/*----------------------------------------------------------------*/ \nBOOL DPGetDefaultPrinter(LPTSTR pPrinterName, LPDWORD pdwBufferSize)\n{\n BOOL bFlag;\n OSVERSIONINFO osv;\n TCHAR cBuffer[MAXBUFFERSIZE];\n PRINTER_INFO_2 *ppi2 = NULL;\n DWORD dwNeeded = 0;\n DWORD dwReturned = 0;\n HMODULE hWinSpool = NULL;\n PROC fnGetDefaultPrinter = NULL;\n\n // What version of Windows are you running?\n osv.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\n GetVersionEx(&osv);\n\n // If Windows 95 or 98, use EnumPrinters.\n if (osv.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)\n {\n // The first EnumPrinters() tells you how big our buffer must\n // be to hold ALL of PRINTER_INFO_2. Note that this will\n // typically return FALSE. This only means that the buffer (the 4th\n // parameter) was not filled in. You do not want it filled in here.\n SetLastError(0);\n bFlag = EnumPrinters(PRINTER_ENUM_DEFAULT, NULL, 2, NULL, 0, &dwNeeded, &dwReturned);\n {\n if ((GetLastError() != ERROR_INSUFFICIENT_BUFFER) || (dwNeeded == 0))\n return FALSE;\n }\n\n // Allocate enough space for PRINTER_INFO_2.\n ppi2 = (PRINTER_INFO_2 *)GlobalAlloc(GPTR, dwNeeded);\n if (!ppi2)\n return FALSE;\n\n // The second EnumPrinters() will fill in all the current information.\n bFlag = EnumPrinters(PRINTER_ENUM_DEFAULT, NULL, 2, (LPBYTE)ppi2, dwNeeded, &dwNeeded, &dwReturned);\n if (!bFlag)\n {\n GlobalFree(ppi2);\n return FALSE;\n }\n\n // If specified buffer is too small, set required size and fail.\n if ((DWORD)lstrlen(ppi2->pPrinterName) >= *pdwBufferSize)\n {\n *pdwBufferSize = (DWORD)lstrlen(ppi2->pPrinterName) + 1;\n GlobalFree(ppi2);\n return FALSE;\n }\n\n // Copy printer name into passed-in buffer.\n lstrcpy(pPrinterName, ppi2->pPrinterName);\n\n // Set buffer size parameter to minimum required buffer size.\n *pdwBufferSize = (DWORD)lstrlen(ppi2->pPrinterName) + 1;\n }\n\n // If Windows NT, use the GetDefaultPrinter API for Windows 2000,\n // or GetProfileString for version 4.0 and earlier.\n else if (osv.dwPlatformId == VER_PLATFORM_WIN32_NT)\n {\n if (osv.dwMajorVersion >= 5) // Windows 2000 or later (use explicit call)\n {\n hWinSpool = LoadLibrary(\"winspool.drv\");\n if (!hWinSpool)\n return FALSE;\n fnGetDefaultPrinter = GetProcAddress(hWinSpool, GETDEFAULTPRINTER);\n if (!fnGetDefaultPrinter)\n {\n FreeLibrary(hWinSpool);\n return FALSE;\n }\n\n bFlag = fnGetDefaultPrinter(pPrinterName, pdwBufferSize);\n FreeLibrary(hWinSpool);\n if (!bFlag)\n return FALSE;\n }\n\n else // NT4.0 or earlier\n {\n // Retrieve the default string from Win.ini (the registry).\n // String will be in form \"printername,drivername,portname\".\n if (GetProfileString(\"windows\", \"device\", \",,,\", cBuffer, MAXBUFFERSIZE) <= 0)\n return FALSE;\n\n // Printer name precedes first \",\" character.\n strtok(cBuffer, \",\");\n\n // If specified buffer is too small, set required size and fail.\n if ((DWORD)lstrlen(cBuffer) >= *pdwBufferSize)\n {\n *pdwBufferSize = (DWORD)lstrlen(cBuffer) + 1;\n return FALSE;\n }\n\n // Copy printer name into passed-in buffer.\n lstrcpy(pPrinterName, cBuffer);\n\n // Set buffer size parameter to minimum required buffer size.\n *pdwBufferSize = (DWORD)lstrlen(cBuffer) + 1;\n }\n }\n\n // Clean up.\n if (ppi2)\n GlobalFree(ppi2);\n\n return TRUE;\n}\n#undef MAXBUFFERSIZE\n#undef GETDEFAULTPRINTER\n\n\n// You are explicitly linking to SetDefaultPrinter because implicitly\n// linking on Windows 95/98 or NT4 results in a runtime error.\n// This block specifies which text version you explicitly link to.\n#ifdef UNICODE\n #define SETDEFAULTPRINTER \"SetDefaultPrinterW\"\n#else\n #define SETDEFAULTPRINTER \"SetDefaultPrinterA\"\n#endif\n\n/*-----------------------------------------------------------------*/ \n/* DPSetDefaultPrinter */ \n/* */ \n/* Parameters: */ \n/* pPrinterName: Valid name of existing printer to make default. */ \n/* */ \n/* Returns: TRUE for success, FALSE for failure. */ \n/*-----------------------------------------------------------------*/ \nBOOL DPSetDefaultPrinter(LPTSTR pPrinterName)\n\n{\n BOOL bFlag;\n OSVERSIONINFO osv;\n DWORD dwNeeded = 0;\n HANDLE hPrinter = NULL;\n PRINTER_INFO_2 *ppi2 = NULL;\n LPTSTR pBuffer = NULL;\n LONG lResult;\n HMODULE hWinSpool = NULL;\n PROC fnSetDefaultPrinter = NULL;\n\n // What version of Windows are you running?\n osv.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\n GetVersionEx(&osv);\n\n if (!pPrinterName)\n return FALSE;\n\n // If Windows 95 or 98, use SetPrinter.\n if (osv.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)\n {\n // Open this printer so you can get information about it.\n bFlag = OpenPrinter(pPrinterName, &hPrinter, NULL);\n if (!bFlag || !hPrinter)\n return FALSE;\n\n // The first GetPrinter() tells you how big our buffer must\n // be to hold ALL of PRINTER_INFO_2. Note that this will\n // typically return FALSE. This only means that the buffer (the 3rd\n // parameter) was not filled in. You do not want it filled in here.\n SetLastError(0);\n bFlag = GetPrinter(hPrinter, 2, 0, 0, &dwNeeded);\n if (!bFlag)\n {\n if ((GetLastError() != ERROR_INSUFFICIENT_BUFFER) || (dwNeeded == 0))\n {\n ClosePrinter(hPrinter);\n return FALSE;\n }\n }\n\n // Allocate enough space for PRINTER_INFO_2.\n ppi2 = (PRINTER_INFO_2 *)GlobalAlloc(GPTR, dwNeeded);\n if (!ppi2)\n {\n ClosePrinter(hPrinter);\n return FALSE;\n }\n\n // The second GetPrinter() will fill in all the current information\n // so that all you have to do is modify what you are interested in.\n bFlag = GetPrinter(hPrinter, 2, (LPBYTE)ppi2, dwNeeded, &dwNeeded);\n if (!bFlag)\n {\n ClosePrinter(hPrinter);\n GlobalFree(ppi2);\n return FALSE;\n }\n\n // Set default printer attribute for this printer.\n ppi2->Attributes |= PRINTER_ATTRIBUTE_DEFAULT;\n bFlag = SetPrinter(hPrinter, 2, (LPBYTE)ppi2, 0);\n if (!bFlag)\n {\n ClosePrinter(hPrinter);\n GlobalFree(ppi2);\n return FALSE;\n }\n\n // Tell all open programs that this change occurred. \n // Allow each program 1 second to handle this message.\n lResult = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0L,\n (LPARAM)(LPCTSTR)\"windows\", SMTO_NORMAL, 1000, NULL);\n }\n\n // If Windows NT, use the SetDefaultPrinter API for Windows 2000,\n // or WriteProfileString for version 4.0 and earlier.\n else if (osv.dwPlatformId == VER_PLATFORM_WIN32_NT)\n {\n if (osv.dwMajorVersion >= 5) // Windows 2000 or later (use explicit call)\n {\n hWinSpool = LoadLibrary(\"winspool.drv\");\n if (!hWinSpool)\n return FALSE;\n fnSetDefaultPrinter = GetProcAddress(hWinSpool, SETDEFAULTPRINTER);\n if (!fnSetDefaultPrinter)\n {\n FreeLibrary(hWinSpool);\n return FALSE;\n }\n\n bFlag = fnSetDefaultPrinter(pPrinterName);\n FreeLibrary(hWinSpool);\n if (!bFlag)\n return FALSE;\n }\n\n else // NT4.0 or earlier\n {\n // Open this printer so you can get information about it.\n bFlag = OpenPrinter(pPrinterName, &hPrinter, NULL);\n if (!bFlag || !hPrinter)\n return FALSE;\n\n // The first GetPrinter() tells you how big our buffer must\n // be to hold ALL of PRINTER_INFO_2. Note that this will\n // typically return FALSE. This only means that the buffer (the 3rd\n // parameter) was not filled in. You do not want it filled in here.\n SetLastError(0);\n bFlag = GetPrinter(hPrinter, 2, 0, 0, &dwNeeded);\n if (!bFlag)\n {\n if ((GetLastError() != ERROR_INSUFFICIENT_BUFFER) || (dwNeeded == 0))\n {\n ClosePrinter(hPrinter);\n return FALSE;\n }\n }\n\n // Allocate enough space for PRINTER_INFO_2.\n ppi2 = (PRINTER_INFO_2 *)GlobalAlloc(GPTR, dwNeeded);\n if (!ppi2)\n {\n ClosePrinter(hPrinter);\n return FALSE;\n }\n\n // The second GetPrinter() fills in all the current<BR/>\n // information.\n bFlag = GetPrinter(hPrinter, 2, (LPBYTE)ppi2, dwNeeded, &dwNeeded);\n if ((!bFlag) || (!ppi2->pDriverName) || (!ppi2->pPortName))\n {\n ClosePrinter(hPrinter);\n GlobalFree(ppi2);\n return FALSE;\n }\n\n // Allocate buffer big enough for concatenated string.\n // String will be in form \"printername,drivername,portname\".\n pBuffer = (LPTSTR)GlobalAlloc(GPTR,\n lstrlen(pPrinterName) +\n lstrlen(ppi2->pDriverName) +\n lstrlen(ppi2->pPortName) + 3);\n if (!pBuffer)\n {\n ClosePrinter(hPrinter);\n GlobalFree(ppi2);\n return FALSE;\n }\n\n // Build string in form \"printername,drivername,portname\".\n lstrcpy(pBuffer, pPrinterName); lstrcat(pBuffer, \",\");\n lstrcat(pBuffer, ppi2->pDriverName); lstrcat(pBuffer, \",\");\n lstrcat(pBuffer, ppi2->pPortName);\n\n // Set the default printer in Win.ini and registry.\n bFlag = WriteProfileString(\"windows\", \"device\", pBuffer);\n if (!bFlag)\n {\n ClosePrinter(hPrinter);\n GlobalFree(ppi2);\n GlobalFree(pBuffer);\n return FALSE;\n }\n }\n\n // Tell all open programs that this change occurred. \n // Allow each app 1 second to handle this message.\n lResult = SendMessageTimeout(HWND_BROADCAST, WM_SETTINGCHANGE, 0L, 0L,\n SMTO_NORMAL, 1000, NULL);\n }\n\n // Clean up.\n if (hPrinter)\n ClosePrinter(hPrinter);\n if (ppi2)\n GlobalFree(ppi2);\n if (pBuffer)\n GlobalFree(pBuffer);\n\n return TRUE;\n}\n#undef SETDEFAULTPRINTER\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104844",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8117/"
]
| I'm looking for a way to find the name of the Windows default printer using unmanaged C++ (found plenty of .NET examples, but no success unmanaged). Thanks. | The following works great for printing with the win32api from C++
```
char szPrinterName[255];
unsigned long lPrinterNameLength;
GetDefaultPrinter( szPrinterName, &lPrinterNameLength );
HDC hPrinterDC;
hPrinterDC = CreateDC("WINSPOOL\0", szPrinterName, NULL, NULL);
```
In the future instead of googling "unmanaged" try googling "win32 /subject/" or "win32 api /subject/" |
104,850 | <p>I want to try to convert a string to a Guid, but I don't want to rely on catching exceptions (</p>
<ul>
<li>for performance reasons - exceptions are expensive</li>
<li>for usability reasons - the debugger pops up </li>
<li>for design reasons - the expected is not exceptional</li>
</ul>
<p>In other words the code:</p>
<pre><code>public static Boolean TryStrToGuid(String s, out Guid value)
{
try
{
value = new Guid(s);
return true;
}
catch (FormatException)
{
value = Guid.Empty;
return false;
}
}
</code></pre>
<p>is not suitable.</p>
<p>I would try using RegEx, but since the guid can be parenthesis wrapped, brace wrapped, none wrapped, makes it hard. </p>
<p>Additionally, I thought certain Guid values are invalid(?)</p>
<hr>
<p><strong>Update 1</strong></p>
<p><a href="https://stackoverflow.com/questions/104850/c-test-if-string-is-a-guid-without-throwing-exceptions#137829">ChristianK</a> had a good idea to catch only <code>FormatException</code>, rather than all. Changed the question's code sample to include suggestion.</p>
<hr>
<p><strong>Update 2</strong></p>
<p>Why worry about thrown exceptions? Am I really expecting invalid GUIDs all that often? </p>
<p>The answer is <em>yes</em>. That is why I am using TryStrToGuid - I <strong>am</strong> expecting bad data.</p>
<p><strong>Example 1</strong> <a href="http://msdn.microsoft.com/en-us/library/cc144096(VS.85).aspx" rel="noreferrer">Namespace extensions can be specified by appending a GUID to a folder name</a>. I might be parsing folder names, checking to see if the text after the final <strong>.</strong> is a GUID.</p>
<pre><code>c:\Program Files
c:\Program Files.old
c:\Users
c:\Users.old
c:\UserManager.{CE7F5AA5-6832-43FE-BAE1-80D14CD8F666}
c:\Windows
c:\Windows.old
</code></pre>
<p><strong>Example 2</strong> I might be running a heavily used web-server wants to check the validity of some posted back data. I don't want invalid data tying up resources 2-3 orders of magnitude higher than it needs to be.</p>
<p><strong>Example 3</strong> I might be parsing a search expression entered by a user. </p>
<p><img src="https://i.stack.imgur.com/Ghb12.png" alt="enter image description here"></p>
<p>If they enter GUID's I want to process them specially (such as specifically searching for that object, or highlight and format that specific search term in the response text.)</p>
<hr>
<p><strong>Update 3 - Performance benchmarks</strong></p>
<p>Test converting 10,000 good Guids, and 10,000 bad Guids.</p>
<pre><code>Catch FormatException:
10,000 good: 63,668 ticks
10,000 bad: 6,435,609 ticks
Regex Pre-Screen with try-catch:
10,000 good: 637,633 ticks
10,000 bad: 717,894 ticks
COM Interop CLSIDFromString
10,000 good: 126,120 ticks
10,000 bad: 23,134 ticks
</code></pre>
<p><em>p.s. I shouldn't have to justify a question.</em></p>
| [
{
"answer_id": 104893,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "<p>Run the potential GUID though a RegEx or some custom code that does a sanity check to ensure the strig at least looks like a GUID and consists only of valid characters (and maybe that it seems to fit the overall format). If it doesn't pass the sanity check return an error - that'll probably weed out the vast majority of invalid strings.</p>\n\n<p>Then convert the string as you have above, still catching the exception for the few invalid strings that get through the sanity check.</p>\n\n<p>Jon Skeet did an analysis for something similar for parsing Ints (before TryParse was in the Framework): <a href=\"http://groups.google.com/group/microsoft.public.dotnet.framework/browse_thread/thread/3a72ac6eb7d88cc7/dc9241dff1dc524d?lnk=st&q=%22Checking+if+a+string+can+be+converted+to+Int32%22++jon+skeet#dc9241dff1dc524d\" rel=\"nofollow noreferrer\">Checking if a string can be converted to Int32</a></p>\n\n<p>However, as <a href=\"https://stackoverflow.com/questions/104850/c-test-if-string-is-a-guid-without-throwing-exceptions#104896\">AnthonyWJones</a> indicated you probably shouldn't be worrying about this.</p>\n"
},
{
"answer_id": 104896,
"author": "AnthonyWJones",
"author_id": 17516,
"author_profile": "https://Stackoverflow.com/users/17516",
"pm_score": 6,
"selected": false,
"text": "<p>You're not going to like this but what makes you think that catching the exception is going to be slower?</p>\n\n<p>How many failed attempts to parse a GUID are you expecting in comparison with successful ones?</p>\n\n<p>My advice is use the function you've just created and profile your code. If you find that this function is truely a hotspot <strong>then</strong> fix it but not before.</p>\n"
},
{
"answer_id": 104932,
"author": "pdavis",
"author_id": 7819,
"author_profile": "https://Stackoverflow.com/users/7819",
"pm_score": 3,
"selected": false,
"text": "<p>Well, here is the regex you will need...</p>\n\n<pre><code>^[A-Fa-f0-9]{32}$|^({|\\\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\\\))?$|^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$\n</code></pre>\n\n<p>But that is just for starters. You will also have to verify that the various parts such as the date/time are within acceptable ranges. I can't imagine this being any faster than the try/catch method that you have already outlined. Hopefully you aren't receiving that many invalid GUIDs to warrant this type of check!</p>\n"
},
{
"answer_id": 104947,
"author": "Ilya Ryzhenkov",
"author_id": 18575,
"author_profile": "https://Stackoverflow.com/users/18575",
"pm_score": 2,
"selected": false,
"text": "<p>As far as I know, there is no something like Guid.TryParse in mscrolib. According to Reference Source, Guid type has mega-complex constructor which checks all kinds of guid formats and tries to parse them. There is no helper method you can call, even via reflection. I think you have to search for 3rd party Guid parsers, or write your own.</p>\n"
},
{
"answer_id": 104962,
"author": "rupello",
"author_id": 635,
"author_profile": "https://Stackoverflow.com/users/635",
"pm_score": 1,
"selected": false,
"text": "<pre><code> bool IsProbablyGuid(string s)\n {\n int hexchars = 0;\n foreach(character c in string s)\n {\n if(IsValidHexChar(c)) \n hexchars++; \n }\n return hexchars==32;\n }\n</code></pre>\n"
},
{
"answer_id": 104972,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 3,
"selected": false,
"text": "<p>While it <em>is</em> true that using errors is more expensive, most people believe that a majority of their GUIDs are going to be computer generated so a <code>TRY-CATCH</code> isn't too expensive since it only generates cost on the <code>CATCH</code>. You can prove this to yourself with a simple test of the <a href=\"https://fserv-web.finsel.com:8443/svn/PublicSource/NET/Testing/TestGuidValidation\" rel=\"noreferrer\">two</a> (user public, no password). </p>\n\n<p>Here you go:</p>\n\n<pre><code>using System.Text.RegularExpressions;\n\n\n /// <summary>\n /// Validate that a string is a valid GUID\n /// </summary>\n /// <param name=\"GUIDCheck\"></param>\n /// <returns></returns>\n private bool IsValidGUID(string GUIDCheck)\n {\n if (!string.IsNullOrEmpty(GUIDCheck))\n {\n return new Regex(@\"^(\\{{0,1}([0-9a-fA-F]){8}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){4}-([0-9a-fA-F]){12}\\}{0,1})$\").IsMatch(GUIDCheck);\n }\n return false;\n }\n</code></pre>\n"
},
{
"answer_id": 137829,
"author": "Christian.K",
"author_id": 21567,
"author_profile": "https://Stackoverflow.com/users/21567",
"pm_score": 5,
"selected": false,
"text": "<p>I would at least rewrite it as:</p>\n\n<pre><code>try\n{\n value = new Guid(s);\n return true;\n}\ncatch (FormatException)\n{\n value = Guid.Empty;\n return false;\n}\n</code></pre>\n\n<p>You don't want to say \"invalid GUID\" on SEHException, ThreadAbortException or other fatal or non-related stuff.</p>\n\n<p><strong>Update</strong>: Starting with .NET 4.0, there is a new set of methods available for Guid:</p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.guid.tryparse(v=vs.100).aspx\" rel=\"noreferrer\"><code>Guid.TryParse</code></a></li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.guid.tryparseexact(v=vs.100).aspx\" rel=\"noreferrer\"><code>Guid.TryParseExact</code></a></li>\n</ul>\n\n<p>Really, those should be used (if only for the fact, that they are not \"naively\" implemented using try-catch internally).</p>\n"
},
{
"answer_id": 287877,
"author": "Ian Boyd",
"author_id": 12597,
"author_profile": "https://Stackoverflow.com/users/12597",
"pm_score": 8,
"selected": true,
"text": "<p><strong>Performance Benchmarks</strong></p>\n\n<pre><code>Catch exception:\n 10,000 good: 63,668 ticks\n 10,000 bad: 6,435,609 ticks\n\nRegex Pre-Screen:\n 10,000 good: 637,633 ticks\n 10,000 bad: 717,894 ticks\n\nCOM Interop CLSIDFromString\n 10,000 good: 126,120 ticks\n 10,000 bad: 23,134 ticks\n</code></pre>\n\n<p><strong>COM Intertop (Fastest) Answer:</strong></p>\n\n<pre><code>/// <summary>\n/// Attempts to convert a string to a guid.\n/// </summary>\n/// <param name=\"s\">The string to try to convert</param>\n/// <param name=\"value\">Upon return will contain the Guid</param>\n/// <returns>Returns true if successful, otherwise false</returns>\npublic static Boolean TryStrToGuid(String s, out Guid value)\n{\n //ClsidFromString returns the empty guid for null strings \n if ((s == null) || (s == \"\")) \n { \n value = Guid.Empty; \n return false; \n }\n\n int hresult = PInvoke.ObjBase.CLSIDFromString(s, out value);\n if (hresult >= 0)\n {\n return true;\n }\n else\n {\n value = Guid.Empty;\n return false;\n }\n}\n\n\nnamespace PInvoke\n{\n class ObjBase\n {\n /// <summary>\n /// This function converts a string generated by the StringFromCLSID function back into the original class identifier.\n /// </summary>\n /// <param name=\"sz\">String that represents the class identifier</param>\n /// <param name=\"clsid\">On return will contain the class identifier</param>\n /// <returns>\n /// Positive or zero if class identifier was obtained successfully\n /// Negative if the call failed\n /// </returns>\n [DllImport(\"ole32.dll\", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true)]\n public static extern int CLSIDFromString(string sz, out Guid clsid);\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Bottom line: If you need to check if a string is a guid, and you care about performance, use COM Interop. </p>\n\n<p>If you need to convert a guid in String representation to a Guid, use</p>\n\n<pre><code>new Guid(someString);\n</code></pre>\n"
},
{
"answer_id": 290730,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 4,
"selected": false,
"text": "<p>Interop is slower than just catching the exception:</p>\n\n<p>In the happy path, with 10,000 Guids:</p>\n\n<pre><code>Exception: 26ms\nInterop: 1,201ms\n</code></pre>\n\n<p>In the unhappy path:</p>\n\n<pre><code>Exception: 1,150ms\n Interop: 1,201ms\n</code></pre>\n\n<p>It's more consistent, but it's also consistently slower. Seems to me you'd be better off configuring your debugger to only break on unhandled exceptions.</p>\n"
},
{
"answer_id": 901607,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>if TypeOf ctype(myvar,Object) Is Guid then .....</p>\n"
},
{
"answer_id": 917135,
"author": "JMD",
"author_id": 55611,
"author_profile": "https://Stackoverflow.com/users/55611",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>for usability reasons - the debugger pops up</p>\n</blockquote>\n\n<p>If you're going for the try/catch approach you can add the [System.Diagnostics.DebuggerHidden] attribute to make sure the debugger doesn’t break even if you've set it to break on throw.</p>\n"
},
{
"answer_id": 917158,
"author": "THX-1138",
"author_id": 93422,
"author_profile": "https://Stackoverflow.com/users/93422",
"pm_score": 1,
"selected": false,
"text": "<ul>\n<li>Get Reflector</li>\n<li>copy'n'paste Guid's .ctor(String)</li>\n<li>replace every occurance of \"throw new ...\" with \"return false\". </li>\n</ul>\n\n<p>Guid's ctor is pretty much a compiled regex, that way you'll get exactly the same behavior without overhead of the exception.</p>\n\n<ol>\n<li>Does this constitute a reverse engineering? I think it does, and as such might be illegal.</li>\n<li>Will break if GUID form changes.</li>\n</ol>\n\n<p>Even cooler solution would be to dynamically instrument a method, by replacing \"throw new\" on the fly.</p>\n"
},
{
"answer_id": 1185400,
"author": "JBrooks",
"author_id": 136059,
"author_profile": "https://Stackoverflow.com/users/136059",
"pm_score": 3,
"selected": false,
"text": "<p>I had a similar situation and I noticed that almost never was the invalid string 36 characters long. So based on this fact, I changed your code a little to get better performance while still keeping it simple.</p>\n\n<pre><code>public static Boolean TryStrToGuid(String s, out Guid value)\n{\n\n // this is before the overhead of setting up the try/catch block.\n if(value == null || value.Length != 36)\n { \n value = Guid.Empty;\n return false;\n }\n\n try\n {\n value = new Guid(s);\n return true;\n }\n catch (FormatException)\n {\n value = Guid.Empty;\n return false;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1305659,
"author": "Stefan Steiger",
"author_id": 155077,
"author_profile": "https://Stackoverflow.com/users/155077",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Private Function IsGuidWithOptionalBraces(ByRef strValue As String) As Boolean\n If String.IsNullOrEmpty(strValue) Then\n Return False\n End If\n\n Return System.Text.RegularExpressions.Regex.IsMatch(strValue, \"^[\\{]?[0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}[\\}]?$\", System.Text.RegularExpressions.RegexOptions.IgnoreCase)\nEnd Function\n\n\nPrivate Function IsGuidWithoutBraces(ByRef strValue As String) As Boolean\n If String.IsNullOrEmpty(strValue) Then\n Return False\n End If\n\n Return System.Text.RegularExpressions.Regex.IsMatch(strValue, \"^[0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}$\", System.Text.RegularExpressions.RegexOptions.IgnoreCase)\nEnd Function\n\n\nPrivate Function IsGuidWithBraces(ByRef strValue As String) As Boolean\n If String.IsNullOrEmpty(strValue) Then\n Return False\n End If\n\n Return System.Text.RegularExpressions.Regex.IsMatch(strValue, \"^\\{[0-9a-fA-F]{8}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{4}\\-[0-9a-fA-F]{12}\\}$\", System.Text.RegularExpressions.RegexOptions.IgnoreCase)\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 1317296,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I vote for the GuidTryParse link posted above by <a href=\"https://stackoverflow.com/users/731/jon-sagara\">Jon</a> or a similar solution (IsProbablyGuid). I will be writing one like those for my Conversion library.</p>\n<p>I think it is totally lame that this question has to be so complicated. The "is" or "as" keyword would be just fine IF a Guid could be null. But for some reason, even though SQL Server is OK with that, .NET is not. Why? What is the value of Guid.Empty? This is just a silly problem created by the design of .NET, and it really bugs me when the conventions of a language step on itself. The best-performing answer so far has been using COM Interop because the Framework doesn't handle it gracefully? "Can this string be a GUID?" should be a question that is easy to answer.</p>\n<p>Relying on the exception being thrown is OK, until the app goes on the internet. At that point I just set myself up for a denial of service attack. Even if I don't get "attacked", I know some yahoo is going to monkey with the URL, or maybe my marketing department will send out a malformed link, and then my application has to suffer a fairly hefty performance hit that COULD bring down the server because I didn't write my code to handle a problem that SHOULDN'T happen, but we all know WILL HAPPEN.</p>\n<p>This blurs the line a bit on "Exception" - but bottom line, even if the problem is infrequent, if it can happen enough times in a short timespan that your application crashes servicing the catches from it all, then I think throwing an exception is bad form.</p>\n<p>TheRage3K</p>\n"
},
{
"answer_id": 1983992,
"author": "No Refunds No Returns",
"author_id": 210754,
"author_profile": "https://Stackoverflow.com/users/210754",
"pm_score": 7,
"selected": false,
"text": "<p>Once .net 4.0 is available you can use <a href=\"https://msdn.microsoft.com/en-us/library/system.guid.tryparse(v=vs.110).aspx\" rel=\"noreferrer\"><code>Guid.TryParse()</code></a>.</p>\n"
},
{
"answer_id": 6533282,
"author": "zhilia",
"author_id": 822813,
"author_profile": "https://Stackoverflow.com/users/822813",
"pm_score": 6,
"selected": false,
"text": "<p>In .NET 4.0 you can write as following:</p>\n\n<pre><code>public static bool IsValidGuid(string str)\n{\n Guid guid;\n return Guid.TryParse(str, out guid);\n}\n</code></pre>\n"
},
{
"answer_id": 45224630,
"author": "Mike",
"author_id": 649766,
"author_profile": "https://Stackoverflow.com/users/649766",
"pm_score": 0,
"selected": false,
"text": "<p>With an extension method in C#</p>\n\n<pre><code>public static bool IsGUID(this string text)\n{\n return Guid.TryParse(text, out Guid guid);\n}\n</code></pre>\n"
},
{
"answer_id": 69887837,
"author": "rajquest",
"author_id": 1834631,
"author_profile": "https://Stackoverflow.com/users/1834631",
"pm_score": 0,
"selected": false,
"text": "<p>Returns Guid value from string. If invalid Guid value then return Guid.Empty. Null value can't be returned because Guid is a struct type</p>\n<pre><code> /// <summary>\n /// Gets the GUID from string.\n /// </summary>\n /// <param name="guid">The GUID.</param>\n /// <returns></returns>\n public static Guid GetGuidFromString(string guid)\n {\n try\n {\n if (Guid.TryParse(guid, out Guid value))\n {\n return value;\n }\n else\n {\n return Guid.Empty;\n }\n }\n catch (Exception)\n {\n return Guid.Empty;\n }\n }\n</code></pre>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
]
| I want to try to convert a string to a Guid, but I don't want to rely on catching exceptions (
* for performance reasons - exceptions are expensive
* for usability reasons - the debugger pops up
* for design reasons - the expected is not exceptional
In other words the code:
```
public static Boolean TryStrToGuid(String s, out Guid value)
{
try
{
value = new Guid(s);
return true;
}
catch (FormatException)
{
value = Guid.Empty;
return false;
}
}
```
is not suitable.
I would try using RegEx, but since the guid can be parenthesis wrapped, brace wrapped, none wrapped, makes it hard.
Additionally, I thought certain Guid values are invalid(?)
---
**Update 1**
[ChristianK](https://stackoverflow.com/questions/104850/c-test-if-string-is-a-guid-without-throwing-exceptions#137829) had a good idea to catch only `FormatException`, rather than all. Changed the question's code sample to include suggestion.
---
**Update 2**
Why worry about thrown exceptions? Am I really expecting invalid GUIDs all that often?
The answer is *yes*. That is why I am using TryStrToGuid - I **am** expecting bad data.
**Example 1** [Namespace extensions can be specified by appending a GUID to a folder name](http://msdn.microsoft.com/en-us/library/cc144096(VS.85).aspx). I might be parsing folder names, checking to see if the text after the final **.** is a GUID.
```
c:\Program Files
c:\Program Files.old
c:\Users
c:\Users.old
c:\UserManager.{CE7F5AA5-6832-43FE-BAE1-80D14CD8F666}
c:\Windows
c:\Windows.old
```
**Example 2** I might be running a heavily used web-server wants to check the validity of some posted back data. I don't want invalid data tying up resources 2-3 orders of magnitude higher than it needs to be.
**Example 3** I might be parsing a search expression entered by a user.

If they enter GUID's I want to process them specially (such as specifically searching for that object, or highlight and format that specific search term in the response text.)
---
**Update 3 - Performance benchmarks**
Test converting 10,000 good Guids, and 10,000 bad Guids.
```
Catch FormatException:
10,000 good: 63,668 ticks
10,000 bad: 6,435,609 ticks
Regex Pre-Screen with try-catch:
10,000 good: 637,633 ticks
10,000 bad: 717,894 ticks
COM Interop CLSIDFromString
10,000 good: 126,120 ticks
10,000 bad: 23,134 ticks
```
*p.s. I shouldn't have to justify a question.* | **Performance Benchmarks**
```
Catch exception:
10,000 good: 63,668 ticks
10,000 bad: 6,435,609 ticks
Regex Pre-Screen:
10,000 good: 637,633 ticks
10,000 bad: 717,894 ticks
COM Interop CLSIDFromString
10,000 good: 126,120 ticks
10,000 bad: 23,134 ticks
```
**COM Intertop (Fastest) Answer:**
```
/// <summary>
/// Attempts to convert a string to a guid.
/// </summary>
/// <param name="s">The string to try to convert</param>
/// <param name="value">Upon return will contain the Guid</param>
/// <returns>Returns true if successful, otherwise false</returns>
public static Boolean TryStrToGuid(String s, out Guid value)
{
//ClsidFromString returns the empty guid for null strings
if ((s == null) || (s == ""))
{
value = Guid.Empty;
return false;
}
int hresult = PInvoke.ObjBase.CLSIDFromString(s, out value);
if (hresult >= 0)
{
return true;
}
else
{
value = Guid.Empty;
return false;
}
}
namespace PInvoke
{
class ObjBase
{
/// <summary>
/// This function converts a string generated by the StringFromCLSID function back into the original class identifier.
/// </summary>
/// <param name="sz">String that represents the class identifier</param>
/// <param name="clsid">On return will contain the class identifier</param>
/// <returns>
/// Positive or zero if class identifier was obtained successfully
/// Negative if the call failed
/// </returns>
[DllImport("ole32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true)]
public static extern int CLSIDFromString(string sz, out Guid clsid);
}
}
```
---
Bottom line: If you need to check if a string is a guid, and you care about performance, use COM Interop.
If you need to convert a guid in String representation to a Guid, use
```
new Guid(someString);
``` |
104,872 | <p>I'm working on a <code>PHP</code> application that links into the <code>Protx VSP Direct payment gateway</code>. To handle "3D Secure" requests from the credit card processing company, I need to forward the user to a different website, mimicking a form that has been posted. I'm trying to use the <code>cURL</code> libraries, but seem to have hit a problem. My code is the following: </p>
<pre><code><?php
$ch = curl_init();
// Set the URL
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/');
// Perform a POST
curl_setopt($ch, CURLOPT_POST, 1);
// If not set, curl prints output to the browser
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
// Set the "form fields"
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$output = curl_exec($ch);
curl_close($ch);
?>
</code></pre>
<p>All this does is grab the content of the URL passed through, and doesn't forward the user anywhere. I've tried Googling and reading up as much as I can, but can't figure out what i'm missing. Any ideas? I don't want to have to create a HTML form that auto-submits itself if I can avoid it.</p>
<p>Thanks for any help :-)</p>
| [
{
"answer_id": 104887,
"author": "neu242",
"author_id": 13365,
"author_profile": "https://Stackoverflow.com/users/13365",
"pm_score": 3,
"selected": true,
"text": "<p>The 3D Secure API doesn't allow you to do the request in the background. You need to forward the user to the 3D secure site. Use javascript to automatically submit your form. Here's what our provider suggests:</p>\n\n<pre><code><html> \n <head> \n <title>Processing your request...</title> \n </head> \n <body OnLoad=\"OnLoadEvent();\"> \n <form name=\"downloadForm\" action=\"<%=RedirURL%>\" method=\"POST\"> \n <noscript> \n <br> \n <br> \n <div align=\"center\"> \n <h1>Processing your 3-D Secure Transaction</h1> \n <h2>JavaScript is currently disabled or is not supported by your browser.</h2><BR> \n <h3>Please click Submit to continue the processing of your 3-D Secure transaction.</h3><BR> \n <input type=\"submit\" value=\"Submit\"> \n </div> \n </noscript> \n <input type=\"hidden\" name=\"PaReq\" value=\"<%=PAREQ%>\"> \n <input type=\"hidden\" name=\"MD\" value=\"<%=TransactionID%>\"> \n <input type=\"hidden\" name=\"TermUrl\" value=\"<%=TermUrl%>\"> \n </form> \n <SCRIPT LANGUAGE=\"Javascript\"> \n <!-- \n function OnLoadEvent() { \n document.downloadForm.submit(); \n } \n //--> \n </SCRIPT> \n </body> \n</html>\n</code></pre>\n"
},
{
"answer_id": 104908,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 0,
"selected": false,
"text": "<p>I think you are a bit confused as to what curl does. It does exactly what you explained, it acts sort of like a browser and makes the call to the site and returns the content of that post. I don't know of any way you can actually redirect the browser server side and represent a post. I would actually create a Javascript solution to do such a thing. </p>\n"
},
{
"answer_id": 104909,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 0,
"selected": false,
"text": "<p>To redirect a user to another page in PHP you can send a <code>header(\"Location: http://example.com/newpage\");</code>. However, unfortunately for your program redirection cause all POST variables to be removed (for security reasons). If you want to cause the user's browser to send a POST request to a different URL, you would have to create a form that submits itself. :(</p>\n"
},
{
"answer_id": 104913,
"author": "fistameeny",
"author_id": 19232,
"author_profile": "https://Stackoverflow.com/users/19232",
"pm_score": 0,
"selected": false,
"text": "<p>I'd much rather use something behind the scenes like cURL, as I can't guarantee my users will have JS enabled, and displaying a form causes some other problems I'd rather avoid. It's my plan B though ;-)</p>\n"
},
{
"answer_id": 104927,
"author": "Michael Ridley",
"author_id": 4838,
"author_profile": "https://Stackoverflow.com/users/4838",
"pm_score": 0,
"selected": false,
"text": "<p>You can use fsockopen() to redirect to the new web site while preserving your POST variables. There is a good tutorial on how to accomplish this <a href=\"http://www.faqts.com/knowledge_base/view.phtml/aid/12039/fid/51\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>In case that web site gets eaten by the Internet monster, I've copied and pasted the function but I suggest checking out the original web site for the context.</p>\n\n<pre><code>function sendToHost($host,$method,$path,$data,$useragent=0)\n{\n // Supply a default method of GET if the one passed was empty\n if (empty($method)) {\n $method = 'GET';\n }\n $method = strtoupper($method);\n $fp = fsockopen($host, 80);\n if ($method == 'GET') {\n $path .= '?' . $data;\n }\n fputs($fp, \"$method $path HTTP/1.1\\r\\n\");\n fputs($fp, \"Host: $host\\r\\n\");\n fputs($fp,\"Content-type: application/x-www-form- urlencoded\\r\\n\");\n fputs($fp, \"Content-length: \" . strlen($data) . \"\\r\\n\");\n if ($useragent) {\n fputs($fp, \"User-Agent: MSIE\\r\\n\");\n }\n fputs($fp, \"Connection: close\\r\\n\\r\\n\");\n if ($method == 'POST') {\n fputs($fp, $data);\n }\n\n while (!feof($fp)) {\n $buf .= fgets($fp,128);\n }\n fclose($fp);\n return $buf;\n}\n</code></pre>\n"
},
{
"answer_id": 104929,
"author": "fistameeny",
"author_id": 19232,
"author_profile": "https://Stackoverflow.com/users/19232",
"pm_score": 0,
"selected": false,
"text": "<p>Ah, if I've misunderstood what cURL does, I guess i'll settle for a HTML form with JS auto-submit. Creates quite a bit more work for me, but if it's the only way, i'll have to do it. </p>\n\n<p>Thanks for the help all.</p>\n"
},
{
"answer_id": 105089,
"author": "MarkR",
"author_id": 13724,
"author_profile": "https://Stackoverflow.com/users/13724",
"pm_score": 0,
"selected": false,
"text": "<p>I think in this case you need to use a form. The card payment companies web site needs to be visited by the user's browser, not your server-side code.</p>\n\n<p>Yes, 3dsecure etc, are quite annoying to integrate with, but they do provide a real security boost - use it as it's intended.</p>\n"
},
{
"answer_id": 105937,
"author": "Nathan Strong",
"author_id": 9780,
"author_profile": "https://Stackoverflow.com/users/9780",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe I'm missing something; it looks like you're trying to receive the user's data, forward it via cURL to the payment processor, and then redirect the user somewhere. Right?</p>\n\n<p>If so, all you need to do is just put this at the end of your code:</p>\n\n<p>header(\"Location: <a href=\"http://www.yoursite.com/yoururl\" rel=\"nofollow noreferrer\">http://www.yoursite.com/yoururl</a>\");</p>\n\n<p>However, for this to work, the script CANNOT send anything to the client while it is processing; that means that the script should not be executed in the middle of a template, and another gotcha is whitespace at the beginning of the file before the opening tag.</p>\n\n<p>If you need to save the data from the original POST transaction, use a session to save it.</p>\n\n<p>That should work for a JS-free solution.</p>\n"
},
{
"answer_id": 106296,
"author": "flungabunga",
"author_id": 11000,
"author_profile": "https://Stackoverflow.com/users/11000",
"pm_score": 0,
"selected": false,
"text": "<p>I may be utterly wrong but it sounds like you're trying to do something similar to the Proxy Pattern.</p>\n\n<p>I have implemented similar patterns for other sites I've worked with and it does require a bit of tinkering around to get right.</p>\n\n<p>I'd set the RETURN_TRANSFER to TRUE so that you can analyse the retrieved response and make application level actions depending on it. </p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Proxy_pattern\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Proxy_pattern</a></p>\n\n<p>Good luck.</p>\n"
},
{
"answer_id": 922355,
"author": "Chip Kaye",
"author_id": 101086,
"author_profile": "https://Stackoverflow.com/users/101086",
"pm_score": 0,
"selected": false,
"text": "<p>I found the sendToHost() function above very useful, but there is a typo in the source that took some time to debug: the Content-type header value contains a space between 'form-' and 'urlencoded' - should be 'application/x-www-form-urlencoded'</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19232/"
]
| I'm working on a `PHP` application that links into the `Protx VSP Direct payment gateway`. To handle "3D Secure" requests from the credit card processing company, I need to forward the user to a different website, mimicking a form that has been posted. I'm trying to use the `cURL` libraries, but seem to have hit a problem. My code is the following:
```
<?php
$ch = curl_init();
// Set the URL
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/');
// Perform a POST
curl_setopt($ch, CURLOPT_POST, 1);
// If not set, curl prints output to the browser
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
// Set the "form fields"
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$output = curl_exec($ch);
curl_close($ch);
?>
```
All this does is grab the content of the URL passed through, and doesn't forward the user anywhere. I've tried Googling and reading up as much as I can, but can't figure out what i'm missing. Any ideas? I don't want to have to create a HTML form that auto-submits itself if I can avoid it.
Thanks for any help :-) | The 3D Secure API doesn't allow you to do the request in the background. You need to forward the user to the 3D secure site. Use javascript to automatically submit your form. Here's what our provider suggests:
```
<html>
<head>
<title>Processing your request...</title>
</head>
<body OnLoad="OnLoadEvent();">
<form name="downloadForm" action="<%=RedirURL%>" method="POST">
<noscript>
<br>
<br>
<div align="center">
<h1>Processing your 3-D Secure Transaction</h1>
<h2>JavaScript is currently disabled or is not supported by your browser.</h2><BR>
<h3>Please click Submit to continue the processing of your 3-D Secure transaction.</h3><BR>
<input type="submit" value="Submit">
</div>
</noscript>
<input type="hidden" name="PaReq" value="<%=PAREQ%>">
<input type="hidden" name="MD" value="<%=TransactionID%>">
<input type="hidden" name="TermUrl" value="<%=TermUrl%>">
</form>
<SCRIPT LANGUAGE="Javascript">
<!--
function OnLoadEvent() {
document.downloadForm.submit();
}
//-->
</SCRIPT>
</body>
</html>
``` |
104,918 | <p>My question is related to the command pattern, where we have the following abstraction (C# code) :</p>
<pre><code>public interface ICommand
{
void Execute();
}
</code></pre>
<p>Let's take a simple concrete command, which aims to delete an entity from our application. A <code>Person</code> instance, for example.</p>
<p>I'll have a <code>DeletePersonCommand</code>, which implements <code>ICommand</code>. This command needs the <code>Person</code> to delete as a parameter, in order to delete it when <code>Execute</code> method is called.</p>
<p>What is the best way to manage parametrized commands ? How to pass parameters to commands, before executing them ?</p>
| [
{
"answer_id": 104934,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 3,
"selected": false,
"text": "<p>In the constructor and stored as fields.</p>\n\n<p>You will also want to eventually make your ICommands serializable for the undo stack or file persistence.</p>\n"
},
{
"answer_id": 104939,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 0,
"selected": false,
"text": "<p>DeletePersonCommand can have parameter in its constructor or methods . DeletePersonCommand will have the Execute() and in the execute can check attribute that will be passed by Getter/Setter previously the call of the Execute().</p>\n"
},
{
"answer_id": 104940,
"author": "Matt Dillard",
"author_id": 863,
"author_profile": "https://Stackoverflow.com/users/863",
"pm_score": 0,
"selected": false,
"text": "<p>I would add any necessary arguments to the constructor of <code>DeletePersonCommand</code>. Then, when <code>Execute()</code> is called, those parameters passed into the object at construction time are used.</p>\n"
},
{
"answer_id": 104946,
"author": "Joel Martinez",
"author_id": 5416,
"author_profile": "https://Stackoverflow.com/users/5416",
"pm_score": -1,
"selected": false,
"text": "<p>Have \"Person\" implement some sort of IDeletable interface, then make the command take whatever base class or interface your entities use. That way, you can make a DeleteCommand, which tries to cast the entity to an IDeletable, and if that works, call .Delete</p>\n\n<pre><code>public class DeleteCommand : ICommand\n{\n public void Execute(Entity entity)\n {\n IDeletable del = entity as IDeletable;\n if (del != null) del.Delete();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 104948,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 7,
"selected": true,
"text": "<p>You'll need to associate the parameters with the command object, either by constructor or setter injection (or equivalent). Perhaps something like this:</p>\n\n<pre><code>public class DeletePersonCommand: ICommand\n{\n private Person personToDelete;\n public DeletePersonCommand(Person personToDelete)\n {\n this.personToDelete = personToDelete;\n }\n\n public void Execute()\n {\n doSomethingWith(personToDelete);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 104949,
"author": "Juanma",
"author_id": 3730,
"author_profile": "https://Stackoverflow.com/users/3730",
"pm_score": 4,
"selected": false,
"text": "<p>There are some options:</p>\n\n<p>You could pass parameters by properties or constructor.</p>\n\n<p>Other option could be:</p>\n\n<pre><code>interface ICommand<T>\n{\n void Execute(T args);\n}\n</code></pre>\n\n<p>And encapsulate all command parameters in a value object.</p>\n"
},
{
"answer_id": 104985,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 3,
"selected": false,
"text": "<p>Pass the person when you create the command object:</p>\n\n<pre><code>ICommand command = new DeletePersonCommand(person);\n</code></pre>\n\n<p>so that when you execute the command, it already knows everything that it needs to know.</p>\n\n<pre><code>class DeletePersonCommand : ICommand\n{\n private Person person;\n public DeletePersonCommand(Person person)\n {\n this.person = person;\n }\n\n public void Execute()\n {\n RealDelete(person);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 104995,
"author": "user12786",
"author_id": 12786,
"author_profile": "https://Stackoverflow.com/users/12786",
"pm_score": 3,
"selected": false,
"text": "<p>In this case, what we've done with our Command objects is to create a Context object which is essentially a map. The map contains name value pairs where the keys are constants and the values are parameters that are used by the Command implementations. Especially useful if you have a Chain of Commands where later commands depend on context changes from earlier commands.</p>\n\n<p>So the actual method becomes</p>\n\n<pre><code>void execute(Context ctx);\n</code></pre>\n"
},
{
"answer_id": 105050,
"author": "TheZenker",
"author_id": 10552,
"author_profile": "https://Stackoverflow.com/users/10552",
"pm_score": 2,
"selected": false,
"text": "<p>Based on the pattern in C#/WPF the ICommand Interface (System.Windows.Input.ICommand) is defined to take an object as a parameter on the Execute, as well as the CanExecute method.</p>\n\n<pre><code>interface ICommand\n {\n bool CanExecute(object parameter);\n void Execute(object parameter);\n }\n</code></pre>\n\n<p>This allows you to define your command as a static public field which is an instance of your custom command object that implements ICommand.</p>\n\n<pre><code>public static ICommand DeleteCommand = new DeleteCommandInstance();\n</code></pre>\n\n<p>In this way the relevant object, in your case a person, is passed in when execute is called. The Execute method can then cast the object and call the Delete() method.</p>\n\n<pre><code>public void Execute(object parameter)\n {\n person target = (person)parameter;\n target.Delete();\n } \n</code></pre>\n"
},
{
"answer_id": 111250,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 2,
"selected": false,
"text": "<p>You should create a CommandArgs object to contain the parameters you want to use. Inject the CommandArgs object using the constructor of the Command object.</p>\n"
},
{
"answer_id": 136565,
"author": "Scott Stanchfield",
"author_id": 12541,
"author_profile": "https://Stackoverflow.com/users/12541",
"pm_score": 5,
"selected": false,
"text": "<p>Passing the data in via a constructor or setter works, but requires the creator of the command to know the data the command needs...</p>\n\n<p>The \"context\" idea is really good, and I was working on (an internal) framework that leveraged it a while back.</p>\n\n<p>If you set up your controller (UI components that interact with the user, CLI interpreting user commands, servlet interpreting incoming parameters and session data, etc) to provide named access to the available data, commands can directly ask for the data they want.</p>\n\n<p>I really like the separation a setup like this allows. Think about layering as follows:</p>\n\n<pre><code>User Interface (GUI controls, CLI, etc)\n |\n[syncs with/gets data]\n V\nController / Presentation Model\n | ^\n[executes] |\n V |\nCommands --------> [gets data by name]\n |\n[updates]\n V\nDomain Model\n</code></pre>\n\n<p>If you do this \"right\", the same commands and presentation model can be used with any type of user interface.</p>\n\n<p>Taking this a step further, the \"controller\" in the above is pretty generic. The UI controls only need to know the <em>name</em> of the command they'll invoke -- they (or the controller) don't need to have any knowledge of how to create that command or what data that command needs. That's the real advantage here.</p>\n\n<p>For example, you could hold the name of the command to execute in a Map. Whenever the component is \"triggered\" (usually an actionPerformed), the controller looks up the command name, instantiates it, calls execute, and pushes it on the undo stack (if you use one). </p>\n"
},
{
"answer_id": 2486070,
"author": "bloparod",
"author_id": 134559,
"author_profile": "https://Stackoverflow.com/users/134559",
"pm_score": 3,
"selected": false,
"text": "<p>My implementation would be this (using the ICommand proposed by Juanma):</p>\n\n<pre><code>public class DeletePersonCommand: ICommand<Person>\n{\n public DeletePersonCommand(IPersonService personService)\n { \n this.personService = personService;\n }\n\n public void Execute(Person person)\n {\n this.personService.DeletePerson(person);\n }\n}\n</code></pre>\n\n<p>IPersonService could be an IPersonRepository, it depends in what \"layer\" your command is.</p>\n"
},
{
"answer_id": 60908173,
"author": "Kostas Thanasis",
"author_id": 7296110,
"author_profile": "https://Stackoverflow.com/users/7296110",
"pm_score": 2,
"selected": false,
"text": "<p>Already mentioned code from Blair Conrad(don't know how to tag him) works perfectly fine <strong>if you know what person you want to delete when you instantiate the class</strong> and his method would suffice.But,if you don't know who you gonna delete until you press the button you can instantiate the command using a method reference that returns the person.</p>\n\n<pre><code> class DeletePersonCommand implements ICommand\n{\n private Supplier<Person> personSupplier;\n\n public DeletePersonCommand(Supplier<Person> personSupplier)\n {\n this.personSupplier = personSupplier;\n }\n\n public void Execute()\n {\n personSupplier.get().delete();\n }\n}\n</code></pre>\n\n<p>That way when the command is executed the supplier fetches the person you want to delete,doing so at the point of execution. Up until that time the command had no information of who to delete.</p>\n\n<p>Usefull <a href=\"https://stackoverflow.com/questions/38842853/what-is-the-c-equivalent-of-a-java-util-function-supplier\">link</a> on the supplier.</p>\n\n<p><strong>NOTE:code writen in java</strong> . Someone with c# knowledge can tune that.</p>\n"
}
]
| 2008/09/19 | [
"https://Stackoverflow.com/questions/104918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4687/"
]
| My question is related to the command pattern, where we have the following abstraction (C# code) :
```
public interface ICommand
{
void Execute();
}
```
Let's take a simple concrete command, which aims to delete an entity from our application. A `Person` instance, for example.
I'll have a `DeletePersonCommand`, which implements `ICommand`. This command needs the `Person` to delete as a parameter, in order to delete it when `Execute` method is called.
What is the best way to manage parametrized commands ? How to pass parameters to commands, before executing them ? | You'll need to associate the parameters with the command object, either by constructor or setter injection (or equivalent). Perhaps something like this:
```
public class DeletePersonCommand: ICommand
{
private Person personToDelete;
public DeletePersonCommand(Person personToDelete)
{
this.personToDelete = personToDelete;
}
public void Execute()
{
doSomethingWith(personToDelete);
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.